diff --git a/app/main/controller/accesscontroller.php b/app/main/controller/accesscontroller.php index 72f9772e..281cb325 100644 --- a/app/main/controller/accesscontroller.php +++ b/app/main/controller/accesscontroller.php @@ -9,7 +9,7 @@ namespace Controller; -use Model; +use Model\Pathfinder; class AccessController extends Controller { @@ -20,7 +20,7 @@ class AccessController extends Controller { * @return bool * @throws \Exception */ - function beforeroute(\Base $f3, $params): bool { + function beforeroute(\Base $f3, $params) : bool { if($return = parent::beforeroute($f3, $params)){ // Any route/endpoint of a child class of this one, // requires a valid logged in user! @@ -41,7 +41,7 @@ class AccessController extends Controller { * @return string * @throws \Exception */ - protected function isLoggedIn(\Base $f3): string { + protected function isLoggedIn(\Base $f3) : string { $loginStatus = 'UNKNOWN'; if($character = $this->getCharacter()){ if($character->checkLoginTimer()){ @@ -63,7 +63,7 @@ class AccessController extends Controller { $f3->get('DEBUG') === 3 ){ self::getLogger('CHARACTER_ACCESS')->write( - sprintf(Model\CharacterModel::LOG_ACCESS, + sprintf(Pathfinder\CharacterModel::LOG_ACCESS, $character->_id , $loginStatus, $character->name @@ -77,21 +77,21 @@ class AccessController extends Controller { /** * broadcast map data to clients * -> send over TCP Socket - * @param Model\MapModel $map + * @param Pathfinder\MapModel $map * @throws \Exception */ - protected function broadcastMapData(Model\MapModel $map) : void { + protected function broadcastMapData(Pathfinder\MapModel $map) : void { $mapData = $this->getFormattedMapData($map); $this->getF3()->webSocket()->write('mapUpdate', $mapData); } /** * get formatted Map Data - * @param Model\MapModel $map + * @param Pathfinder\MapModel $map * @return array * @throws \Exception */ - protected function getFormattedMapData(Model\MapModel $map){ + protected function getFormattedMapData(Pathfinder\MapModel $map) : array { $mapData = $map->getData(); return [ diff --git a/app/main/controller/admin.php b/app/main/controller/admin.php index 3a914f69..0ceccb00 100644 --- a/app/main/controller/admin.php +++ b/app/main/controller/admin.php @@ -1,7 +1,7 @@ timer = Config::getPathfinderData('timer'); // get all available map types ---------------------------------------------------------------------------- - $mapType = Model\BasicModel::getNew('MapTypeModel'); + $mapType = Pathfinder\AbstractPathfinderModel::getNew('MapTypeModel'); $rows = $mapType->find('active = 1'); // default map type config @@ -86,7 +88,7 @@ class Map extends Controller\AccessController { $validInitData = $validInitData ? !empty($mapTypeData) : $validInitData; // get all available map scopes --------------------------------------------------------------------------- - $mapScope = Model\BasicModel::getNew('MapScopeModel'); + $mapScope = Pathfinder\AbstractPathfinderModel::getNew('MapScopeModel'); $rows = $mapScope->find('active = 1'); $mapScopeData = []; foreach((array)$rows as $rowData){ @@ -101,7 +103,7 @@ class Map extends Controller\AccessController { $validInitData = $validInitData ? !empty($mapScopeData) : $validInitData; // get all available system status ------------------------------------------------------------------------ - $systemStatus = Model\BasicModel::getNew('SystemStatusModel'); + $systemStatus = Pathfinder\AbstractPathfinderModel::getNew('SystemStatusModel'); $rows = $systemStatus->find('active = 1'); $systemScopeData = []; foreach((array)$rows as $rowData){ @@ -117,7 +119,7 @@ class Map extends Controller\AccessController { $validInitData = $validInitData ? !empty($systemScopeData) : $validInitData; // get all available system types ------------------------------------------------------------------------- - $systemType = Model\BasicModel::getNew('SystemTypeModel'); + $systemType = Pathfinder\AbstractPathfinderModel::getNew('SystemTypeModel'); $rows = $systemType->find('active = 1'); $systemTypeData = []; foreach((array)$rows as $rowData){ @@ -132,7 +134,7 @@ class Map extends Controller\AccessController { $validInitData = $validInitData ? !empty($systemTypeData) : $validInitData; // get available connection scopes ------------------------------------------------------------------------ - $connectionScope = Model\BasicModel::getNew('ConnectionScopeModel'); + $connectionScope = Pathfinder\AbstractPathfinderModel::getNew('ConnectionScopeModel'); $rows = $connectionScope->find('active = 1'); $connectionScopeData = []; foreach((array)$rows as $rowData){ @@ -148,7 +150,7 @@ class Map extends Controller\AccessController { $validInitData = $validInitData ? !empty($connectionScopeData) : $validInitData; // get available character status ------------------------------------------------------------------------- - $characterStatus = Model\BasicModel::getNew('CharacterStatusModel'); + $characterStatus = Pathfinder\AbstractPathfinderModel::getNew('CharacterStatusModel'); $rows = $characterStatus->find('active = 1'); $characterStatusData = []; foreach((array)$rows as $rowData){ @@ -197,7 +199,7 @@ class Map extends Controller\AccessController { ]; // structure status --------------------------------------------------------------------------------------- - $structureStatus = Model\StructureStatusModel::getAll(); + $structureStatus = Pathfinder\StructureStatusModel::getAll(); $structureData = []; foreach($structureStatus as $status){ $structureData[$status->_id] = $status->getData(); @@ -208,9 +210,9 @@ class Map extends Controller\AccessController { // get available wormhole types --------------------------------------------------------------------------- /** - * @var $wormhole Model\Universe\WormholeModel + * @var $wormhole Universe\WormholeModel */ - $wormhole = Model\Universe\BasicUniverseModel::getNew('WormholeModel'); + $wormhole = Universe\AbstractUniverseModel::getNew('WormholeModel'); $wormholesData = []; if($rows = $wormhole->find(null, ['order' => 'name asc'])){ foreach($rows as $rowData){ @@ -227,9 +229,9 @@ class Map extends Controller\AccessController { // universe category data --------------------------------------------------------------------------------- /** - * @var $categoryUniverseModel Model\Universe\CategoryModel + * @var $categoryUniverseModel Universe\CategoryModel */ - $categoryUniverseModel = Model\Universe\BasicUniverseModel::getNew('CategoryModel'); + $categoryUniverseModel = Universe\AbstractUniverseModel::getNew('CategoryModel'); $categoryUniverseModel->getById(6); $shipData = $categoryUniverseModel->getData(['mass']); $categoryUniverseModel->getById(65); @@ -280,14 +282,14 @@ class Map extends Controller\AccessController { $activeCharacter = $this->getCharacter(); /** - * @var $map Model\MapModel + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); /** - * @var $mapType Model\MapTypeModel + * @var $mapType Pathfinder\MapTypeModel */ - $mapType = Model\BasicModel::getNew('MapTypeModel'); + $mapType = Pathfinder\AbstractPathfinderModel::getNew('MapTypeModel'); $mapType->getById((int)$importData['typeId']); if( !$mapType->dry() ){ @@ -302,9 +304,9 @@ class Map extends Controller\AccessController { $mapDataData = (array)$mapData['data']; /** - * @var $mapScope Model\MapScopeModel + * @var $mapScope Pathfinder\MapScopeModel */ - $mapScope = Model\BasicModel::getNew('MapScopeModel'); + $mapScope = Pathfinder\AbstractPathfinderModel::getNew('MapScopeModel'); $mapScope->getById((int)$mapDataConfig['scope']['id']); if( !$mapScope->dry() ){ @@ -340,9 +342,9 @@ class Map extends Controller\AccessController { } /** - * @var $connection Model\ConnectionModel + * @var $connection Pathfinder\ConnectionModel */ - $connection = Model\BasicModel::getNew('ConnectionModel'); + $connection = Pathfinder\AbstractPathfinderModel::getNew('ConnectionModel'); $connection->setActivityLogging(false); foreach($mapDataConnections as $connectionData){ @@ -437,9 +439,9 @@ class Map extends Controller\AccessController { $activeCharacter = $this->getCharacter(); /** - * @var $map Model\MapModel + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById( (int)$formData['id'] ); if( @@ -470,9 +472,9 @@ class Map extends Controller\AccessController { if($accessCharacters){ /** - * @var $tempCharacter Model\CharacterModel + * @var $tempCharacter Pathfinder\CharacterModel */ - $tempCharacter = Model\BasicModel::getNew('CharacterModel'); + $tempCharacter = Pathfinder\AbstractPathfinderModel::getNew('CharacterModel'); foreach($accessCharacters as $characterId){ $tempCharacter->getById( (int)$characterId ); @@ -513,9 +515,9 @@ class Map extends Controller\AccessController { if($accessCorporations){ /** - * @var $tempCorporation Model\CorporationModel + * @var $tempCorporation Pathfinder\CorporationModel */ - $tempCorporation = Model\BasicModel::getNew('CorporationModel'); + $tempCorporation = Pathfinder\AbstractPathfinderModel::getNew('CorporationModel'); foreach($accessCorporations as $corporationId){ $tempCorporation->getById( (int)$corporationId ); @@ -556,9 +558,9 @@ class Map extends Controller\AccessController { if($accessAlliances){ /** - * @var $tempAlliance Model\AllianceModel + * @var $tempAlliance Pathfinder\AllianceModel */ - $tempAlliance = Model\BasicModel::getNew('AllianceModel'); + $tempAlliance = Pathfinder\AbstractPathfinderModel::getNew('AllianceModel'); foreach($accessAlliances as $allianceId){ $tempAlliance->getById( (int)$allianceId ); @@ -623,9 +625,9 @@ class Map extends Controller\AccessController { $activeCharacter = $this->getCharacter(); /** - * @var $map Model\MapModel + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById($mapId); if($map->hasAccess($activeCharacter)){ @@ -644,10 +646,10 @@ class Map extends Controller\AccessController { /** * broadcast characters with map access rights to WebSocket server * -> if characters with map access found -> broadcast mapData to them - * @param Model\MapModel $map + * @param Pathfinder\MapModel $map * @throws Exception */ - protected function broadcastMapAccess(Model\MapModel $map){ + protected function broadcastMapAccess(Pathfinder\MapModel $map){ $mapAccess = [ 'id' => $map->_id, 'characterIds' => array_map(function ($data){ @@ -820,11 +822,11 @@ class Map extends Controller\AccessController { /** * get formatted map data - * @param Model\MapModel[] $mapModels + * @param Pathfinder\MapModel[] $mapModels * @return array * @throws Exception */ - protected function getFormattedMapsData($mapModels){ + protected function getFormattedMapsData(array $mapModels) : array { $mapData = []; foreach($mapModels as $mapModel){ $mapData[] = $this->getFormattedMapData($mapModel); @@ -905,12 +907,12 @@ class Map extends Controller\AccessController { /** * add new map connection based on current $character location - * @param Model\CharacterModel $character - * @param Model\MapModel $map - * @return Model\MapModel + * @param Pathfinder\CharacterModel $character + * @param Pathfinder\MapModel $map + * @return Pathfinder\MapModel * @throws Exception */ - protected function updateMapData(Model\CharacterModel $character, Model\MapModel $map){ + protected function updateMapData(Pathfinder\CharacterModel $character, Pathfinder\MapModel $map){ // map changed. update cache (system/connection) changed $mapDataChanged = false; @@ -944,14 +946,14 @@ class Map extends Controller\AccessController { // -> NO target system available if($sourceSystemId === $targetSystemId){ // check if previous (solo) system is already on the map - $sourceSystem = $map->getSystemByCCPId($sourceSystemId, [Model\BasicModel::getFilter('active', true)]); + $sourceSystem = $map->getSystemByCCPId($sourceSystemId, [AbstractModel::getFilter('active', true)]); $sameSystem = true; }else{ // check if previous (source) system is already on the map - $sourceSystem = $map->getSystemByCCPId($sourceSystemId, [Model\BasicModel::getFilter('active', true)]); + $sourceSystem = $map->getSystemByCCPId($sourceSystemId, [AbstractModel::getFilter('active', true)]); // -> check if system is already on this map - $targetSystem = $map->getSystemByCCPId($targetSystemId, [Model\BasicModel::getFilter('active', true)]); + $targetSystem = $map->getSystemByCCPId($targetSystemId, [AbstractModel::getFilter('active', true)]); } // if systems don´t already exists on map -> get "blank" system @@ -1131,9 +1133,9 @@ class Map extends Controller\AccessController { $activeCharacter = $this->getCharacter(); /** - * @var Model\MapModel $map + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById($mapId); if($map->hasAccess($activeCharacter)){ @@ -1187,9 +1189,9 @@ class Map extends Controller\AccessController { $activeCharacter = $this->getCharacter(); /** - * @var Model\MapModel $map + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById($mapId); if($map->hasAccess($activeCharacter)){ diff --git a/app/main/controller/api/rest/abstractrestcontroller.php b/app/main/controller/api/rest/abstractrestcontroller.php index 27a65497..1d0debea 100644 --- a/app/main/controller/api/rest/abstractrestcontroller.php +++ b/app/main/controller/api/rest/abstractrestcontroller.php @@ -1,7 +1,7 @@ getCharacter(); /** - * @var Model\MapModel $map + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById($mapId); if($map->hasAccess($activeCharacter)){ $source = $map->getSystemById((int)$requestData['source']); @@ -39,9 +39,9 @@ class Connection extends AbstractRestController { !is_null($target) ){ /** - * @var $connection Model\ConnectionModel + * @var $connection Pathfinder\ConnectionModel */ - $connection = Model\BasicModel::getNew('ConnectionModel'); + $connection = Pathfinder\AbstractPathfinderModel::getNew('ConnectionModel'); $connection->getById((int)$requestData['id']); $connection->mapId = $map; @@ -79,9 +79,9 @@ class Connection extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var Model\MapModel $map + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById($mapId); if($map->hasAccess($activeCharacter)){ foreach($connectionIds as $connectionId){ diff --git a/app/main/controller/api/rest/log.php b/app/main/controller/api/rest/log.php index e019ff5b..8b872f0c 100644 --- a/app/main/controller/api/rest/log.php +++ b/app/main/controller/api/rest/log.php @@ -1,14 +1,14 @@ getCharacter(); /** - * @var Model\ConnectionModel $connection + * @var $connection Pathfinder\ConnectionModel */ - $connection = Model\BasicModel::getNew('ConnectionModel'); + $connection = Pathfinder\AbstractPathfinderModel::getNew('ConnectionModel'); $connection->getById($connectionId); if($connection->hasAccess($activeCharacter)){ @@ -84,7 +84,7 @@ class Log extends AbstractRestController { * update existing connectionLog with new data * @param int $logId * @param array $logData - * @return bool|Model\ConnectionLogModel + * @return bool|Pathfinder\ConnectionLogModel * @throws \Exception */ private function update(int $logId, array $logData){ @@ -92,9 +92,9 @@ class Log extends AbstractRestController { if($logId){ $activeCharacter = $this->getCharacter(); /** - * @var Model\ConnectionLogModel $log + * @var $log Pathfinder\ConnectionLogModel */ - $log = Model\BasicModel::getNew('ConnectionLogModel'); + $log = Pathfinder\AbstractPathfinderModel::getNew('ConnectionLogModel'); $log->getById($logId, 0, false); if($log->hasAccess($activeCharacter)){ diff --git a/app/main/controller/api/rest/signature.php b/app/main/controller/api/rest/signature.php index dc846cad..00edec02 100644 --- a/app/main/controller/api/rest/signature.php +++ b/app/main/controller/api/rest/signature.php @@ -9,7 +9,7 @@ namespace Controller\Api\Rest; -use Model; +use Model\Pathfinder; class Signature extends AbstractRestController { @@ -26,9 +26,9 @@ class Signature extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $system Model\SystemModel + * @var $system Pathfinder\SystemModel */ - $system = Model\BasicModel::getNew('SystemModel'); + $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $system->getById($systemId, 0); if($system->hasAccess($activeCharacter)){ // if there is any changed/deleted/updated signature @@ -112,9 +112,9 @@ class Signature extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $system Model\SystemModel + * @var $system Pathfinder\SystemModel */ - $system = Model\BasicModel::getNew('SystemModel'); + $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $system->getById($systemId); if($system->hasAccess($activeCharacter)){ $signature = $system->getNewSignature(); @@ -143,9 +143,9 @@ class Signature extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $signature Model\SystemSignatureModel + * @var $signature Pathfinder\SystemSignatureModel */ - $signature = Model\BasicModel::getNew('SystemSignatureModel'); + $signature = Pathfinder\AbstractPathfinderModel::getNew('SystemSignatureModel'); $signature->getById($signatureId); if($signature->hasAccess($activeCharacter)){ // if groupId changed @@ -183,9 +183,9 @@ class Signature extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $system Model\SystemModel + * @var $system Pathfinder\SystemModel */ - $system = Model\BasicModel::getNew('SystemModel'); + $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $system->getById($systemId); if($system->hasAccess($activeCharacter)){ @@ -194,7 +194,7 @@ class Signature extends AbstractRestController { $updateSignaturesHistory = false; /** - * @var Model\SystemSignatureModel $signature + * @var $signature Pathfinder\SystemSignatureModel */ $signature = $system->rel('signatures'); foreach($signatureIds as $signatureId){ diff --git a/app/main/controller/api/rest/signaturehistory.php b/app/main/controller/api/rest/signaturehistory.php index 4ad07352..3c78b91e 100644 --- a/app/main/controller/api/rest/signaturehistory.php +++ b/app/main/controller/api/rest/signaturehistory.php @@ -9,7 +9,7 @@ namespace Controller\Api\Rest; -use Model; +use Model\Pathfinder; use lib\Config; class SignatureHistory extends AbstractRestController { @@ -27,9 +27,9 @@ class SignatureHistory extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $system Model\SystemModel + * @var $system Pathfinder\SystemModel */ - $system = Model\BasicModel::getNew('SystemModel'); + $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $system->getById($systemId); if($system->hasAccess($activeCharacter)){ @@ -69,9 +69,9 @@ class SignatureHistory extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $system Model\SystemModel + * @var $system Pathfinder\SystemModel */ - $system = Model\BasicModel::getNew('SystemModel'); + $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $system->getById($systemId, 0); if($system->hasAccess($activeCharacter)){ if($historyEntry = $system->getSignatureHistoryData($stamp)){ diff --git a/app/main/controller/api/rest/structure.php b/app/main/controller/api/rest/structure.php index 7b87cc90..b100d77e 100644 --- a/app/main/controller/api/rest/structure.php +++ b/app/main/controller/api/rest/structure.php @@ -9,7 +9,7 @@ namespace Controller\Api\Rest; -use Model; +use Model\Pathfinder; class Structure extends AbstractRestController { @@ -55,9 +55,9 @@ class Structure extends AbstractRestController { if($structureId = (int)$params['id']){ $activeCharacter = $this->getCharacter(); /** - * @var $structure Model\StructureModel + * @var $structure Pathfinder\StructureModel */ - $structure = Model\BasicModel::getNew('StructureModel'); + $structure = Pathfinder\AbstractPathfinderModel::getNew('StructureModel'); $structure->getById($structureId); if($structure->hasAccess($activeCharacter) && $structure->erase()){ $deletedStructureIds[] = $structureId; @@ -78,9 +78,9 @@ class Structure extends AbstractRestController { if($activeCharacter->hasCorporation()){ // structures always belong to a corporation /** - * @var $structure Model\StructureModel + * @var $structure Pathfinder\StructureModel */ - $structure = Model\BasicModel::getNew('StructureModel'); + $structure = Pathfinder\AbstractPathfinderModel::getNew('StructureModel'); foreach($structuresData as $structureData){ // reset on loop start because of potential "continue" $structure->reset(); diff --git a/app/main/controller/api/rest/system.php b/app/main/controller/api/rest/system.php index 3ad9706a..94b5fe3e 100644 --- a/app/main/controller/api/rest/system.php +++ b/app/main/controller/api/rest/system.php @@ -9,7 +9,7 @@ namespace Controller\Api\Rest; -use Model; +use Model\Pathfinder; class System extends AbstractRestController { @@ -57,9 +57,9 @@ class System extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $map Model\MapModel + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById($mapId); if($map->hasAccess($activeCharacter)){ $system = $map->getNewSystem($requestData['systemId']); @@ -84,9 +84,9 @@ class System extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var $system Model\SystemModel + * @var $system Pathfinder\SystemModel */ - $system = Model\BasicModel::getNew('SystemModel'); + $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $system->getById($systemId); if($system->hasAccess($activeCharacter)){ @@ -111,13 +111,13 @@ class System extends AbstractRestController { $activeCharacter = $this->getCharacter(); /** - * @var Model\MapModel $map + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); $map->getById($mapId); if($map->hasAccess($activeCharacter)){ - $newSystemModel = Model\BasicModel::getNew('SystemModel'); + $newSystemModel = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); foreach($systemIds as $systemId){ if($system = $map->getSystemById($systemId)){ // check whether system should be deleted OR set "inactive" @@ -156,12 +156,12 @@ class System extends AbstractRestController { /** * update system with new data - * @param Model\SystemModel $system + * @param Pathfinder\SystemModel $system * @param array $systemData - * @return Model\SystemModel + * @return Pathfinder\SystemModel * @throws \Exception */ - private function update(Model\SystemModel $system, array $systemData) : Model\SystemModel { + private function update(Pathfinder\SystemModel $system, array $systemData) : Pathfinder\SystemModel { $activeCharacter = $this->getCharacter(); // statusId === 0 is 'auto' status -> keep current status @@ -180,9 +180,9 @@ class System extends AbstractRestController { // get data from "fresh" model (e.g. some relational data has changed: "statusId") /** - * @var $newSystem Model\SystemModel + * @var $newSystem Pathfinder\SystemModel */ - $newSystem = Model\BasicModel::getNew('SystemModel'); + $newSystem = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $newSystem->getById($system->_id, 0); $newSystem->clearCacheData(); @@ -194,11 +194,11 @@ class System extends AbstractRestController { /** * checks whether a system should be "deleted" or set "inactive" (keep some data) - * @param Model\MapModel $map - * @param Model\SystemModel $system + * @param Pathfinder\MapModel $map + * @param Pathfinder\SystemModel $system * @return bool */ - private function checkDeleteMode(Model\MapModel $map, Model\SystemModel $system) : bool { + private function checkDeleteMode(Pathfinder\MapModel $map, Pathfinder\SystemModel $system) : bool { $delete = true; if( !empty($system->description) ){ diff --git a/app/main/controller/api/route.php b/app/main/controller/api/route.php index 68415bff..0650994b 100644 --- a/app/main/controller/api/route.php +++ b/app/main/controller/api/route.php @@ -11,7 +11,7 @@ namespace Controller\Api; use Controller; use Controller\Ccp\Universe; use lib\Config; -use Model; +use Model\Pathfinder; /** * Routes controller @@ -20,6 +20,9 @@ use Model; */ class Route extends Controller\AccessController { + /** + * route search depth + */ const ROUTE_SEARCH_DEPTH_DEFAULT = 1; /** @@ -670,9 +673,9 @@ class Route extends Controller\AccessController { $validMaps = []; /** - * @var $map Model\MapModel + * @var $map Pathfinder\MapModel */ - $map = Model\BasicModel::getNew('MapModel'); + $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); // limit max search routes to max limit array_splice($routesData, Config::getPathfinderData('route.limit')); @@ -686,7 +689,7 @@ class Route extends Controller\AccessController { // check map access (filter requested mapIDs and format) ---------------------------------------------- array_walk($mapData, function(&$item, &$key, $data){ /** - * @var Model\MapModel $data[0] + * @var Pathfinder\MapModel $data[0] */ if( isset($data[1][$key]) ){ // character has map access -> do not check again diff --git a/app/main/controller/api/setup.php b/app/main/controller/api/setup.php index 10620abf..a14d1109 100644 --- a/app/main/controller/api/setup.php +++ b/app/main/controller/api/setup.php @@ -1,7 +1,7 @@ setupCategory($categoryId, $offset, $length); - $categoryUniverseModel = Model\Universe\BasicUniverseModel::getNew('CategoryModel'); + $categoryUniverseModel = Model\Universe\AbstractUniverseModel::getNew('CategoryModel'); $categoryUniverseModel->getById($categoryId, 0); $return->countAll = (int)$f3->get('REQUIREMENTS.DATA.STRUCTURES'); $return->countBuild = array_reduce($buildInfo, $sum, 0); @@ -88,7 +87,7 @@ class Setup extends Controller\Controller { $offset = $count * $length; $buildInfo = $controller->setupCategory($categoryId, $offset, $length); - $categoryUniverseModel = Model\Universe\BasicUniverseModel::getNew('CategoryModel'); + $categoryUniverseModel = Model\Universe\AbstractUniverseModel::getNew('CategoryModel'); $categoryUniverseModel->getById($categoryId, 0); $return->countAll = (int)$f3->get('REQUIREMENTS.DATA.SHIPS'); $return->countBuild = array_reduce($buildInfo, $sum, 0); @@ -100,7 +99,7 @@ class Setup extends Controller\Controller { $this->setupSystemJumpTable(); $return->countAll = (int)$f3->get('REQUIREMENTS.DATA.NEIGHBOURS'); - $return->countBuild = Database::instance()->getRowCount('system_neighbour'); + $return->countBuild = $f3->DB->getDB('PF')->getRowCount('system_neighbour'); $return->countBuildAll = $return->countBuild; $return->progress = $percent($return->countAll, $return->countBuildAll); break; @@ -135,8 +134,8 @@ class Setup extends Controller\Controller { switch($type) { case 'Systems': $controller->clearSystemsIndex(); - $systemUniverseModel = Model\Universe\BasicUniverseModel::getNew('SystemModel'); - $return->countAll = Database::instance()->getRowCount($systemUniverseModel->getTable(), 'UNIVERSE'); + $systemUniverseModel = Model\Universe\AbstractUniverseModel::getNew('SystemModel'); + $return->countAll = $f3->DB->getDB('UNIVERSE')->getRowCount($systemUniverseModel->getTable()); break; } diff --git a/app/main/controller/api/statistic.php b/app/main/controller/api/statistic.php index b002adb2..e8fed3b8 100644 --- a/app/main/controller/api/statistic.php +++ b/app/main/controller/api/statistic.php @@ -10,7 +10,7 @@ namespace controller\api; use Controller; use lib\Config; -use Model\CharacterModel; +use Model\Pathfinder\CharacterModel; class Statistic extends Controller\AccessController { @@ -31,10 +31,14 @@ class Statistic extends Controller\AccessController { * @param $year * @return int */ - protected function getIsoWeeksInYear($year) { - $date = new \DateTime; - $date->setISODate($year, 53); - return ($date->format('W') === '53' ? 53 : 52); + protected function getIsoWeeksInYear($year){ + $week = 0; + try{ + $date = new \DateTime; + $date->setISODate($year, 53); + $week = ($date->format('W') === '53' ? 53 : 52); + }catch(\Exception $e){} + return $week; } /** @@ -124,7 +128,7 @@ class Statistic extends Controller\AccessController { * @param int $weekEnd * @return array */ - protected function queryStatistic( CharacterModel $character, $typeId, $yearStart, $weekStart, $yearEnd, $weekEnd){ + protected function queryStatistic(CharacterModel $character, $typeId, $yearStart, $weekStart, $yearEnd, $weekEnd){ $data = []; // can be either "characterId" || "corporationId" || "allianceId" @@ -281,9 +285,9 @@ class Statistic extends Controller\AccessController { $offsetPrev = $this->calculateYearWeekOffset($yearStart, $weekStart, $weekCount + 1, true); // check if "next" button is available (not in future) - $currentCurrentDataConcat = intval( $this->concatYearWeek($currentYear, $currentWeek) ); - $offsetNextDateConcat = intval( $this->concatYearWeek($offsetNext['year'], $offsetNext['week']) ); - if( $offsetNextDateConcat <= $currentCurrentDataConcat){ + $currentCurrentDataConcat = intval($this->concatYearWeek($currentYear, $currentWeek)); + $offsetNextDateConcat = intval($this->concatYearWeek($offsetNext['year'], $offsetNext['week'])); + if($offsetNextDateConcat <= $currentCurrentDataConcat){ $return->next = $offsetNext; } diff --git a/app/main/controller/api/system.php b/app/main/controller/api/system.php index cdc77a59..1b80de87 100644 --- a/app/main/controller/api/system.php +++ b/app/main/controller/api/system.php @@ -9,7 +9,7 @@ namespace Controller\Api; use Controller; -use Model; +use Model\Pathfinder; class System extends Controller\AccessController { @@ -58,7 +58,7 @@ class System extends Controller\AccessController { $cacheSystem = false; foreach($logTables as $label => $ModelClass){ - $systemLogModel = Model\BasicModel::getNew($ModelClass); + $systemLogModel = Pathfinder\AbstractPathfinderModel::getNew($ModelClass); $systemLogExists = false; // 10min cache (could be up to 1h cache time) @@ -167,9 +167,9 @@ class System extends Controller\AccessController { $activeCharacter = $this->getCharacter(); /** - * @var Model\SystemModel $system + * @var $system Pathfinder\SystemModel */ - $system = Model\BasicModel::getNew('SystemModel'); + $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel'); $system->getById($systemId); if($system->hasAccess($activeCharacter)){ diff --git a/app/main/controller/api/universe.php b/app/main/controller/api/universe.php index e59e580b..559d0347 100644 --- a/app/main/controller/api/universe.php +++ b/app/main/controller/api/universe.php @@ -1,7 +1,7 @@ = 3 ){ $offset = ($page - 1) * self::PAGE_SIZE_SYSTEMS; - $system = Model\Universe\BasicUniverseModel::getNew('SystemModel'); + $system = Model\Universe\AbstractUniverseModel::getNew('SystemModel'); $filter = [ 'id LIKE :id OR name LIKE :name', @@ -110,7 +110,7 @@ class Universe extends Controller\AccessController { $return->error = []; $return->systemsData = []; - $constellation = Model\Universe\BasicUniverseModel::getNew('ConstellationModel'); + $constellation = Model\Universe\AbstractUniverseModel::getNew('ConstellationModel'); $constellation->getById($constellationId); if( !$constellation->dry() && $constellation->systems){ /** diff --git a/app/main/controller/api/user.php b/app/main/controller/api/user.php index c645bb16..c6d41901 100644 --- a/app/main/controller/api/user.php +++ b/app/main/controller/api/user.php @@ -7,8 +7,10 @@ */ namespace Controller\Api; + + use Controller; -use Model; +use Model\Pathfinder; use Exception; class User extends Controller\Controller{ @@ -41,11 +43,11 @@ class User extends Controller\Controller{ /** * login a valid character - * @param Model\CharacterModel $character + * @param Pathfinder\CharacterModel $character * @return bool * @throws Exception */ - protected function loginByCharacter(Model\CharacterModel &$character) : bool { + protected function loginByCharacter(Pathfinder\CharacterModel &$character) : bool { $login = false; if($user = $character->getUser()){ diff --git a/app/main/controller/appcontroller.php b/app/main/controller/appcontroller.php index 6079c365..81723a21 100644 --- a/app/main/controller/appcontroller.php +++ b/app/main/controller/appcontroller.php @@ -14,7 +14,12 @@ use lib\Resource; class AppController extends Controller { - public function beforeroute(\Base $f3, $params) : bool{ + /** + * @param \Base $f3 + * @param $params + * @return bool + */ + public function beforeroute(\Base $f3, $params) : bool { // page title $f3->set('tplPageTitle', Config::getPathfinderData('name')); @@ -58,7 +63,7 @@ class AppController extends Controller { * show main login (index) page * @param \Base $f3 */ - public function init(\Base $f3) { + public function init(\Base $f3){ $resource = Resource::instance(); $resource->register('script', 'app/login'); $resource->register('script', 'app/mappage', 'prefetch'); diff --git a/app/main/controller/ccp/sso.php b/app/main/controller/ccp/sso.php index df1615d0..d55ff30b 100644 --- a/app/main/controller/ccp/sso.php +++ b/app/main/controller/ccp/sso.php @@ -15,7 +15,7 @@ namespace Controller\Ccp; use Controller; use Controller\Api as Api; -use Model; +use Model\Pathfinder; use Lib; class Sso extends Api\User{ @@ -74,9 +74,9 @@ class Sso extends Api\User{ $characterId = (int)trim((string)$params['characterId']); /** - * @var Model\CharacterModel $character + * @var $character Pathfinder\CharacterModel */ - $character = Model\BasicModel::getNew('CharacterModel'); + $character = Pathfinder\AbstractPathfinderModel::getNew('CharacterModel'); $character->getById($characterId, 0); // check if character is valid and exists @@ -222,19 +222,19 @@ class Sso extends Api\User{ if( is_null( $user = $characterModel->getUser()) ){ // no user found (new character) -> create new user and connect to character /** - * @var $user Model\UserModel + * @var $user Pathfinder\UserModel */ - $user = Model\BasicModel::getNew('UserModel'); + $user = Pathfinder\AbstractPathfinderModel::getNew('UserModel'); $user->name = $characterModel->name; $user->save(); } } /** - * @var $userCharactersModel Model\UserCharacterModel + * @var $userCharactersModel Pathfinder\UserCharacterModel */ if( is_null($userCharactersModel = $characterModel->userCharacter) ){ - $userCharactersModel = Model\BasicModel::getNew('UserCharacterModel'); + $userCharactersModel = Pathfinder\AbstractPathfinderModel::getNew('UserCharacterModel'); $userCharactersModel->characterId = $characterModel; } @@ -265,7 +265,7 @@ class Sso extends Api\User{ }else{ // character is not authorized to log in $f3->set(self::SESSION_KEY_SSO_ERROR, - sprintf(self::ERROR_CHARACTER_FORBIDDEN, $characterModel->name, Model\CharacterModel::AUTHORIZATION_STATUS[$authStatus]) + sprintf(self::ERROR_CHARACTER_FORBIDDEN, $characterModel->name, Pathfinder\CharacterModel::AUTHORIZATION_STATUS[$authStatus]) ); } } @@ -465,9 +465,9 @@ class Sso extends Api\User{ if($corporationId = (int)$characterDataBasic['corporation']['id']){ /** - * @var Model\CorporationModel $corporation + * @var $corporation Pathfinder\CorporationModel */ - $corporation = Model\BasicModel::getNew('CorporationModel'); + $corporation = Pathfinder\AbstractPathfinderModel::getNew('CorporationModel'); $corporation->getById($corporationId, 0); if( !$corporation->dry() ){ $characterData->corporation = $corporation; @@ -476,9 +476,9 @@ class Sso extends Api\User{ if($allianceId = (int)$characterDataBasic['alliance']['id']){ /** - * @var Model\AllianceModel $allianceModel + * @var $alliance Pathfinder\AllianceModel */ - $alliance = Model\BasicModel::getNew('AllianceModel'); + $alliance = Pathfinder\AbstractPathfinderModel::getNew('AllianceModel'); $alliance->getById($allianceId, 0); if( !$alliance->dry() ){ $characterData->alliance = $alliance; @@ -493,17 +493,17 @@ class Sso extends Api\User{ /** * update character * @param \stdClass $characterData - * @return \Model\CharacterModel|null + * @return Pathfinder\CharacterModel|null * @throws \Exception */ - protected function updateCharacter(\stdClass $characterData){ + protected function updateCharacter(\stdClass $characterData) : ?Pathfinder\CharacterModel { $character = null; if( !empty($characterData->character) ){ /** - * @var Model\CharacterModel $character + * @var $character Pathfinder\CharacterModel */ - $character = Model\BasicModel::getNew('CharacterModel'); + $character = Pathfinder\AbstractPathfinderModel::getNew('CharacterModel'); $character->getById((int)$characterData->character['id'], 0); $character->copyfrom($characterData->character, [ 'id', 'name', 'ownerHash', 'esiAccessToken', 'esiAccessTokenExpires', 'esiRefreshToken', 'esiScopes', 'securityStatus' diff --git a/app/main/controller/ccp/universe.php b/app/main/controller/ccp/universe.php index cd3be2a0..94f1a142 100644 --- a/app/main/controller/ccp/universe.php +++ b/app/main/controller/ccp/universe.php @@ -1,7 +1,7 @@ 93 systems) ]; $regionIds = $f3->ccpClient()->getUniverseRegions(); - $regionIds = array_intersect ($regionsWhitelist, $regionIds); + $regionIds = array_intersect($regionsWhitelist, $regionIds); - $region = Model\Universe\BasicUniverseModel::getNew('RegionModel'); + $region = Model\Universe\AbstractUniverseModel::getNew('RegionModel'); foreach($regionIds as $regionId){ $region->loadById($regionId); $region->loadConstellationsData(); @@ -44,8 +44,8 @@ class Universe extends Controller { 20000014 // Mal (11 systems) ]; $constellationIds = $f3->ccpClient()->getUniverseConstellations(); - $constellationIds = array_intersect ($constellationsWhitelist, $constellationIds); - $constellation = Model\Universe\BasicUniverseModel::getNew('ConstellationModel'); + $constellationIds = array_intersect($constellationsWhitelist, $constellationIds); + $constellation = Model\Universe\AbstractUniverseModel::getNew('ConstellationModel'); foreach($constellationIds as $constellationId){ $constellation->loadById($constellationId); $constellation->loadSystemsData(); @@ -62,13 +62,13 @@ class Universe extends Controller { * @return array * @throws \Exception */ - public function setupCategory(int $categoryId, int $offset = 0, int $length = 0){ + public function setupCategory(int $categoryId, int $offset = 0, int $length = 0) : array { $return = []; if($categoryId){ /** * @var $category Model\Universe\CategoryModel */ - $category = Model\Universe\BasicUniverseModel::getNew('CategoryModel'); + $category = Model\Universe\AbstractUniverseModel::getNew('CategoryModel'); $category->loadById($categoryId); $groupIds = $category->loadGroupsData($offset, $length); foreach((array)$category->groups as $group){ @@ -90,10 +90,10 @@ class Universe extends Controller { * @return array * @throws \Exception */ - protected function setupCategories(array $categoriesWhitelist = []){ + protected function setupCategories(array $categoriesWhitelist = []) : array { $return = []; $categoryIds = $this->getF3()->ccpClient()->getUniverseCategories(); - $categoryIds = array_intersect ($categoriesWhitelist, $categoryIds); + $categoryIds = array_intersect($categoriesWhitelist, $categoryIds); foreach($categoryIds as $categoryId){ $return[$categoryId] = $this->setupCategory($categoryId); } @@ -110,14 +110,14 @@ class Universe extends Controller { * @return array * @throws \Exception */ - protected function setupGroups(array $groupsWhitelist = []){ + protected function setupGroups(array $groupsWhitelist = []) : array { $return = []; $groupIds = $this->getF3()->ccpClient()->getUniverseGroups(); - $groupIds = array_intersect ($groupsWhitelist, $groupIds); + $groupIds = array_intersect($groupsWhitelist, $groupIds); /** * @var $group Model\Universe\GroupModel */ - $group = Model\Universe\BasicUniverseModel::getNew('GroupModel'); + $group = Model\Universe\AbstractUniverseModel::getNew('GroupModel'); foreach($groupIds as $groupId){ $group->loadById($groupId); $return[$group->_id] = $group->loadTypesData(); @@ -143,7 +143,7 @@ class Universe extends Controller { /** * @var $system Model\Universe\SystemModel */ - $system = Model\Universe\BasicUniverseModel::getNew('SystemModel'); + $system = Model\Universe\AbstractUniverseModel::getNew('SystemModel'); $indexData = []; foreach($systemIds as $systemId){ $system->getById($systemId); @@ -174,7 +174,7 @@ class Universe extends Controller { /** * @var $system Model\Universe\SystemModel */ - $system = Model\Universe\BasicUniverseModel::getNew('SystemModel'); + $system = Model\Universe\AbstractUniverseModel::getNew('SystemModel'); if($systems = $system->find()){ $systemIds = $systems->getAll('id'); if(count($systemIds)){ @@ -194,7 +194,7 @@ class Universe extends Controller { */ public function getSystemsIndex(bool $all = false) : array { $index = []; - $cacheKeyTable = Model\Universe\BasicUniverseModel::generateHashKeyTable('system'); + $cacheKeyTable = Model\Universe\AbstractUniverseModel::generateHashKeyTable('system'); if($this->getF3()->exists($cacheKeyTable,$cacheKeys)){ foreach((array)$cacheKeys as $cacheKeyRow){ if(($data = $this->get($cacheKeyRow)) && is_object($data)){ @@ -209,7 +209,7 @@ class Universe extends Controller { * clear complete systems search index for all systems */ public function clearSystemsIndex(){ - $cacheKeyTable = Model\Universe\BasicUniverseModel::generateHashKeyTable('system'); + $cacheKeyTable = Model\Universe\AbstractUniverseModel::generateHashKeyTable('system'); if($this->getF3()->exists($cacheKeyTable,$cacheKeys)){ foreach((array)$cacheKeys as $cacheKeyRow) { $this->clear($cacheKeyRow); @@ -229,14 +229,14 @@ class Universe extends Controller { $data = null; if($systemId){ // ...check index for data - $cacheKeyRow = Model\Universe\BasicUniverseModel::generateHashKeyRow('system', $systemId); + $cacheKeyRow = Model\Universe\AbstractUniverseModel::generateHashKeyRow('system', $systemId); $data = $this->get($cacheKeyRow); if(!$data){ // .. try to build index /** * @var $system Model\Universe\SystemModel */ - $system = Model\Universe\BasicUniverseModel::getNew('SystemModel'); + $system = Model\Universe\AbstractUniverseModel::getNew('SystemModel'); $system->getById($systemId); $data = $system->buildIndex(); } @@ -252,7 +252,7 @@ class Universe extends Controller { private function get(string $cacheKey){ $data = null; if($this->getF3()->exists($cacheKey,$value)) { - if(is_string($value) && strpos($value, Model\Universe\BasicUniverseModel::CACHE_KEY_PREFIX) === 0) { + if(is_string($value) && strpos($value, Model\Universe\AbstractUniverseModel::CACHE_KEY_PREFIX) === 0) { // value references an other cacheKey that holds data return $this->get($value); }elseif( !empty((array)$value) ){ @@ -269,7 +269,7 @@ class Universe extends Controller { */ private function clear(string $cacheKey){ if($this->getF3()->exists($cacheKey,$value)) { - if(is_string($value) && strpos($value, Model\Universe\BasicUniverseModel::CACHE_KEY_PREFIX) === 0) { + if(is_string($value) && strpos($value, Model\Universe\AbstractUniverseModel::CACHE_KEY_PREFIX) === 0) { // value references another cacheKey -> clear that one as well $this->clear($value); } diff --git a/app/main/controller/controller.php b/app/main/controller/controller.php index 66f3b3f6..75804e51 100644 --- a/app/main/controller/controller.php +++ b/app/main/controller/controller.php @@ -12,10 +12,11 @@ use Controller\Api as Api; use Exception\PathfinderException; use lib\api\CcpClient; use lib\Config; +use lib\db\SQL; use lib\Resource; use lib\Monolog; use lib\Util; -use Model; +use Model\Pathfinder; use DB; class Controller { @@ -57,10 +58,19 @@ class Controller { * get $f3 base object * @return \Base */ - protected function getF3(){ + protected function getF3() : \Base { return \Base::instance(); } + /** + * get DB connection + * @param string $alias + * @return SQL|null + */ + protected function getDB(string $alias = 'PF') : ?SQL { + return $this->getF3()->DB->getDB($alias); + } + /** * event handler for all "views" * some global template variables are set in here @@ -68,10 +78,7 @@ class Controller { * @param $params * @return bool */ - function beforeroute(\Base $f3, $params): bool { - // initiate DB connection - DB\Database::instance()->getDB('PF'); - + function beforeroute(\Base $f3, $params) : bool { // init user session $this->initSession($f3); @@ -110,15 +117,6 @@ class Controller { } } - /** - * set change the DB connection - * @param string $database - * @return DB\SQL - */ - protected function getDB($database = 'PF'){ - return DB\Database::instance()->getDB($database); - } - /** * init new Session handler * @param \Base $f3 @@ -128,7 +126,7 @@ class Controller { if( $f3->get('SESSION_CACHE') === 'mysql' && - $this->getDB('PF') instanceof DB\SQL + ($db = $f3->DB->getDB('PF')) instanceof SQL ){ if(!headers_sent() && session_status()!=PHP_SESSION_ACTIVE){ /** @@ -149,7 +147,7 @@ class Controller { return false; }; - new DB\SQL\MySQL\Session($this->getDB('PF'), 'sessions', true, $onSuspect); + new DB\SQL\MySQL\Session($db, 'sessions', true, $onSuspect); } } } @@ -186,7 +184,7 @@ class Controller { * -> whether user accepts cookies * @return bool */ - protected function getCookieState(){ + protected function getCookieState() : bool { return (bool)count( $this->getCookieByName(self::COOKIE_NAME_STATE) ); } @@ -198,7 +196,7 @@ class Controller { * @param bool $prefix * @return array */ - protected function getCookieByName($cookieName, $prefix = false){ + protected function getCookieByName($cookieName, $prefix = false) : array { $data = []; if(!empty($cookieName)){ @@ -222,10 +220,10 @@ class Controller { /** * set/update logged in cookie by character model * -> store validation data in DB - * @param Model\CharacterModel $character + * @param Pathfinder\CharacterModel $character * @throws \Exception */ - protected function setLoginCookie(Model\CharacterModel $character){ + protected function setLoginCookie(Pathfinder\CharacterModel $character){ if( $this->getCookieState() ){ $expireSeconds = (int)Config::getPathfinderData('login.cookie_expire'); $expireSeconds *= 24 * 60 * 60; @@ -279,10 +277,10 @@ class Controller { * * @param array $cookieData * @param bool $checkAuthorization - * @return Model\CharacterModel[] + * @return Pathfinder\CharacterModel[] * @throws \Exception */ - protected function getCookieCharacters($cookieData = [], $checkAuthorization = true){ + protected function getCookieCharacters($cookieData = [], $checkAuthorization = true) : array { $characters = []; if( @@ -290,9 +288,9 @@ class Controller { !empty($cookieData) ){ /** - * @var $characterAuth Model\CharacterAuthenticationModel + * @var $characterAuth Pathfinder\CharacterAuthenticationModel */ - $characterAuth = Model\BasicModel::getNew('CharacterAuthenticationModel'); + $characterAuth = Pathfinder\AbstractPathfinderModel::getNew('CharacterAuthenticationModel'); $timezone = $this->getF3()->get('getTimeZone')(); $currentTime = new \DateTime('now', $timezone); @@ -318,7 +316,7 @@ class Controller { // -> try to update character information from ESI // e.g. Corp has changed, this also ensures valid "access_token" /** - * @var $character Model\CharacterModel + * @var $character Pathfinder\CharacterModel */ $updateStatus = $characterAuth->characterId->updateFromESI(); @@ -413,17 +411,17 @@ class Controller { /** * get current character * @param int $ttl - * @return Model\CharacterModel|null + * @return Pathfinder\CharacterModel|null * @throws \Exception */ - public function getCharacter(int $ttl = 0) : ?Model\CharacterModel { + public function getCharacter(int $ttl = 0) : ?Pathfinder\CharacterModel { $character = null; if(!empty($characterData = $this->getSessionCharacterData())){ /** - * @var $characterModel Model\CharacterModel + * @var $characterModel Pathfinder\CharacterModel */ - $characterModel = Model\BasicModel::getNew('CharacterModel'); + $characterModel = Pathfinder\AbstractPathfinderModel::getNew('CharacterModel'); $characterModel->getById((int)$characterData['ID'], $ttl); if( !$characterModel->dry() && @@ -439,17 +437,17 @@ class Controller { /** * get current user * @param int $ttl - * @return Model\UserModel|null + * @return Pathfinder\UserModel|null * @throws \Exception */ - public function getUser($ttl = 0){ + public function getUser($ttl = 0) : ?Pathfinder\UserModel { $user = null; if($this->getF3()->exists(Api\User::SESSION_KEY_USER_ID, $userId)){ /** - * @var $userModel Model\UserModel + * @var $userModel Pathfinder\UserModel */ - $userModel = Model\BasicModel::getNew('UserModel'); + $userModel = Pathfinder\AbstractPathfinderModel::getNew('UserModel'); $userModel->getById($userId, $ttl); if( @@ -495,9 +493,9 @@ class Controller { if($sessionCharacterData){ $activeCharacterId = ($activeCharacter = $this->getCharacter()) ? $activeCharacter->_id : 0; /** - * @var Model\CharacterModel $character + * @var $character Pathfinder\CharacterModel */ - $character = Model\BasicModel::getNew('CharacterModel'); + $character = Pathfinder\AbstractPathfinderModel::getNew('CharacterModel'); $characterIds = []; foreach($sessionCharacterData as $characterData){ if($characterData['ID'] === $activeCharacterId){ @@ -689,7 +687,7 @@ class Controller { * get a custom userAgent string for API calls * @return string */ - protected function getUserAgent(){ + protected function getUserAgent() : string { $userAgent = ''; $userAgent .= Config::getPathfinderData('name'); $userAgent .= ' - ' . Config::getPathfinderData('version'); @@ -812,7 +810,7 @@ class Controller { * get controller by class name * -> controller class is searched within all controller directories * @param $className - * @return null|\Controller\ + * @return null|Controller * @throws \Exception */ static function getController($className){ @@ -862,7 +860,7 @@ class Controller { * getallheaders() is not available under nginx * @return array (string $key -> string $value) */ - static function getRequestHeaders(){ + static function getRequestHeaders() : array { $headers = []; $serverData = self::getServerData(); @@ -871,10 +869,10 @@ class Controller { function_exists('apache_request_headers') && $serverData->type === 'apache' ){ - // Apache Webserver + // Apache WebServer $headers = apache_request_headers(); }else{ - // Other webserver, e.g. Nginx + // Other WebServer, e.g. Nginx // Unfortunately this "fallback" does not work for me (Apache) // Therefore we can´t use this for all servers // https://github.com/exodus4d/pathfinder/issues/58 @@ -956,9 +954,9 @@ class Controller { * @param $key * @return string */ - static function formatHiveKey($key){ + static function formatHiveKey($key) : string { $illegalCharacters = ['-', ' ']; - return strtolower( str_replace($illegalCharacters, '', $key) ); + return strtolower(str_replace($illegalCharacters, '', $key)); } /** diff --git a/app/main/controller/logcontroller.php b/app/main/controller/logcontroller.php index d7290ed7..ebe47a49 100644 --- a/app/main/controller/logcontroller.php +++ b/app/main/controller/logcontroller.php @@ -7,11 +7,11 @@ */ namespace controller; -use DB; + + use lib\Config; use lib\logging\MapLog; -use Model\ActivityLogModel; -use Model\BasicModel; +use Model\Pathfinder; class LogController extends \Prefab { @@ -41,9 +41,9 @@ class LogController extends \Prefab { $f3 = \Base::instance(); if(!$f3->exists(self::CACHE_KEY_ACTIVITY_COLUMNS, $this->activityLogColumns)){ /** - * @var $activityLogModel ActivityLogModel + * @var $activityLogModel Pathfinder\ActivityLogModel */ - $activityLogModel = BasicModel::getNew('ActivityLogModel'); + $activityLogModel = Pathfinder\AbstractPathfinderModel::getNew('ActivityLogModel'); $this->activityLogColumns = $activityLogModel->getCountableColumnNames(); $f3->set(self::CACHE_KEY_ACTIVITY_COLUMNS, self::CACHE_TTL_ACTIVITY_COLUMNS); } @@ -86,7 +86,7 @@ class LogController extends \Prefab { */ public function logActivities(){ if( !empty($this->activityLogBuffer) ){ - $db = DB\Database::instance()->getDB('PF'); + $db = \Base::instance()->DB->getDB('PF'); $quoteStr = function($str) use ($db) { return $db->quotekey($str); @@ -166,12 +166,8 @@ class LogController extends \Prefab { */ public static function getLogger(string $type) : \Log { $logFiles = Config::getPathfinderData('logfiles'); - $logFileName = empty($logFiles[$type]) ? 'error' : $logFiles[$type]; - $logFile = $logFileName . '.log'; - $logger = new \Log($logFile); - - return $logger; + return new \Log($logFileName . '.log'); } } \ No newline at end of file diff --git a/app/main/controller/setup.php b/app/main/controller/setup.php index 206eeaeb..6b1b610b 100644 --- a/app/main/controller/setup.php +++ b/app/main/controller/setup.php @@ -8,14 +8,14 @@ namespace Controller; -use Controller\Ccp\Universe; +use Controller\Ccp\Universe as UniverseController; use data\filesystem\Search; -use DB; -use DB\SQL; +use DB\SQL\Schema; use DB\SQL\MySQL as MySQL; use lib\Config; use lib\Util; -use Model; +use Model\Pathfinder; +use Model\Universe; class Setup extends Controller { @@ -59,47 +59,47 @@ class Setup extends Controller { 'PF' => [ 'info' => [], 'models' => [ - 'Model\UserModel', - 'Model\AllianceModel', - 'Model\CorporationModel', - 'Model\MapModel', - 'Model\MapScopeModel', - 'Model\MapTypeModel', - 'Model\SystemTypeModel', - 'Model\SystemStatusModel', - 'Model\SystemNeighbourModel', - 'Model\RightModel', - 'Model\RoleModel', - 'Model\StructureModel', + 'Model\Pathfinder\UserModel', + 'Model\Pathfinder\AllianceModel', + 'Model\Pathfinder\CorporationModel', + 'Model\Pathfinder\MapModel', + 'Model\Pathfinder\MapScopeModel', + 'Model\Pathfinder\MapTypeModel', + 'Model\Pathfinder\SystemTypeModel', + 'Model\Pathfinder\SystemStatusModel', + 'Model\Pathfinder\SystemNeighbourModel', + 'Model\Pathfinder\RightModel', + 'Model\Pathfinder\RoleModel', + 'Model\Pathfinder\StructureModel', - 'Model\CharacterStatusModel', - 'Model\ConnectionScopeModel', - 'Model\StructureStatusModel', + 'Model\Pathfinder\CharacterStatusModel', + 'Model\Pathfinder\ConnectionScopeModel', + 'Model\Pathfinder\StructureStatusModel', - 'Model\CharacterMapModel', - 'Model\AllianceMapModel', - 'Model\CorporationMapModel', + 'Model\Pathfinder\CharacterMapModel', + 'Model\Pathfinder\AllianceMapModel', + 'Model\Pathfinder\CorporationMapModel', - 'Model\CorporationRightModel', - 'Model\CorporationStructureModel', + 'Model\Pathfinder\CorporationRightModel', + 'Model\Pathfinder\CorporationStructureModel', - 'Model\UserCharacterModel', - 'Model\CharacterModel', - 'Model\CharacterAuthenticationModel', - 'Model\CharacterLogModel', + 'Model\Pathfinder\UserCharacterModel', + 'Model\Pathfinder\CharacterModel', + 'Model\Pathfinder\CharacterAuthenticationModel', + 'Model\Pathfinder\CharacterLogModel', - 'Model\SystemModel', + 'Model\Pathfinder\SystemModel', - 'Model\ConnectionModel', - 'Model\ConnectionLogModel', - 'Model\SystemSignatureModel', + 'Model\Pathfinder\ConnectionModel', + 'Model\Pathfinder\ConnectionLogModel', + 'Model\Pathfinder\SystemSignatureModel', - 'Model\ActivityLogModel', + 'Model\Pathfinder\ActivityLogModel', - 'Model\SystemShipKillModel', - 'Model\SystemPodKillModel', - 'Model\SystemFactionKillModel', - 'Model\SystemJumpModel' + 'Model\Pathfinder\SystemShipKillModel', + 'Model\Pathfinder\SystemPodKillModel', + 'Model\Pathfinder\SystemFactionKillModel', + 'Model\Pathfinder\SystemJumpModel' ] ], 'UNIVERSE' => [ @@ -108,6 +108,7 @@ class Setup extends Controller { 'Model\Universe\TypeModel', 'Model\Universe\GroupModel', 'Model\Universe\CategoryModel', + 'Model\Universe\FactionModel', 'Model\Universe\StructureModel', 'Model\Universe\WormholeModel', 'Model\Universe\StargateModel', @@ -121,11 +122,6 @@ class Setup extends Controller { ] ]; - /** - * @var DB\Database - */ - protected $dbLib = null; - /** * database error * @var bool @@ -142,9 +138,6 @@ class Setup extends Controller { function beforeroute(\Base $f3, $params): bool { $this->initResource($f3); - // init dbLib class. Manages all DB connections - $this->dbLib = DB\Database::instance(); - // page title $f3->set('tplPageTitle', 'Setup | ' . Config::getPathfinderData('name')); @@ -199,10 +192,10 @@ class Setup extends Controller { switch($params['action']){ case 'createDB': - $this->createDB($params['db']); + $this->createDB($f3, $params['db']); break; case 'bootstrapDB': - $this->bootstrapDB($params['db']); + $this->bootstrapDB($f3, $params['db']); break; case 'fixCols': $fixColumns = true; @@ -1083,7 +1076,7 @@ class Setup extends Controller { */ protected function checkDatabase(\Base $f3, $exec = false){ - foreach($this->databases as $dbKey => $dbData){ + foreach($this->databases as $dbAlias => $dbData){ $dbLabel = ''; $dbConfig = []; @@ -1105,14 +1098,16 @@ class Setup extends Controller { // tables that should exist in this DB $requiredTables = []; // get DB config - $dbConfigValues = Config::getDatabaseConfig($dbKey); - // check DB for valid connection - $db = $this->dbLib->getDB($dbKey); + $dbConfigValues = Config::getDatabaseConfig($f3, $dbAlias); // collection for errors $dbErrors = []; + /** + * @var $db \lib\db\SQL + */ + $db = $f3->DB->getDB($dbAlias); // check config that does NOT require a valid DB connection - switch($dbKey){ + switch($dbAlias){ case 'PF': $dbLabel = 'Pathfinder'; break; case 'UNIVERSE': $dbLabel = 'EVE-Online universe'; break; } @@ -1122,7 +1117,7 @@ class Setup extends Controller { $dbAlias = $dbConfigValues['ALIAS']; if($db){ - switch($dbKey){ + switch($dbAlias){ case 'PF': case 'UNIVERSE': // enable (table) setup for this DB @@ -1150,7 +1145,7 @@ class Setup extends Controller { $dbConfig = $this->checkDBConfig($f3, $db); // get tables - $schema = new SQL\Schema($db); + $schema = new Schema($db); $currentTables = $schema->getTables(); // check each table for changes @@ -1169,7 +1164,7 @@ class Setup extends Controller { $tableModifierTemp = new MySQL\TableModifier($requiredTableName, $schema); $currentColumns = $tableModifierTemp->getCols(true); // get row count - $tableRows = $this->dbLib->getRowCount($requiredTableName, $dbKey); + $tableRows = $db->getRowCount($requiredTableName); }else{ // table missing $dbStatusCheckCount++; @@ -1357,15 +1352,15 @@ class Setup extends Controller { // DB connection failed $dbStatusCheckCount++; - foreach($this->dbLib->getErrors($dbAlias, 10) as $dbException){ + foreach($f3->DB->getErrors($dbAlias, 10) as $dbException){ $dbErrors[] = $dbException->getMessage(); } // try to connect without! DB (-> offer option to create them) // do not log errors (silent) - $this->dbLib->setSilent(true); - $dbServer = $this->dbLib->connectToServer($dbAlias); - $this->dbLib->setSilent(false); + $f3->DB->setSilent(true); + $dbServer = $f3->DB->connectToServer($dbAlias); + $f3->DB->setSilent(false); if(!is_null($dbServer)){ // connection succeeded $dbCreate = true; @@ -1380,11 +1375,11 @@ class Setup extends Controller { // sort tables for better readability ksort($requiredTables); - $this->databases[$dbKey]['info'] = [ + $this->databases[$dbAlias]['info'] = [ // 'db' => $db, 'label' => $dbLabel, - 'host' => Config::getDatabaseDNSValue((string)$dbConfigValues['DNS'], 'host'), - 'port' => Config::getDatabaseDNSValue((string)$dbConfigValues['DNS'], 'port'), + 'host' => $dbConfigValues['SOCKET'] ? : $dbConfigValues['HOST'], + 'port' => $dbConfigValues['PORT'] && !$dbConfigValues['SOCKET'] ? $dbConfigValues['PORT'] : '', 'driver' => $dbDriver, 'name' => $dbName, 'user' => $dbUser, @@ -1411,11 +1406,10 @@ class Setup extends Controller { /** * check MySQL params * @param \Base $f3 - * @param SQL $db + * @param \lib\db\SQL $db * @return array */ - protected function checkDBConfig(\Base $f3, SQL $db){ - + protected function checkDBConfig(\Base $f3, \lib\db\SQL $db) : array { // some db like "Maria DB" have some strange version strings.... $dbVersionString = $db->version(); $dbVersionParts = explode('-', $dbVersionString); @@ -1437,15 +1431,22 @@ class Setup extends Controller { ] ]; - $mySQLConfigParams = (array)$f3->get('REQUIREMENTS.MYSQL.VARS'); - foreach($mySQLConfigParams as $param => $requiredValue){ - // get current MySQL config value for $param - $result = $db->exec("SHOW VARIABLES LIKE '" . strtolower($param) . "'"); - $tmpResult = reset($result); - $value = !empty($result)? end($tmpResult) : 'unknown'; + $mySQLConfig = array_change_key_case((array)$f3->get('REQUIREMENTS.MYSQL.VARS')); + $mySQLConfigKeys = array_keys($mySQLConfig); + $results = $db->exec("SHOW VARIABLES WHERE Variable_Name IN ('" . implode("','", $mySQLConfigKeys) . "')"); + + $getValue = function(string $param) use ($results) : string { + $match = array_filter($results, function($k) use ($param) : bool { + return strtolower($k['Variable_name']) == $param; + }); + return !empty($match) ? end(reset($match)) : 'unknown'; + }; + + foreach($mySQLConfig as $param => $requiredValue){ + $value = $getValue($param); $dbConfig[] = [ - 'label' => strtolower($param), + 'label' => $param, 'required' => $requiredValue, 'version' => $value, 'check' => !empty($requiredValue) ? ($requiredValue == $value) : true @@ -1457,22 +1458,23 @@ class Setup extends Controller { /** * try to create a fresh database - * @param string $dbKey + * @param \Base $f3 + * @param string $dbAlias */ - protected function createDB(string $dbKey){ + protected function createDB(\Base $f3, string $dbAlias){ // check for valid key - if(!empty($this->databases[$dbKey])){ + if(!empty($this->databases[$dbAlias])){ // disable logging (we expect the DB connect to fail -> no db created) - $this->dbLib->setSilent(true); + $f3->DB->setSilent(true); // try to connect - $db = $this->dbLib->getDB($dbKey); + $db = $f3->DB->getDB($dbAlias); // enable logging - $this->dbLib->setSilent(false, true); + $f3->DB->setSilent(false, true); if(is_null($db)){ // try create new db - $db = $this->dbLib->createDB($dbKey); + $db = $f3->DB->createDB($dbAlias); if(is_null($db)){ - foreach($this->dbLib->getErrors($dbKey, 5) as $error){ + foreach($f3->DB->getErrors($dbAlias, 5) as $error){ // ... no further error handling here -> check log files //$error->getMessage() } @@ -1486,18 +1488,19 @@ class Setup extends Controller { * - create tables * - create indexes * - set default static values - * @param string $dbKey + * @param \Base $f3 + * @param string $dbAlias * @return array */ - protected function bootstrapDB(string $dbKey){ - $db = $this->dbLib->getDB($dbKey); + protected function bootstrapDB(\Base $f3, string $dbAlias) : array { $checkTables = []; - if($db){ + if($db = $f3->DB->getDB($dbAlias)){ // set some default config for this database - DB\Database::prepareDatabase($db); + $requiredVars = Config::getRequiredDbVars($f3, $db->driver()); + $db->prepareDatabase($requiredVars['CHARACTER_SET_DATABASE'], $requiredVars['COLLATION_DATABASE']); // setup tables - foreach($this->databases[$dbKey]['models'] as $modelClass){ + foreach($this->databases[$dbAlias]['models'] as $modelClass){ $checkTables[] = call_user_func($modelClass . '::setup', $db); } } @@ -1616,9 +1619,9 @@ class Setup extends Controller { // active DB and tables are required for obtain index data if(!$this->databaseHasError){ /** - * @var $categoryUniverseModel Model\Universe\CategoryModel + * @var $categoryUniverseModel Universe\CategoryModel */ - $categoryUniverseModel = Model\Universe\BasicUniverseModel::getNew('CategoryModel'); + $categoryUniverseModel = Universe\AbstractUniverseModel::getNew('CategoryModel'); $categoryUniverseModel->getById(65, 0); $structureCount = $categoryUniverseModel->getTypesCount(false); @@ -1626,11 +1629,9 @@ class Setup extends Controller { $shipCount = $categoryUniverseModel->getTypesCount(false); /** - * @var $systemNeighbourModel Model\SystemNeighbourModel + * @var $systemNeighbourModel Pathfinder\SystemNeighbourModel */ - $systemNeighbourModel = Model\BasicModel::getNew('SystemNeighbourModel'); - - + $systemNeighbourModel = Pathfinder\AbstractPathfinderModel::getNew('SystemNeighbourModel'); $indexInfo = [ 'Systems' => [ @@ -1648,8 +1649,8 @@ class Setup extends Controller { ] ], 'label' => 'build systems index', - 'countBuild' => count((new Universe())->getSystemsIndex()), - 'countAll' => count((new Universe())->getSystemIds()), + 'countBuild' => count((new UniverseController())->getSystemsIndex()), + 'countAll' => count((new UniverseController())->getSystemIds()), 'tooltip' => 'build up a static search index over all systems found on DB. Do not refresh page until import is complete (check progress)! Runtime: ~5min' ], 'Structures' => [ @@ -1690,7 +1691,7 @@ class Setup extends Controller { ] ], 'label' => 'build neighbour index', - 'countBuild' => $this->dbLib->getRowCount($systemNeighbourModel->getTable()), + 'countBuild' => $f3->DB->getDB('PF')->getRowCount($systemNeighbourModel->getTable()), 'countAll' => (int)$f3->get('REQUIREMENTS.DATA.NEIGHBOURS'), 'tooltip' => 'build up a static search index for route search. This is used as fallback in case ESI is down. Runtime: ~30s' @@ -1712,7 +1713,7 @@ class Setup extends Controller { ] ], 'label' => 'wormhole', - 'countBuild' => $this->dbLib->getRowCount($wormholeModel->getTable()), + 'countBuild' => $f3->DB->getDB('PF')->getRowCount($wormholeModel->getTable()), 'countAll' => 89 ] */ @@ -1737,7 +1738,7 @@ class Setup extends Controller { */ protected function importTable($modelClass){ $this->getDB('PF'); - return Model\BasicModel::getNew($modelClass)->importData(); + return Pathfinder\AbstractPathfinderModel::getNew($modelClass)->importData(); } /** @@ -1747,7 +1748,7 @@ class Setup extends Controller { */ protected function exportTable($modelClass){ $this->getDB('PF'); - Model\BasicModel::getNew($modelClass)->exportData(); + Pathfinder\AbstractPathfinderModel::getNew($modelClass)->exportData(); } /** @@ -1850,7 +1851,7 @@ class Setup extends Controller { */ protected function invalidateCookies(\Base $f3){ $this->getDB('PF'); - $authenticationModel = Model\BasicModel::getNew('CharacterAuthenticationModel'); + $authenticationModel = Pathfinder\AbstractPathfinderModel::getNew('CharacterAuthenticationModel'); $results = $authenticationModel->find(); if($results){ foreach($results as $result){ diff --git a/app/main/cron/abstractcron.php b/app/main/cron/abstractcron.php index 04b4076d..d98c7706 100644 --- a/app/main/cron/abstractcron.php +++ b/app/main/cron/abstractcron.php @@ -1,7 +1,7 @@ exec('SHOW TABLES LIKE :table', [':table' => $table])); } /** * check all system log tables for the correct number of system entries that will be locked + * @param \Base $f3 * @return array */ - private function prepareSystemLogTables() : array { + private function prepareSystemLogTables(\Base $f3) : array { $systemsData = []; // get all available systems from "universe" DB - $universeDB = DB\Database::instance()->getDB('UNIVERSE'); + $universeDB = $f3->DB->getDB('UNIVERSE'); if($this->tableExists($universeDB, 'system')){ $systemsData = $universeDB->exec('SELECT @@ -57,7 +58,7 @@ class CcpSystemsUpdate extends AbstractCron { [':ns' => '0.0', ':ls' => 'L', ':hs' => 'H'] ); - $pfDB = DB\Database::instance()->getDB('PF'); + $pfDB = $f3->DB->getDB('PF'); // insert systems into each log table if not exist $pfDB->begin(); @@ -90,12 +91,12 @@ class CcpSystemsUpdate extends AbstractCron { // prepare system jump log table ------------------------------------------------------------------------------ $time_start = microtime(true); - $systemsData = $this->prepareSystemLogTables(); + $systemsData = $this->prepareSystemLogTables($f3); $time_end = microtime(true); $execTimePrepareSystemLogTables = $time_end - $time_start; // switch DB for data import.. - $pfDB = DB\Database::instance()->getDB('PF'); + $pfDB = $f3->DB->getDB('PF'); // get current jump data -------------------------------------------------------------------------------------- $time_start = microtime(true); diff --git a/app/main/cron/characterupdate.php b/app/main/cron/characterupdate.php index 3f74e9e9..325b1339 100644 --- a/app/main/cron/characterupdate.php +++ b/app/main/cron/characterupdate.php @@ -7,10 +7,10 @@ */ namespace Cron; -use DB; -use Model; +use Model\Pathfinder; + class CharacterUpdate extends AbstractCron { /** @@ -42,13 +42,12 @@ class CharacterUpdate extends AbstractCron { */ function deleteLogData(\Base $f3){ $this->setMaxExecutionTime(); - DB\Database::instance()->getDB('PF'); $logInactiveTime = $this->getCharacterLogInactiveTime($f3); /** - * @var $characterLogModel Model\CharacterLogModel + * @var $characterLogModel Pathfinder\CharacterLogModel */ - $characterLogModel = Model\BasicModel::getNew('CharacterLogModel'); + $characterLogModel = Pathfinder\AbstractPathfinderModel::getNew('CharacterLogModel'); // find character logs that were not checked recently and update $characterLogs = $characterLogModel->find([ @@ -62,7 +61,7 @@ class CharacterUpdate extends AbstractCron { if(is_object($characterLogs)){ foreach($characterLogs as $characterLog){ /** - * @var $characterLog Model\CharacterLogModel + * @var $characterLog Pathfinder\CharacterLogModel */ if(is_object($characterLog->characterId)){ // force characterLog as "updated" even if no changes were made @@ -85,12 +84,11 @@ class CharacterUpdate extends AbstractCron { */ function cleanUpCharacterData(\Base $f3){ $this->setMaxExecutionTime(); - DB\Database::instance()->getDB('PF'); /** - * @var $characterModel Model\CharacterModel + * @var $characterModel Pathfinder\CharacterModel */ - $characterModel = Model\BasicModel::getNew('CharacterModel'); + $characterModel = Pathfinder\AbstractPathfinderModel::getNew('CharacterModel'); $characters = $characterModel->find([ 'active = :active AND TIMESTAMPDIFF(SECOND, kicked, NOW() ) > 0', @@ -100,7 +98,7 @@ class CharacterUpdate extends AbstractCron { if(is_object($characters)){ foreach($characters as $character){ /** - * @var $character Model\CharacterModel + * @var $character Pathfinder\CharacterModel */ $character->kick(); $character->save(); @@ -117,12 +115,11 @@ class CharacterUpdate extends AbstractCron { */ function deleteAuthenticationData(\Base $f3){ $this->setMaxExecutionTime(); - DB\Database::instance()->getDB('PF'); /** - * @var $authenticationModel Model\CharacterAuthenticationModel + * @var $authenticationModel Pathfinder\CharacterAuthenticationModel */ - $authenticationModel = Model\BasicModel::getNew('CharacterAuthenticationModel'); + $authenticationModel = Pathfinder\AbstractPathfinderModel::getNew('CharacterAuthenticationModel'); // find expired authentication data $authentications = $authenticationModel->find([ diff --git a/app/main/cron/mapupdate.php b/app/main/cron/mapupdate.php index 24c62c5e..dbf3e4bc 100644 --- a/app/main/cron/mapupdate.php +++ b/app/main/cron/mapupdate.php @@ -7,9 +7,10 @@ */ namespace cron; -use DB; + + use lib\Config; -use Model; +use Model\Pathfinder; class MapUpdate extends AbstractCron { @@ -28,14 +29,13 @@ class MapUpdate extends AbstractCron { $privateMapLifetime = (int)Config::getMapsDefaultConfig('private.lifetime'); if($privateMapLifetime > 0){ - $pfDB = DB\Database::instance()->getDB('PF'); - if($pfDB){ + if($pfDB = $f3->DB->getDB('PF')){ $sqlDeactivateExpiredMaps = "UPDATE map SET - active = 0 - WHERE - map.active = 1 AND - map.typeId = 2 AND - TIMESTAMPDIFF(DAY, map.updated, NOW() ) > :lifetime"; + active = 0 + WHERE + map.active = 1 AND + map.typeId = 2 AND + TIMESTAMPDIFF(DAY, map.updated, NOW() ) > :lifetime"; $pfDB->exec($sqlDeactivateExpiredMaps, ['lifetime' => $privateMapLifetime]); } @@ -50,10 +50,9 @@ class MapUpdate extends AbstractCron { */ function deleteMapData(\Base $f3){ $this->setMaxExecutionTime(); - $pfDB = DB\Database::instance()->getDB('PF'); $deletedMapsCount = 0; - if($pfDB){ + if($pfDB = $f3->DB->getDB('PF')){ $sqlDeleteDisabledMaps = "SELECT id FROM @@ -65,7 +64,7 @@ class MapUpdate extends AbstractCron { $disabledMaps = $pfDB->exec($sqlDeleteDisabledMaps, ['deletion_time' => self::DAYS_UNTIL_MAP_DELETION]); if($deletedMapsCount = $pfDB->count()){ - $mapModel = Model\BasicModel::getNew('MapModel'); + $mapModel = Pathfinder\AbstractPathfinderModel::getNew('MapModel'); foreach($disabledMaps as $data){ $mapModel->getById( (int)$data['id'], 3, false ); if( !$mapModel->dry() ){ @@ -92,8 +91,7 @@ class MapUpdate extends AbstractCron { $eolExpire = (int)$f3->get('PATHFINDER.CACHE.EXPIRE_CONNECTIONS_EOL'); if($eolExpire > 0){ - $pfDB = DB\Database::instance()->getDB('PF'); - if($pfDB){ + if($pfDB = $f3->DB->getDB('PF')){ $sql = "SELECT `con`.`id` FROM @@ -112,9 +110,9 @@ class MapUpdate extends AbstractCron { if($connectionsData){ /** - * @var $connection Model\ConnectionModel + * @var $connection Pathfinder\ConnectionModel */ - $connection = Model\BasicModel::getNew('ConnectionModel'); + $connection = Pathfinder\AbstractPathfinderModel::getNew('ConnectionModel'); foreach($connectionsData as $data){ $connection->getById( (int)$data['id'] ); if( !$connection->dry() ){ @@ -137,8 +135,7 @@ class MapUpdate extends AbstractCron { $whExpire = (int)$f3->get('PATHFINDER.CACHE.EXPIRE_CONNECTIONS_WH'); if($whExpire > 0){ - $pfDB = DB\Database::instance()->getDB('PF'); - if($pfDB){ + if($pfDB = $f3->DB->getDB('PF')){ $sql = "SELECT `con`.`id` FROM @@ -159,9 +156,9 @@ class MapUpdate extends AbstractCron { if($connectionsData){ /** - * @var $connection Model\ConnectionModel + * @var $connection Pathfinder\ConnectionModel */ - $connection = Model\BasicModel::getNew('ConnectionModel'); + $connection = Pathfinder\AbstractPathfinderModel::getNew('ConnectionModel'); foreach($connectionsData as $data){ $connection->getById( (int)$data['id'] ); if( !$connection->dry() ){ @@ -183,8 +180,7 @@ class MapUpdate extends AbstractCron { $signatureExpire = (int)$f3->get('PATHFINDER.CACHE.EXPIRE_SIGNATURES'); if($signatureExpire > 0){ - $pfDB = DB\Database::instance()->getDB('PF'); - if($pfDB){ + if($pfDB = $f3->DB->getDB('PF')){ $sqlDeleteExpiredSignatures = "DELETE `sigs` FROM `system_signature` `sigs` INNER JOIN `system` ON diff --git a/app/main/cron/statisticsupdate.php b/app/main/cron/statisticsupdate.php index ac9f78ca..76bc93e9 100644 --- a/app/main/cron/statisticsupdate.php +++ b/app/main/cron/statisticsupdate.php @@ -7,7 +7,6 @@ */ namespace cron; -use DB; class StatisticsUpdate extends AbstractCron { @@ -26,7 +25,7 @@ class StatisticsUpdate extends AbstractCron { $currentWeek = (int)date('W'); $expiredYear = $currentYear - 1; - $pfDB = DB\Database::instance()->getDB('PF'); + $pfDB = $f3->DB->getDB('PF'); $queryData = [ 'yearWeekEnd' => strval($expiredYear) . str_pad($currentWeek, 2, 0, STR_PAD_LEFT) diff --git a/app/main/cron/universe.php b/app/main/cron/universe.php index dda1c05f..b39d06a7 100644 --- a/app/main/cron/universe.php +++ b/app/main/cron/universe.php @@ -1,7 +1,7 @@ echoLoading(++$count, $importCount, $id); @@ -252,7 +252,7 @@ class Universe extends AbstractCron { function updateUniverseSystems(\Base $f3){ $this->setMaxExecutionTime(); - $system = Model\Universe\BasicUniverseModel::getNew('SystemModel'); + $system = Model\Universe\AbstractUniverseModel::getNew('SystemModel'); $systems = $system->find( null, ['order' => 'updated', 'limit' => 2]); if($systems){ foreach ($systems as $system){ diff --git a/app/main/data/file/filehandler.php b/app/main/data/file/filehandler.php index 739a3d61..f1c6e75d 100644 --- a/app/main/data/file/filehandler.php +++ b/app/main/data/file/filehandler.php @@ -1,7 +1,7 @@ NO database is used - * -> can be used to check if a certain DB exists without connecting to it directly - * @param string $dbKey - * @return SQL|null - */ - public function connectToServer(string $dbKey = 'PF') : ?SQL { - $dbConfig = Config::getDatabaseConfig($dbKey); - $dbConfig['DNS'] = str_replace(';dbname=', '', $dbConfig['DNS'] ); - $dbConfig['NAME'] = ''; - return call_user_func_array([$this, 'connect'], $dbConfig); - } - - /** - * tries to create a database if not exists - * -> DB user needs rights to create a DB - * @param string $dbKey - * @return SQL|null - */ - public function createDB(string $dbKey = 'PF') : ?SQL { - $db = null; - $dbConfig = Config::getDatabaseConfig($dbKey); - // remove database from $dsn (we want to crate it) - $newDbName = $dbConfig['NAME']; - if(!empty($newDbName)){ - $dbConfig['NAME'] = ''; - $dbConfig['DNS'] = str_replace(';dbname=', '', $dbConfig['DNS'] ); - - /** - * @var $db SQL|null - */ - $db = call_user_func_array([$this, 'connect'], $dbConfig); - - if(!is_null($db)){ - $schema = new SQL\Schema($db); - if(!in_array($newDbName, $schema->getDatabases())){ - $db->exec("CREATE DATABASE IF NOT EXISTS - `" . $newDbName . "` DEFAULT CHARACTER SET utf8 - COLLATE utf8_general_ci;"); - $db->exec("USE `" . $newDbName . "`"); - - // check if DB create was successful - $dbCheck = $db->exec("SELECT DATABASE()"); - if( - !empty($dbCheck[0]) && - !empty($checkDbName = reset($dbCheck[0])) && - $checkDbName == $newDbName - ){ - self::prepareDBConnection($db); - self::prepareDatabase($db); - } - } - } - } - - return $db; - } - - /** - * get database - * @param string $dbKey - * @return SQL|null - */ - public function getDB(string $dbKey = 'PF') : ?SQL { - $f3 = \Base::instance(); - // "Hive" Key for DB object cache - $dbHiveKey = $this->getDbHiveKey($dbKey); - if( !$f3->exists($dbHiveKey, $db) ){ - $dbConfig = Config::getDatabaseConfig($dbKey); - /** - * @var $db SQL|null - */ - $db = call_user_func_array([$this, 'connect'], $dbConfig); - if(!is_null($db)){ - self::prepareDBConnection($db); - $f3->set($dbHiveKey, $db); - } - } - - return $db; - } - - /** - * get a unique hive key for each DB connection - * @param $dbKey - * @return string - */ - protected function getDbHiveKey(string $dbKey) : string { - return 'DB_' . $dbKey; - } - - /** - * connect to a database - * @param string $dns - * @param string $name - * @param string $user - * @param string $password - * @param string $alias - * @return SQL|null - */ - protected function connect(string $dns, string $name, string $user, string $password, string $alias) : ?SQL { - $db = null; - $f3 = \Base::instance(); - - $options = [ - \PDO::MYSQL_ATTR_COMPRESS => true, - \PDO::ATTR_TIMEOUT => \Base::instance()->get('REQUIREMENTS.MYSQL.PDO_TIMEOUT'), - ]; - - if(Config::getPathfinderData('experiments.persistent_db_connections')){ - $options[\PDO::ATTR_PERSISTENT] = true; - } - - // set ERRMODE depending on pathfinders global DEBUG level - if($f3->get('DEBUG') >= 1){ - $options[\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_WARNING; - }else{ - $options[\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION; - } - - try { - $db = new SQL( - $dns . $name, - $user, - $password, - $options - ); - }catch(\PDOException $e){ - $this->pushError($alias, $e); - if(!$this->isSilent()){ - self::getLogger()->write($e); - } - } - - return $db; - } - - /** - * get all table names from a DB - * @param string $dbKey - * @return array|bool - */ - public function getTables(string $dbKey = 'PF'){ - $schema = new SQL\Schema( $this->getDB($dbKey) ); - return $schema->getTables(); - } - - /** - * checks whether a table exists on a DB or not - * @param string $table - * @param string $dbKey - * @return bool - */ - public function tableExists(string $table, string $dbKey = 'PF') : bool { - $tableNames = $this->getTables($dbKey); - return in_array($table, $tableNames); - } - - /** - * get current row (data) count for an existing table - * -> returns 0 if table not exists or empty - * @param string $table - * @param string $dbKey - * @return int - */ - public function getRowCount(string $table, string $dbKey = 'PF') : int { - $count = 0; - if( $this->tableExists($table, $dbKey) ){ - $db = $this->getDB($dbKey); - $countRes = $db->exec("SELECT COUNT(*) `num` FROM " . $db->quotekey($table)); - if(isset($countRes[0]['num'])){ - $count = (int)$countRes[0]['num']; - } - } - return $count; - } - - /** - * @return bool - */ - public function isSilent() : bool { - return $this->silent; - } - - /** - * set "silent" mode (no error logging) - * -> optional clear $this->errors - * @param bool $silent - * @param bool $clearErrors - */ - public function setSilent(bool $silent, bool $clearErrors = false){ - $this->silent = $silent; - if($clearErrors){ - $this->errors = []; - } - } - - /** - * push new Exception into static error history - * @param string $alias - * @param \PDOException $e - */ - protected function pushError(string $alias, \PDOException $e){ - if(!is_array($this->errors[$alias])){ - $this->errors[$alias] = []; - } - - // prevent adding same errors twice - if(!empty($this->errors[$alias])){ - $lastError = array_values($this->errors[$alias])[0]; - if($lastError->getMessage() === $e->getMessage()){ - return; - } - } - - array_unshift($this->errors[$alias], $e); - if(count($this->errors[$alias]) > 5){ - $this->errors[$alias] = array_pop($this->errors[$alias]); - } - } - - /** - * get last recent Exceptions from error history - * @param string $alias - * @param int $limit - * @return \PDOException[] - */ - public function getErrors(string $alias, int $limit = 1){ - return array_slice((array)$this->errors[$alias] , 0, $limit); - } - - /** - * prepare current DB - * -> set session connection variables - * @param SQL $db - */ - public static function prepareDBConnection(SQL &$db){ - // set DB timezone to UTC +00:00 (eve server time) - // set default storage engine - $db->exec([ - 'SET @@session.time_zone = :time_zone', - 'SET @@session.default_storage_engine = :storage_engine' - ], [ - [':time_zone' => '+00:00'], - [':storage_engine' => self::getRequiredMySqlVariables('DEFAULT_STORAGE_ENGINE')] - ] - ); - } - - /** - * set some default config for current DB - * @param SQL $db - */ - public static function prepareDatabase(SQL &$db){ - if($db->name()){ - // set/change default "character set" and "collation" - $db->exec('ALTER DATABASE ' . $db->quotekey($db->name()) - . ' CHARACTER SET ' . self::getRequiredMySqlVariables('CHARACTER_SET_DATABASE') - . ' COLLATE ' . self::getRequiredMySqlVariables('COLLATION_DATABASE') - ); - } - } - - /** - * get required MySQL variable value - * @param string $key - * @return string|null - */ - public static function getRequiredMySqlVariables(string $key) : ?string { - \Base::instance()->exists('REQUIREMENTS[MYSQL][VARS][' . $key . ']', $data); - return $data; - } - - /** - * get logger for DB logging - * @return \Log - */ - static function getLogger() : \Log { - return LogController::getLogger('ERROR'); - } -} \ No newline at end of file diff --git a/app/main/db/sql/mysql/tablemodifier.php b/app/main/db/sql/mysql/tablemodifier.php index 0afa57f0..b28b62f4 100644 --- a/app/main/db/sql/mysql/tablemodifier.php +++ b/app/main/db/sql/mysql/tablemodifier.php @@ -23,7 +23,7 @@ class TableModifier extends SQL\TableModifier { /** * return table foreign key constraints as assoc array * -> if §constraint is passed, constraints are limited to that column - * @param null| \DB\SQL\MySQL\Constraint $constraint + * @param null| SQL\MySQL\Constraint $constraint * @return Constraint[] */ public function listConstraint($constraint = null){ @@ -65,7 +65,7 @@ class TableModifier extends SQL\TableModifier { /** * checks whether a constraint name exists or not * -> does not check constraint params - * @param \DB\SQL\MySQL\Constraint $constraint + * @param SQL\MySQL\Constraint $constraint * @return bool */ public function constraintExists($constraint){ @@ -75,7 +75,7 @@ class TableModifier extends SQL\TableModifier { /** * drop foreign key constraint - * @param \DB\SQL\MySQL\Constraint $constraint + * @param SQL\MySQL\Constraint $constraint */ public function dropConstraint($constraint){ if($constraint->isValid()){ @@ -88,7 +88,7 @@ class TableModifier extends SQL\TableModifier { /** * Add/Update foreign key constraint - * @param \DB\SQL\MySQL\Constraint $constraint + * @param SQL\MySQL\Constraint $constraint */ public function addConstraint($constraint){ @@ -147,7 +147,7 @@ class Column extends SQL\Column { * $constraintData['on-update'] => ON UPDATE action (optional) default: see \DB\SQL\MySQL\Constraint const * * @param array $constraintData - * @return \DB\SQL\MySQL\Constraint + * @return SQL\MySQL\Constraint */ public function newConstraint($constraintData){ diff --git a/app/main/exception/configexception.php b/app/main/exception/configexception.php index bfaa3405..9f2bb033 100644 --- a/app/main/exception/configexception.php +++ b/app/main/exception/configexception.php @@ -1,7 +1,7 @@ no need to init client on __construct() - * maybe it is nerer used... + * maybe it is never used... * @return AbstractClient */ function __invoke() : self { diff --git a/app/main/lib/config.php b/app/main/lib/config.php index 7a10c552..c45e193f 100644 --- a/app/main/lib/config.php +++ b/app/main/lib/config.php @@ -9,6 +9,7 @@ namespace lib; +use lib\db\Pool; use lib\api\CcpClient; use lib\api\GitHubClient; use lib\api\SsoClient; @@ -18,11 +19,34 @@ use lib\socket\TcpSocket; class Config extends \Prefab { + /** + * prefix for custom Pathfinder env vars + */ const PREFIX_KEY = 'PF'; + + /** + * delimiter for custom Pathfinder env vars + */ const ARRAY_DELIMITER = '-'; + + /** + * Hive key for all Pathfinder config vars (*.ini files) + */ const HIVE_KEY_PATHFINDER = 'PATHFINDER'; + + /** + * Hive key for all environment config vars (*.ini files) + */ const HIVE_KEY_ENVIRONMENT = 'ENVIRONMENT'; + + /** + * Hive key for Socket validation check + */ const CACHE_KEY_SOCKET_VALID = 'CACHED_SOCKET_VALID'; + + /** + * Cache time for Socket validation check + */ const CACHE_TTL_SOCKET_VALID = 60; // ================================================================================================================ @@ -58,7 +82,14 @@ class Config extends \Prefab { */ const DOWNTIME_BUFFER = 1; + /** + * error message for missing Composer dependency class + */ const ERROR_CLASS_NOT_EXISTS_COMPOSER = 'Class "%s" not found. → Check installed Composer packages'; + + /** + * error message for missing Composer dependency method + */ const ERROR_METHOD_NOT_EXISTS_COMPOSER = 'Method "%s()" not found in class "%s". → Check installed Composer packages'; @@ -68,6 +99,9 @@ class Config extends \Prefab { */ const ARRAY_KEYS = ['CCP_ESI_SCOPES', 'CCP_ESI_SCOPES_ADMIN']; + /** + * custom HTTP status codes + */ const HTTP_422='Unprocessable Entity'; @@ -103,12 +137,24 @@ class Config extends \Prefab { return new \DateTime($time, $timeZone); }); - // lazy init Web Api clients + // database connection pool ----------------------------------------------------------------------------------- + $f3->set(Pool::POOL_NAME, Pool::instance( + function(string $alias) use ($f3) : array { + // get DB config by alias for new connections + return self::getDatabaseConfig($f3, $alias); + }, + function(string $schema) use ($f3) : array { + // get DB requirement vars from requirements.ini + return self::getRequiredDbVars($f3, $schema); + } + )); + + // lazy init Web Api clients ---------------------------------------------------------------------------------- $f3->set(SsoClient::CLIENT_NAME, SsoClient::instance()); $f3->set(CcpClient::CLIENT_NAME, CcpClient::instance()); $f3->set(GitHubClient::CLIENT_NAME, GitHubClient::instance()); - // Socket connectors + // Socket connectors ------------------------------------------------------------------------------------------ $f3->set(TcpSocket::SOCKET_NAME, function(array $options = ['timeout' => 1]) : SocketInterface { return AbstractSocket::factory(TcpSocket::class, self::getSocketUri(), $options); }); @@ -205,13 +251,13 @@ class Config extends \Prefab { protected function setServerData(){ $data = []; foreach($_SERVER as $key => $value){ - if( strpos($key, self::PREFIX_KEY . self::ARRAY_DELIMITER) === 0 ){ + if(strpos($key, self::PREFIX_KEY . self::ARRAY_DELIMITER) === 0){ $path = explode( self::ARRAY_DELIMITER, $key); // remove prefix array_shift($path); $tmp = &$data; - foreach ($path as $segment) { + foreach($path as $segment){ $tmp[$segment] = (array)$tmp[$segment]; $tmp = &$tmp[$segment]; } @@ -238,32 +284,66 @@ class Config extends \Prefab { /** * get database config values - * @param string $dbKey + * @param \Base $f3 + * @param string $alias * @return array */ - static function getDatabaseConfig(string $dbKey = 'PF') : array { - $dbKey = strtoupper($dbKey); - return [ - 'DNS' => self::getEnvironmentData('DB_' . $dbKey . '_DNS'), - 'NAME' => self::getEnvironmentData('DB_' . $dbKey . '_NAME'), - 'USER' => self::getEnvironmentData('DB_' . $dbKey . '_USER'), - 'PASS' => self::getEnvironmentData('DB_' . $dbKey . '_PASS'), - 'ALIAS' => $dbKey + static function getDatabaseConfig(\Base $f3, string $alias) : array { + $alias = strtoupper($alias); + + $config = [ + 'ALIAS' => $alias, + 'SCHEME' => 'mysql', + 'HOST' => 'localhost', + 'PORT' => 3306, + 'SOCKET' => null, + 'NAME' => self::getEnvironmentData('DB_' . $alias . '_NAME'), + 'USER' => self::getEnvironmentData('DB_' . $alias . '_USER'), + 'PASS' => self::getEnvironmentData('DB_' . $alias . '_PASS') ]; + + $pdoReg = '/^(?[[:alpha:]]+):((host=(?[a-zA-Z0-9\.]*))|(unix_socket=(?[a-zA-Z0-9\/]*\.sock)))((;dbname=(?\w*))|(;port=(?\d*))){0,2}/'; + if(preg_match($pdoReg, self::getEnvironmentData('DB_' . $alias . '_DNS'), $matches)){ + // remove unnamed matches + $matches = array_intersect_key($matches, $config); + // remove empty matches + $matches = array_filter($matches); + // merge matches with default config + $config = array_merge($config, $matches); + } + + // connect options -------------------------------------------------------------------------------------------- + $options = [ + \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, + \PDO::ATTR_TIMEOUT => $f3->get('REQUIREMENTS.MYSQL.PDO_TIMEOUT') + ]; + + if($config['SCHEME'] == 'mysql'){ + $options[\PDO::MYSQL_ATTR_COMPRESS] = true; + $options[\PDO::MYSQL_ATTR_INIT_COMMAND] = implode(',', [ + "SET NAMES " . strtolower(str_replace('-','', $f3->ENCODING)), + "@@session.time_zone = '+00:00'", + "@@session.default_storage_engine = " . self::getRequiredDbVars($f3, $config['SCHEME'])['DEFAULT_STORAGE_ENGINE'] + ]); + } + + if(self::getPathfinderData('experiments.persistent_db_connections')){ + $options[\PDO::ATTR_PERSISTENT] = true; + } + + $config['OPTIONS'] = $options; + + return $config; } /** - * get DB config value from PDO connect $dns string - * @param string $dns - * @param string $key - * @return bool + * get required MySQL variables from requirements.ini + * @param \Base $f3 + * @param string $schema + * @return array */ - static function getDatabaseDNSValue(string $dns, string $key = 'dbname'){ - $value = false; - if(preg_match('/' . preg_quote($key, '/') . '=([[:alnum:]]+)/is', $dns, $parts)){ - $value = $parts[1]; - } - return $value; + static function getRequiredDbVars(\Base $f3, string $schema) : array { + return $f3->exists('REQUIREMENTS[' . strtoupper($schema) . '][VARS]', $vars) ? $vars : []; } /** @@ -354,6 +434,7 @@ class Config extends \Prefab { * This function is intended to pre-check a Socket connection if it MIGHT exists. * No data will be send to the Socket, this function just validates if a socket is available * -> see pingDomain() + * @param string $uri * @return bool */ static function validSocketConnect(string $uri) : bool{ diff --git a/app/main/lib/db/Pool.php b/app/main/lib/db/Pool.php new file mode 100644 index 00000000..a3cbd545 --- /dev/null +++ b/app/main/lib/db/Pool.php @@ -0,0 +1,236 @@ +getConfig = $getConfig; + $this->requiredVars = $requiredVars; + } + + /** + * set "silent" mode (no error logging) + * -> optional clear $this->errors + * @param bool $silent + * @param bool $clearErrors + */ + public function setSilent(bool $silent, bool $clearErrors = false){ + $this->silent = $silent; + if($clearErrors){ + $this->errors = []; + } + } + + /** + * @return bool + */ + public function isSilent() : bool { + return $this->silent; + } + + /** + * connect to the DB server itself -> NO database is used + * -> can be used to check if a certain DB exists without connecting to it directly + * @param string $alias + * @return SQL|null + */ + public function connectToServer(string $alias) : ?SQL { + $config = ($this->getConfig)($alias); + $config['NAME'] = ''; + return $this->newDB($config); + } + + /** + * tries to create a database if not exists + * -> DB user needs rights to create a DB + * @param string $alias + * @return SQL|null + */ + public function createDB(string $alias) : ?SQL { + $db = null; + $config = ($this->getConfig)($alias); + // remove database from $dsn (we want to crate it) + $newDbName = $config['NAME']; + if(!empty($newDbName)){ + $config['NAME'] = ''; + + $db = $this->newDB($config); + if(!is_null($db)){ + $schema = new Schema($db); + if(!in_array($newDbName, $schema->getDatabases())){ + $db->exec("CREATE DATABASE IF NOT EXISTS + `" . $newDbName . "` DEFAULT CHARACTER SET utf8 + COLLATE utf8_general_ci;"); + $db->exec("USE `" . $newDbName . "`"); + + // check if DB create was successful + $dbCheck = $db->exec("SELECT DATABASE()"); + if( + !empty($dbCheck[0]) && + !empty($checkDbName = reset($dbCheck[0])) && + $checkDbName == $newDbName + ){ + // prepare new created DB + $requiredVars = ($this->requiredVars)($db->driver()); + $db->prepareDatabase($requiredVars['CHARACTER_SET_DATABASE'], $requiredVars['COLLATION_DATABASE']); + } + } + } + } + + return $db; + } + + /** + * get active connection from store or init new connection + * @param string $alias + * @return SQL|null + */ + public function getDB(string $alias) : ?SQL { + if(!isset($this->connectionStore[$alias])){ + $db = $this->newDB(($this->getConfig)($alias)); + if(!is_null($db)){ + $this->connectionStore[$alias] = $db; + } + return $db; + }else{ + return $this->connectionStore[$alias]; + } + } + + /** + * get last recent Exceptions from error history + * @param string $alias + * @param int $limit + * @return \Exception[] + */ + public function getErrors(string $alias, int $limit = 1) : array { + return array_slice((array)$this->errors[$alias] , 0, $limit); + } + + /** + * build PDO DNS connect string from DB config array + * -> Hint: dbName is not part of the DNS we need -> passed as extra parameter + * @param array $config + * @return string + */ + protected function buildDnsFromConfig(array $config) : string { + $dns = $config['SCHEME'] . ':'; + $dns .= $config['SOCKET'] ? 'unix_socket=' . $config['SOCKET'] : 'host=' . $config['HOST']; + $dns .= $config['PORT'] && !$config['SOCKET'] ? ';port=' . $config['PORT'] : ''; + $dns .= $config['NAME'] ? ';dbname=' . $config['NAME'] : ''; + return $dns; + } + + /** + * @param array $config + * @return SQL|null + */ + protected function newDB(array $config) : ?SQL { + $db = null; + + if($config['SCHEME'] == 'mysql'){ + try{ + $db = new SQL($this->buildDnsFromConfig($config), $config['USER'], $config['PASS'], $config['OPTIONS']); + }catch(\PDOException $e){ + $this->pushError($config['ALIAS'], $e); + + if(!$this->isSilent()){ + self::getLogger()->write($e); + } + } + }else{ + // unsupported DB type + $this->pushError($config['ALIAS'], new ConfigException( + sprintf(self::ERROR_SCHEME, $config['SCHEME'], $config['ALIAS'])) + ); + } + + return $db; + } + + /** + * push new Exception into static error history + * @param string $alias + * @param \Exception $e + */ + protected function pushError(string $alias, \Exception $e){ + if(!is_array($this->errors[$alias])){ + $this->errors[$alias] = []; + } + + // prevent adding same errors twice + if(!empty($this->errors[$alias])){ + /** + * @var $lastError \Exception + */ + $lastError = array_values($this->errors[$alias])[0]; + if($lastError->getMessage() === $e->getMessage()){ + return; + } + } + + array_unshift($this->errors[$alias], $e); + if(count($this->errors[$alias]) > 5){ + $this->errors[$alias] = array_pop($this->errors[$alias]); + } + } + + /** + * @return \Log + */ + static function getLogger() : \Log { + return LogController::getLogger('ERROR'); + } +} \ No newline at end of file diff --git a/app/main/lib/db/SQL.php b/app/main/lib/db/SQL.php new file mode 100644 index 00000000..b1ea5711 --- /dev/null +++ b/app/main/lib/db/SQL.php @@ -0,0 +1,70 @@ +getTables(); + } + /** + * checks whether a table exists or not + * @param string $table + * @return bool + */ + public function tableExists(string $table) : bool { + return in_array($table, $this->getTables()); + } + + /** + * get current row (data) count for an existing table + * -> returns 0 if table not exists or empty + * @param string $table + * @return int + */ + public function getRowCount(string $table) : int { + $count = 0; + if($this->tableExists($table)){ + $countRes = $this->exec("SELECT COUNT(*) `num` FROM " . $this->quotekey($table)); + if(isset($countRes[0]['num'])){ + $count = (int)$countRes[0]['num']; + } + } + return $count; + } + + /** + * set some default config for this DB + * @param string $characterSetDatabase + * @param string $collationDatabase + */ + public function prepareDatabase(string $characterSetDatabase, string $collationDatabase){ + if($this->name() && $characterSetDatabase && $collationDatabase){ + // set/change default "character set" and "collation" + $this->exec('ALTER DATABASE ' . $this->quotekey($this->name()) + . ' CHARACTER SET ' . $characterSetDatabase + . ' COLLATE ' . $collationDatabase + ); + } + } +} \ No newline at end of file diff --git a/app/main/lib/logging/AbstractChannelLog.php b/app/main/lib/logging/AbstractChannelLog.php index 0bd1803a..3da2b956 100644 --- a/app/main/lib/logging/AbstractChannelLog.php +++ b/app/main/lib/logging/AbstractChannelLog.php @@ -1,7 +1,7 @@ setChannelData($channelData); diff --git a/app/main/lib/logging/AbstractCharacterLog.php b/app/main/lib/logging/AbstractCharacterLog.php index a4083070..17c8bb6f 100644 --- a/app/main/lib/logging/AbstractCharacterLog.php +++ b/app/main/lib/logging/AbstractCharacterLog.php @@ -1,7 +1,7 @@ handlerParamsConfig['stream']) ){ diff --git a/app/main/lib/logging/DefaultLog.php b/app/main/lib/logging/DefaultLog.php index 2653b126..885917d5 100644 --- a/app/main/lib/logging/DefaultLog.php +++ b/app/main/lib/logging/DefaultLog.php @@ -1,7 +1,7 @@ getChannelType() . '_' . $this->getChannelId(); } /** * @return string */ - public function getMessage() : string{ + public function getMessage() : string { return $this->getActionParts()[0] . " '{objName}'"; } /** * @return array */ - public function getData() : array{ + public function getData() : array { $data = parent::getData(); // add system, connection, signature data ------------------------------------------------- @@ -94,7 +94,7 @@ class MapLog extends AbstractCharacterLog{ * @param array $data * @return string */ - protected function formatData(array $data): string{ + protected function formatData(array $data) : string { $actionParts = $this->getActionParts(); $objectString = !empty($data['object']) ? "'" . $data['object']['objName'] . "'" . ' #' . $data['object']['objId'] : ''; $string = ucfirst($actionParts[1]) . 'd ' . $actionParts[0] . " " . $objectString; @@ -103,7 +103,7 @@ class MapLog extends AbstractCharacterLog{ switch($actionParts[1]){ case 'create': case 'update': - $formatChanges = function(array $changes) use ( &$formatChanges ): string{ + $formatChanges = function(array $changes) use (&$formatChanges) : string { $string = ''; foreach($changes as $field => $value){ if(is_array($value)){ @@ -118,7 +118,7 @@ class MapLog extends AbstractCharacterLog{ }elseif(empty($value)){ $formattedValue = "' '"; }elseif(is_string($value)){ - $formattedValue = "'" . $value . "'"; + $formattedValue = "'" . $this->f3->clean($value) . "'"; }else{ $formattedValue = (string)$value; } @@ -143,7 +143,7 @@ class MapLog extends AbstractCharacterLog{ * split $action "CamelCase" wise * @return array */ - protected function getActionParts(): array{ + protected function getActionParts() : array { return array_map('strtolower', preg_split('/(?=[A-Z])/', $this->getAction())); } diff --git a/app/main/lib/logging/RallyLog.php b/app/main/lib/logging/RallyLog.php index bedb7b50..986b359a 100644 --- a/app/main/lib/logging/RallyLog.php +++ b/app/main/lib/logging/RallyLog.php @@ -1,7 +1,7 @@ leave this at a higher value * @var int */ - protected $ttl = 60; + protected $ttl = 60; /** * caching for relational data * @var int */ - protected $rel_ttl = 0; + protected $rel_ttl = 0; /** * ass static columns for this table * -> can be overwritten in child models * @var bool */ - protected $addStaticFields = true; - - /** - * enables check for $fieldChanges on update/insert - * -> fields that should be checked need an "activity-log" flag - * in $fieldConf config - * @var bool - */ - protected $enableActivityLogging = true; + protected $addStaticFields = true; /** * enables change for "active" column @@ -58,61 +49,79 @@ abstract class BasicModel extends \DB\Cortex { * -> $this->active = false; will NOT work (prevent abuse)! * @var bool */ - private $allowActiveChange = false; + private $allowActiveChange = false; /** * getData() cache key prefix * -> do not change, otherwise cached data is lost * @var string */ - private $dataCacheKeyPrefix = 'DATACACHE'; + private $dataCacheKeyPrefix = 'DATACACHE'; /** * enables data export for this table * -> can be overwritten in child models * @var bool */ - public static $enableDataExport = false; + public static $enableDataExport = false; /** * enables data import for this table * -> can be overwritten in child models * @var bool */ - public static $enableDataImport = false; - - /** - * changed fields (columns) on update/insert - * -> e.g. for character "activity logging" - * @var array - */ - protected $fieldChanges = []; + public static $enableDataImport = false; /** * collection for validation errors * @var array */ - protected $validationError = []; + protected $validationError = []; /** * default caching time of field schema - seconds */ - const DEFAULT_TTL = 86400; + const DEFAULT_TTL = 86400; /** * default TTL for getData(); cache - seconds */ - const DEFAULT_CACHE_TTL = 120; + const DEFAULT_CACHE_TTL = 120; /** * default TTL for SQL query cache */ - const DEFAULT_SQL_TTL = 3; + const DEFAULT_SQL_TTL = 3; - const ERROR_INVALID_MODEL_CLASS = 'Model class (%s) not found'; + /** + * data from Universe tables is static and does not change frequently + * -> refresh static data after X days + */ + const CACHE_MAX_DAYS = 60; + /** + * class not exists error + */ + const ERROR_INVALID_MODEL_CLASS = 'Model class (%s) not found'; + + /** + * AbstractModel constructor. + * @param null $db + * @param null $table + * @param null $fluid + * @param int $ttl + */ public function __construct($db = NULL, $table = NULL, $fluid = NULL, $ttl = self::DEFAULT_TTL){ + if(!is_object($db)){ + $db = self::getF3()->DB->getDB(static::DB_ALIAS); + } + + if(is_null($db)){ + // no valid DB connection found -> break on error + self::getF3()->set('HALT', true); + } + $this->addStaticFieldConfig(); parent::__construct($db, $table, $fluid, $ttl); @@ -136,7 +145,6 @@ abstract class BasicModel extends \DB\Cortex { }); // erase events ------------------------------------------------------------------------------------- - $this->beforeerase(function($self, $pkeys){ return $self->beforeEraseEvent($self, $pkeys); }); @@ -153,17 +161,21 @@ abstract class BasicModel extends \DB\Cortex { * @throws ValidationException */ public function set($key, $val){ + if(is_string($val)){ + $val = trim($val); + } + if( !$this->dry() && $key != 'updated' ){ - if( $this->exists($key) ){ + if($this->exists($key)){ // get raw column data (no objects) $currentVal = $this->get($key, true); if(is_object($val)){ if( - is_subclass_of($val, 'Model\BasicModel') && + is_subclass_of($val, 'Model\AbstractModel') && $val->_id != $currentVal ){ // relational object changed @@ -176,72 +188,13 @@ abstract class BasicModel extends \DB\Cortex { } } - // trim all values - if(is_string($val)){ - $val = trim($val); - } - - if( !$this->validateField($key, $val) ){ + if(!$this->validateField($key, $val)){ $this->throwValidationException($key); - }else{ - $this->checkFieldForActivityLogging($key, $val); } return parent::set($key, $val); } - /** - * change default "activity logging" status - * -> enable/disable - * @param $status - */ - public function setActivityLogging($status){ - $this->enableActivityLogging = (bool) $status; - } - - /** - * check column for value changes, - * --> if column is marked for "activity logging" - * @param string $key - * @param mixed $val - */ - protected function checkFieldForActivityLogging($key, $val){ - if( $this->enableActivityLogging ){ - $fieldConf = $this->fieldConf[$key]; - - // check for value changes if field has "activity logging" active - if($fieldConf['activity-log'] === true){ - if( - is_numeric($val) || - $fieldConf['type'] === Schema::DT_BOOL - ){ - $val = (int)$val; - } - - if(is_object($val)){ - $val = $val->_id; - } - - if( $fieldConf['type'] === self::DT_JSON){ - $currentValue = $this->get($key); - }else{ - $currentValue = $this->get($key, true); - } - - - if($currentValue !== $val){ - // field has changed - if( !array_key_exists($key, $this->fieldChanges) ){ - $this->fieldChanges[$key] = [ - 'old' => $currentValue, - 'new' => $val - ]; - } - } - } - } - } - /** * setter for "active" status * -> default: keep current "active" status @@ -250,7 +203,7 @@ abstract class BasicModel extends \DB\Cortex { * @return mixed */ public function set_active($active){ - if( $this->allowActiveChange ){ + if($this->allowActiveChange){ // allowed to set/change -> reset "allowed" property $this->allowActiveChange = false; }else{ @@ -271,14 +224,14 @@ abstract class BasicModel extends \DB\Cortex { if($this->addStaticFields){ $staticFieldConfig = [ 'created' => [ - 'type' => Schema::DT_TIMESTAMP, - 'default' => Schema::DF_CURRENT_TIMESTAMP, - 'index' => true + 'type' => Schema::DT_TIMESTAMP, + 'default' => Schema::DF_CURRENT_TIMESTAMP, + 'index' => true ], 'updated' => [ - 'type' => Schema::DT_TIMESTAMP, - 'default' => Schema::DF_CURRENT_TIMESTAMP, - 'index' => true + 'type' => Schema::DT_TIMESTAMP, + 'default' => Schema::DF_CURRENT_TIMESTAMP, + 'index' => true ] ]; } @@ -324,7 +277,7 @@ abstract class BasicModel extends \DB\Cortex { * @param $key * @param $val * @return bool - * @throws \Exception\ValidationException + * @throws ValidationException */ protected function validate_notDry($key, $val) : bool { $valid = true; @@ -353,7 +306,6 @@ abstract class BasicModel extends \DB\Cortex { */ protected function validate_notEmpty($key, $val) : bool { $valid = false; - if($colConf = $this->fieldConf[$key]){ switch($colConf['type']){ case Schema::DT_INT: @@ -373,7 +325,7 @@ abstract class BasicModel extends \DB\Cortex { * get key for for all objects in this table * @return string */ - private function getTableCacheKey(){ + private function getTableCacheKey() : string { return $this->dataCacheKeyPrefix .'.' . strtoupper($this->table); } @@ -383,22 +335,22 @@ abstract class BasicModel extends \DB\Cortex { * @param string $dataCacheTableKeyPrefix * @return null|string */ - protected function getCacheKey($dataCacheTableKeyPrefix = ''){ + protected function getCacheKey(string $dataCacheTableKeyPrefix = '') : ?string { $cacheKey = null; // set a model unique cache key if the model is saved - if( $this->id > 0){ + if($this->_id > 0){ $cacheKey = $this->getTableCacheKey(); // check if there is a given key prefix // -> if not, use the standard key. // this is useful for caching multiple data sets according to one row entry - if( !empty($dataCacheTableKeyPrefix) ){ + if(!empty($dataCacheTableKeyPrefix)){ $cacheKey .= '.' . $dataCacheTableKeyPrefix . '_'; }else{ $cacheKey .= '.ID_'; } - $cacheKey .= (string) $this->_id; + $cacheKey .= (string)$this->_id; } return $cacheKey; @@ -407,18 +359,15 @@ abstract class BasicModel extends \DB\Cortex { /** * get cached data from this model * @param string $dataCacheKeyPrefix - optional key prefix - * @return \stdClass|null + * @return mixed|null */ protected function getCacheData($dataCacheKeyPrefix = ''){ $cacheData = null; - // table cache exists // -> check cache for this row data - $cacheKey = $this->getCacheKey($dataCacheKeyPrefix); - if( !is_null($cacheKey) ){ + if(!is_null($cacheKey = $this->getCacheKey($dataCacheKeyPrefix))){ self::getF3()->exists($cacheKey, $cacheData); } - return $cacheData; } @@ -428,7 +377,7 @@ abstract class BasicModel extends \DB\Cortex { * @param string $dataCacheKeyPrefix * @param int $data_ttl */ - public function updateCacheData($cacheData, $dataCacheKeyPrefix = '', $data_ttl = self::DEFAULT_CACHE_TTL){ + public function updateCacheData($cacheData, string $dataCacheKeyPrefix = '', int $data_ttl = self::DEFAULT_CACHE_TTL){ $cacheDataTmp = (array)$cacheData; // check if data should be cached @@ -438,8 +387,7 @@ abstract class BasicModel extends \DB\Cortex { !empty($cacheDataTmp) ){ $cacheKey = $this->getCacheKey($dataCacheKeyPrefix); - - if( !is_null($cacheKey) ){ + if(!is_null($cacheKey)){ self::getF3()->set($cacheKey, $cacheData, $data_ttl); } } @@ -450,8 +398,7 @@ abstract class BasicModel extends \DB\Cortex { * -> see also clearCacheDataWithPrefix(), for more information */ public function clearCacheData(){ - $cacheKey = $this->getCacheKey(); - $this->clearCache($cacheKey); + $this->clearCache($this->getCacheKey()); } /** @@ -459,9 +406,8 @@ abstract class BasicModel extends \DB\Cortex { * -> primarily used by object cache with multiple data caches * @param string $dataCacheKeyPrefix */ - public function clearCacheDataWithPrefix($dataCacheKeyPrefix = ''){ - $cacheKey = $this->getCacheKey($dataCacheKeyPrefix); - $this->clearCache($cacheKey); + public function clearCacheDataWithPrefix(string $dataCacheKeyPrefix = ''){ + $this->clearCache($this->getCacheKey($dataCacheKeyPrefix)); } /** @@ -469,9 +415,9 @@ abstract class BasicModel extends \DB\Cortex { * @param $cacheKey */ private function clearCache($cacheKey){ - if( !empty($cacheKey) ){ + if(!empty($cacheKey)){ $f3 = self::getF3(); - if( $f3->exists($cacheKey) ){ + if($f3->exists($cacheKey)){ $f3->clear($cacheKey); } } @@ -496,29 +442,12 @@ abstract class BasicModel extends \DB\Cortex { throw new DatabaseException($msg); } - /** - * set "updated" field to current timestamp - * this is useful to mark a row as "changed" - */ - protected function setUpdated(){ - if($this->_id > 0){ - $pfDB = DB\Database::instance()->getDB('PF'); - - $pfDB->exec( - ["UPDATE " . $this->table . " SET updated=NOW() WHERE id=:id"], - [ - [':id' => $this->_id] - ] - ); - } - } - /** * checks whether this model is active or not * each model should have an "active" column * @return bool */ - public function isActive(){ + public function isActive() : bool { return (bool)$this->active; } @@ -601,7 +530,6 @@ abstract class BasicModel extends \DB\Cortex { } return $relModel ? : null; - } /** @@ -612,7 +540,7 @@ abstract class BasicModel extends \DB\Cortex { * @param $pkeys * @return bool */ - public function beforeInsertEvent($self, $pkeys){ + public function beforeInsertEvent($self, $pkeys) : bool { if($this->exists('updated')){ $this->touch('updated'); } @@ -637,7 +565,7 @@ abstract class BasicModel extends \DB\Cortex { * @param $pkeys * @return bool */ - public function beforeUpdateEvent($self, $pkeys){ + public function beforeUpdateEvent($self, $pkeys) : bool { return true; } @@ -658,7 +586,7 @@ abstract class BasicModel extends \DB\Cortex { * @param $pkeys * @return bool */ - public function beforeEraseEvent($self, $pkeys){ + public function beforeEraseEvent($self, $pkeys) : bool { return true; } @@ -671,15 +599,6 @@ abstract class BasicModel extends \DB\Cortex { public function afterEraseEvent($self, $pkeys){ } - /** - * function should be overwritten in child classes with access restriction - * @param CharacterModel $characterModel - * @return bool - */ - public function hasAccess(CharacterModel $characterModel) : bool { - return true; - } - /** * function should be overwritten in parent classes * @return bool @@ -704,7 +623,7 @@ abstract class BasicModel extends \DB\Cortex { * @param array $fields * @return bool */ - public function exportData(array $fields = []){ + public function exportData(array $fields = []) : bool { $status = false; if(static::$enableDataExport){ @@ -792,7 +711,7 @@ abstract class BasicModel extends \DB\Cortex { * @param array $tableData * @return array */ - protected function importStaticData($tableData = []){ + protected function importStaticData(array $tableData = []) : array { $rowIDs = []; $addedCount = 0; $updatedCount = 0; @@ -811,7 +730,7 @@ abstract class BasicModel extends \DB\Cortex { } $this->copyfrom($rowData, $fields); $this->save(); - $rowIDs[] = $this->id; + $rowIDs[] = $this->_id; $this->reset(); } @@ -832,7 +751,7 @@ abstract class BasicModel extends \DB\Cortex { * @param string $action * @return Logging\LogInterface */ - protected function newLog($action = '') : Logging\LogInterface{ + protected function newLog(string $action = '') : Logging\LogInterface{ return new Logging\DefaultLog($action); } @@ -867,73 +786,62 @@ abstract class BasicModel extends \DB\Cortex { protected function isOutdated() : bool { $outdated = true; if(!$this->dry()){ - $timezone = $this->getF3()->get('getTimeZone')(); - $currentTime = new \DateTime('now', $timezone); - $updateTime = \DateTime::createFromFormat( - 'Y-m-d H:i:s', - $this->updated, - $timezone - ); - $interval = $updateTime->diff($currentTime); - if($interval->days < Universe\BasicUniverseModel::CACHE_MAX_DAYS){ - $outdated = false; + try{ + $timezone = $this->getF3()->get('getTimeZone')(); + $currentTime = new \DateTime('now', $timezone); + $updateTime = \DateTime::createFromFormat( + 'Y-m-d H:i:s', + $this->updated, + $timezone + ); + $interval = $updateTime->diff($currentTime); + if($interval->days < self::CACHE_MAX_DAYS){ + $outdated = false; + } + }catch(\Exception $e){ + self::getF3()->error($e->getCode(), $e->getMessage(), $e->getTrace()); } } return $outdated; } + /** + * @return mixed + */ public function save(){ + $return = false; try{ - return parent::save(); + $return = parent::save(); }catch(ValidationException $e){ $this->setValidationError($e); }catch(DatabaseException $e){ self::getF3()->error($e->getResponseCode(), $e->getMessage(), $e->getTrace()); } + + return $return; } /** * @return string */ - public function __toString(){ + public function __toString() : string { return $this->getTable(); } /** - * get the current class name - * -> namespace not included - * @return string + * @param string $argument + * @return \ReflectionClass + * @throws \ReflectionException */ - public static function getClassName(){ - $parts = explode('\\', static::class); - return end($parts); + protected static function refClass($argument = self::class) : \ReflectionClass { + return new \ReflectionClass($argument); } /** - * factory for all Models - * @param string $model - * @param int $ttl - * @return BasicModel - * @throws \Exception - */ - public static function getNew($model, $ttl = self::DEFAULT_TTL){ - $class = null; - - $model = '\\' . __NAMESPACE__ . '\\' . $model; - if(class_exists($model)){ - $class = new $model( null, null, null, $ttl ); - }else{ - throw new \Exception(sprintf(self::ERROR_INVALID_MODEL_CLASS, $model)); - } - - return $class; - } - - /** - * get the framework instance (singleton) + * get the framework instance * @return \Base */ - public static function getF3(){ + public static function getF3() : \Base { return \Base::instance(); } @@ -986,12 +894,12 @@ abstract class BasicModel extends \DB\Cortex { /** * get tableModifier class for this table - * @return bool|DB\SQL\TableModifier + * @return bool|\DB\SQL\TableModifier */ public static function getTableModifier(){ $df = parent::resolveConfiguration(); $schema = new Schema($df['db']); - $tableModifier = $schema->alterTable( $df['table'] ); + $tableModifier = $schema->alterTable($df['table']); return $tableModifier; } @@ -1022,7 +930,7 @@ abstract class BasicModel extends \DB\Cortex { * @param int $length index length for text fields in mysql * @return bool */ - public static function setMultiColumnIndex(array $columns = [], $unique = false, $length = 20){ + public static function setMultiColumnIndex(array $columns = [], $unique = false, $length = 20) : bool { $status = false; $tableModifier = self::getTableModifier(); @@ -1037,6 +945,24 @@ abstract class BasicModel extends \DB\Cortex { return $status; } + /** + * factory for all Models + * @param string $className + * @param int $ttl + * @return AbstractModel|null + * @throws \Exception + */ + public static function getNew(string $className, int $ttl = self::DEFAULT_TTL) : ?self { + $model = null; + $className = self::refClass(static::class)->getNamespaceName() . '\\' . $className; + if(class_exists($className)){ + $model = new $className(null, null, null, $ttl); + }else{ + throw new \Exception(sprintf(self::ERROR_INVALID_MODEL_CLASS, $className)); + } + return $model; + } + /** * overwrites parent * @param null $db @@ -1045,12 +971,12 @@ abstract class BasicModel extends \DB\Cortex { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); + public static function setup($db = null, $table = null, $fields = null){ + $status = parent::setup($db, $table, $fields); // set static default data if($status === true && property_exists(static::class, 'tableData')){ - $model = self::getNew(self::getClassName(), 0); + $model = self::getNew(self::refClass(static::class)->getShortName(), 0); $model->importStaticData(static::$tableData); } diff --git a/app/main/model/abstractmaptrackingmodel.php b/app/main/model/pathfinder/abstractmaptrackingmodel.php similarity index 89% rename from app/main/model/abstractmaptrackingmodel.php rename to app/main/model/pathfinder/abstractmaptrackingmodel.php index 9a2cce45..8f4b65cf 100644 --- a/app/main/model/abstractmaptrackingmodel.php +++ b/app/main/model/pathfinder/abstractmaptrackingmodel.php @@ -1,22 +1,25 @@ [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CharacterModel', + 'belongs-to-one' => 'Model\Pathfinder\CharacterModel', 'constraint' => [ [ 'table' => 'character', @@ -28,7 +31,7 @@ abstract class AbstractMapTrackingModel extends BasicModel implements LogModelIn 'updatedCharacterId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CharacterModel', + 'belongs-to-one' => 'Model\Pathfinder\CharacterModel', 'constraint' => [ [ 'table' => 'character', @@ -96,7 +99,6 @@ abstract class AbstractMapTrackingModel extends BasicModel implements LogModelIn return []; } - /** * save connection * @param CharacterModel $characterModel diff --git a/app/main/model/pathfinder/abstractpathfindermodel.php b/app/main/model/pathfinder/abstractpathfindermodel.php new file mode 100644 index 00000000..36a0ac01 --- /dev/null +++ b/app/main/model/pathfinder/abstractpathfindermodel.php @@ -0,0 +1,113 @@ + fields that should be checked need an "activity-log" flag + * in $fieldConf config + * @var bool + */ + protected $enableActivityLogging = true; + + /** + * changed fields (columns) on update/insert + * -> e.g. for character "activity logging" + * @var array + */ + protected $fieldChanges = []; + + /** + * change default "activity logging" status + * -> enable/disable + * @param $status + */ + public function setActivityLogging(bool $status){ + $this->enableActivityLogging = $status; + } + + /** + * @param bool $mapper + * @return NULL|void + */ + public function reset($mapper = true){ + $this->fieldChanges = []; + parent::reset($mapper); + } + + /** + * function should be overwritten in child classes with access restriction + * @param CharacterModel $characterModel + * @return bool + */ + public function hasAccess(CharacterModel $characterModel) : bool { + return true; + } + + /** + * set "updated" field to current timestamp + * this is useful to mark a row as "changed" + */ + protected function setUpdated(){ + if($this->_id > 0){ + $this->db->exec( + ["UPDATE " . $this->table . " SET updated=NOW() WHERE id=:id"], + [ + [':id' => $this->_id] + ] + ); + } + } + + /** + * get old and new value from field, in case field is configured with 'activity-log' + * @return array + */ + protected function getFieldChanges() : array { + $changes = []; + + if($this->enableActivityLogging){ + // filter fields, where "activity" (changes) should be logged + $fieldConf = array_filter($this->fieldConf, function($fieldConf, $key) { + return isset($fieldConf['activity-log']) ? (bool)$fieldConf['activity-log'] : false; + }, ARRAY_FILTER_USE_BOTH); + + if($fieldKeys = array_keys($fieldConf)){ + // model has fields where changes should be logged + $schema = $this->getMapper()->schema(); + foreach($fieldKeys as $key){ + if($this->changed($key)){ + $changes[$key] = [ + 'old' => $schema[$key]['initial'], + 'new' => $schema[$key]['value'] + ]; + } + } + } + } + + return $changes; + } + + /** + * @return mixed|void + */ + public function save(){ + // save changed field value BEFORE ->save() it called! + // parent::save() resets the schema and old values get replaced with new values + $this->fieldChanges = $this->getFieldChanges(); + + parent::save(); + } +} \ No newline at end of file diff --git a/app/main/model/abstractsystemapibasicmodel.php b/app/main/model/pathfinder/abstractsystemapibasicmodel.php similarity index 89% rename from app/main/model/abstractsystemapibasicmodel.php rename to app/main/model/pathfinder/abstractsystemapibasicmodel.php index 66acce0c..ab531f03 100644 --- a/app/main/model/abstractsystemapibasicmodel.php +++ b/app/main/model/pathfinder/abstractsystemapibasicmodel.php @@ -6,11 +6,11 @@ * Time: 22:11 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -abstract class AbstractSystemApiBasicModel extends BasicModel { +abstract class AbstractSystemApiBasicModel extends AbstractPathfinderModel { public function __construct($db = NULL, $table = NULL, $fluid = NULL, $ttl = 0){ $this->addStaticKillFieldConfig(); diff --git a/app/main/model/activitylogmodel.php b/app/main/model/pathfinder/activitylogmodel.php similarity index 93% rename from app/main/model/activitylogmodel.php rename to app/main/model/pathfinder/activitylogmodel.php index 33275cb7..efb8631b 100644 --- a/app/main/model/activitylogmodel.php +++ b/app/main/model/pathfinder/activitylogmodel.php @@ -6,11 +6,11 @@ * Time: 15:11 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class ActivityLogModel extends BasicModel { +class ActivityLogModel extends AbstractPathfinderModel { protected $table = 'activity_log'; @@ -24,7 +24,7 @@ class ActivityLogModel extends BasicModel { 'characterId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CharacterModel', + 'belongs-to-one' => 'Model\Pathfinder\CharacterModel', 'constraint' => [ [ 'table' => 'character', @@ -35,7 +35,7 @@ class ActivityLogModel extends BasicModel { 'mapId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapModel', + 'belongs-to-one' => 'Model\Pathfinder\MapModel', 'constraint' => [ [ 'table' => 'map', @@ -180,16 +180,13 @@ class ActivityLogModel extends BasicModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['year', 'week', 'characterId', 'mapId'], true); if($status === true){ $status = parent::setMultiColumnIndex(['year', 'week', 'characterId']); } } - return $status; } } \ No newline at end of file diff --git a/app/main/model/alliancemapmodel.php b/app/main/model/pathfinder/alliancemapmodel.php similarity index 77% rename from app/main/model/alliancemapmodel.php rename to app/main/model/pathfinder/alliancemapmodel.php index f8e29c5d..2634d514 100644 --- a/app/main/model/alliancemapmodel.php +++ b/app/main/model/pathfinder/alliancemapmodel.php @@ -6,11 +6,11 @@ * Time: 20:14 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class AllianceMapModel extends BasicModel { +class AllianceMapModel extends AbstractPathfinderModel { protected $table = 'alliance_map'; @@ -24,7 +24,7 @@ class AllianceMapModel extends BasicModel { 'allianceId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\AllianceModel', + 'belongs-to-one' => 'Model\Pathfinder\AllianceModel', 'constraint' => [ [ 'table' => 'alliance', @@ -35,7 +35,7 @@ class AllianceMapModel extends BasicModel { 'mapId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapModel', + 'belongs-to-one' => 'Model\Pathfinder\MapModel', 'constraint' => [ [ 'table' => 'map', @@ -59,14 +59,12 @@ class AllianceMapModel extends BasicModel { * @param null $table * @param null $fields * @return bool + * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['allianceId', 'mapId'], true); } - return $status; } } \ No newline at end of file diff --git a/app/main/model/alliancemodel.php b/app/main/model/pathfinder/alliancemodel.php similarity index 91% rename from app/main/model/alliancemodel.php rename to app/main/model/pathfinder/alliancemodel.php index 6c43daf1..1a792f5d 100644 --- a/app/main/model/alliancemodel.php +++ b/app/main/model/pathfinder/alliancemodel.php @@ -6,12 +6,12 @@ * Time: 20:43 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; use lib\Config; -class AllianceModel extends BasicModel { +class AllianceModel extends AbstractPathfinderModel { protected $table = 'alliance'; @@ -38,10 +38,10 @@ class AllianceModel extends BasicModel { 'default' => 0 ], 'allianceCharacters' => [ - 'has-many' => ['Model\CharacterModel', 'allianceId'] + 'has-many' => ['Model\Pathfinder\CharacterModel', 'allianceId'] ], 'mapAlliances' => [ - 'has-many' => ['Model\AllianceMapModel', 'allianceId'] + 'has-many' => ['Model\Pathfinder\AllianceMapModel', 'allianceId'] ] ]; @@ -57,7 +57,7 @@ class AllianceModel extends BasicModel { $allianceData->shared = $this->shared; return $allianceData; - } + }/** @noinspection PhpHierarchyChecksInspection */ /** * Event "Hook" function @@ -66,7 +66,7 @@ class AllianceModel extends BasicModel { * @param $pkeys * @return bool */ - public function beforeUpdateEvent($self, $pkeys){ + public function beforeUpdateEvent($self, $pkeys) : bool { // if model changed, 'update' col needs to be updated as well // -> data no longer "outdated" $this->touch('updated'); diff --git a/app/main/model/characterauthenticationmodel.php b/app/main/model/pathfinder/characterauthenticationmodel.php similarity index 87% rename from app/main/model/characterauthenticationmodel.php rename to app/main/model/pathfinder/characterauthenticationmodel.php index 3b2ab69e..b80e773b 100644 --- a/app/main/model/characterauthenticationmodel.php +++ b/app/main/model/pathfinder/characterauthenticationmodel.php @@ -6,12 +6,12 @@ * Time: 19:33 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; use Controller; -class CharacterAuthenticationModel extends BasicModel{ +class CharacterAuthenticationModel extends AbstractPathfinderModel{ protected $table = 'character_authentication'; @@ -25,7 +25,7 @@ class CharacterAuthenticationModel extends BasicModel{ 'characterId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CharacterModel', + 'belongs-to-one' => 'Model\Pathfinder\CharacterModel', 'constraint' => [ [ 'table' => 'character', @@ -61,12 +61,11 @@ class CharacterAuthenticationModel extends BasicModel{ * @param $pkeys * @return bool */ - public function beforeEraseEvent($self, $pkeys){ + public function beforeEraseEvent($self, $pkeys) : bool { // clear existing client Cookies as well $cookieName = Controller\Controller::COOKIE_PREFIX_CHARACTER; $cookieName .= '_' . $this->characterId->getCookieName(); $self::getF3()->clear('COOKIE.' . $cookieName); - return true; } diff --git a/app/main/model/characterlogmodel.php b/app/main/model/pathfinder/characterlogmodel.php similarity index 97% rename from app/main/model/characterlogmodel.php rename to app/main/model/pathfinder/characterlogmodel.php index c1017e3b..2394e650 100644 --- a/app/main/model/characterlogmodel.php +++ b/app/main/model/pathfinder/characterlogmodel.php @@ -6,13 +6,13 @@ * Time: 00:04 */ -namespace Model; +namespace Model\Pathfinder; use Controller\Api\User as User; use Controller\Controller as Controller; use DB\SQL\Schema; -class CharacterLogModel extends BasicModel { +class CharacterLogModel extends AbstractPathfinderModel { protected $table = 'character_log'; @@ -27,7 +27,7 @@ class CharacterLogModel extends BasicModel { 'type' => Schema::DT_INT, 'index' => true, 'unique' => true, - 'belongs-to-one' => 'Model\CharacterModel', + 'belongs-to-one' => 'Model\Pathfinder\CharacterModel', 'constraint' => [ [ 'table' => 'character', @@ -198,7 +198,7 @@ class CharacterLogModel extends BasicModel { */ public function afterUpdateEvent($self, $pkeys){ // check if any "relevant" column has changed - if( !empty($this->fieldChanges) ){ + if(!empty($this->fieldChanges)){ $self->clearCacheData(); } } diff --git a/app/main/model/charactermapmodel.php b/app/main/model/pathfinder/charactermapmodel.php similarity index 79% rename from app/main/model/charactermapmodel.php rename to app/main/model/pathfinder/charactermapmodel.php index 846a65a8..688ce91e 100644 --- a/app/main/model/charactermapmodel.php +++ b/app/main/model/pathfinder/charactermapmodel.php @@ -6,11 +6,11 @@ * Time: 12:31 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class CharacterMapModel extends BasicModel { +class CharacterMapModel extends AbstractPathfinderModel { protected $table = 'character_map'; @@ -24,7 +24,7 @@ class CharacterMapModel extends BasicModel { 'characterId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CharacterModel', + 'belongs-to-one' => 'Model\Pathfinder\CharacterModel', 'constraint' => [ [ 'table' => 'character', @@ -35,7 +35,7 @@ class CharacterMapModel extends BasicModel { 'mapId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapModel', + 'belongs-to-one' => 'Model\Pathfinder\MapModel', 'constraint' => [ [ 'table' => 'map', @@ -61,13 +61,10 @@ class CharacterMapModel extends BasicModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['characterId', 'mapId'], true); } - return $status; } diff --git a/app/main/model/charactermodel.php b/app/main/model/pathfinder/charactermodel.php similarity index 98% rename from app/main/model/charactermodel.php rename to app/main/model/pathfinder/charactermodel.php index 375e72cc..aed8effe 100644 --- a/app/main/model/charactermodel.php +++ b/app/main/model/pathfinder/charactermodel.php @@ -6,7 +6,7 @@ * Time: 15:20 */ -namespace Model; +namespace Model\Pathfinder; use Controller\Ccp\Sso as Sso; use Controller\Api\User as User; @@ -14,7 +14,7 @@ use DB\SQL\Schema; use lib\Config; use Model\Universe; -class CharacterModel extends BasicModel { +class CharacterModel extends AbstractPathfinderModel { protected $table = 'character'; @@ -92,7 +92,7 @@ class CharacterModel extends BasicModel { 'corporationId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CorporationModel', + 'belongs-to-one' => 'Model\Pathfinder\CorporationModel', 'constraint' => [ [ 'table' => 'corporation', @@ -103,7 +103,7 @@ class CharacterModel extends BasicModel { 'allianceId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\AllianceModel', + 'belongs-to-one' => 'Model\Pathfinder\AllianceModel', 'constraint' => [ [ 'table' => 'alliance', @@ -116,7 +116,7 @@ class CharacterModel extends BasicModel { 'nullable' => false, 'default' => 1, 'index' => true, - 'belongs-to-one' => 'Model\RoleModel', + 'belongs-to-one' => 'Model\Pathfinder\RoleModel', 'constraint' => [ [ 'table' => 'role', @@ -153,16 +153,16 @@ class CharacterModel extends BasicModel { 'default' => 0 ], 'userCharacter' => [ - 'has-one' => ['Model\UserCharacterModel', 'characterId'] + 'has-one' => ['Model\Pathfinder\UserCharacterModel', 'characterId'] ], 'characterLog' => [ - 'has-one' => ['Model\CharacterLogModel', 'characterId'] + 'has-one' => ['Model\Pathfinder\CharacterLogModel', 'characterId'] ], 'characterMaps' => [ - 'has-many' => ['Model\CharacterMapModel', 'characterId'] + 'has-many' => ['Model\Pathfinder\CharacterMapModel', 'characterId'] ], 'characterAuthentications' => [ - 'has-many' => ['Model\CharacterAuthenticationModel', 'characterId'] + 'has-many' => ['Model\Pathfinder\CharacterAuthenticationModel', 'characterId'] ] ]; @@ -861,7 +861,7 @@ class CharacterModel extends BasicModel { /** * @var $structureModel Universe\StructureModel */ - $structureModel = Universe\BasicUniverseModel::getNew('StructureModel'); + $structureModel = Universe\AbstractUniverseModel::getNew('StructureModel'); $structureModel->loadById($lookupStructureId, $accessToken, $additionalOptions); if(!$structureModel->dry()){ $structureData['structure'] = (array)$structureModel->getData(); @@ -900,7 +900,7 @@ class CharacterModel extends BasicModel { /** * @var $typeModel Universe\TypeModel */ - $typeModel = Universe\BasicUniverseModel::getNew('TypeModel'); + $typeModel = Universe\AbstractUniverseModel::getNew('TypeModel'); $typeModel->loadById($lookupShipTypeId, '', $additionalOptions); if(!$typeModel->dry()){ $shipData['ship'] = (array)$typeModel->getShipData(); diff --git a/app/main/model/characterstatusmodel.php b/app/main/model/pathfinder/characterstatusmodel.php similarity index 92% rename from app/main/model/characterstatusmodel.php rename to app/main/model/pathfinder/characterstatusmodel.php index 21fb7435..1d5eab8f 100644 --- a/app/main/model/characterstatusmodel.php +++ b/app/main/model/pathfinder/characterstatusmodel.php @@ -6,11 +6,11 @@ * Time: 21:12 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class CharacterStatusModel extends BasicModel { +class CharacterStatusModel extends AbstractPathfinderModel { protected $table = 'character_status'; diff --git a/app/main/model/connectionlogmodel.php b/app/main/model/pathfinder/connectionlogmodel.php similarity index 95% rename from app/main/model/connectionlogmodel.php rename to app/main/model/pathfinder/connectionlogmodel.php index 3f7b7bad..8f3aab9c 100644 --- a/app/main/model/connectionlogmodel.php +++ b/app/main/model/pathfinder/connectionlogmodel.php @@ -1,16 +1,16 @@ [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\ConnectionModel', + 'belongs-to-one' => 'Model\Pathfinder\ConnectionModel', 'constraint' => [ [ 'table' => 'connection', diff --git a/app/main/model/connectionmodel.php b/app/main/model/pathfinder/connectionmodel.php similarity index 93% rename from app/main/model/connectionmodel.php rename to app/main/model/pathfinder/connectionmodel.php index f4260d36..f2672ca7 100644 --- a/app/main/model/connectionmodel.php +++ b/app/main/model/pathfinder/connectionmodel.php @@ -6,7 +6,7 @@ * Time: 21:12 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; use Controller\Api\Route; @@ -26,7 +26,7 @@ class ConnectionModel extends AbstractMapTrackingModel { 'mapId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapModel', + 'belongs-to-one' => 'Model\Pathfinder\MapModel', 'constraint' => [ [ 'table' => 'map', @@ -37,7 +37,7 @@ class ConnectionModel extends AbstractMapTrackingModel { 'source' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\SystemModel', + 'belongs-to-one' => 'Model\Pathfinder\SystemModel', 'constraint' => [ [ 'table' => 'system', @@ -49,7 +49,7 @@ class ConnectionModel extends AbstractMapTrackingModel { 'target' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\SystemModel', + 'belongs-to-one' => 'Model\Pathfinder\SystemModel', 'constraint' => [ [ 'table' => 'system', @@ -73,10 +73,10 @@ class ConnectionModel extends AbstractMapTrackingModel { 'default' => null ], 'signatures' => [ - 'has-many' => ['Model\SystemSignatureModel', 'connectionId'] + 'has-many' => ['Model\Pathfinder\SystemSignatureModel', 'connectionId'] ], 'connectionLog' => [ - 'has-many' => ['Model\ConnectionLogModel', 'connectionId'] + 'has-many' => ['Model\Pathfinder\ConnectionLogModel', 'connectionId'] ] ]; @@ -190,7 +190,7 @@ class ConnectionModel extends AbstractMapTrackingModel { * @return bool * @throws \Exception\DatabaseException */ - public function isValid(): bool { + public function isValid() : bool { if($valid = parent::isValid()){ // check if source/target system are not equal // check if source/target belong to same map @@ -211,12 +211,12 @@ class ConnectionModel extends AbstractMapTrackingModel { * Event "Hook" function * can be overwritten * return false will stop any further action - * @param BasicModel $self + * @param self $self * @param $pkeys * @return bool * @throws \Exception\DatabaseException */ - public function beforeInsertEvent($self, $pkeys){ + public function beforeInsertEvent($self, $pkeys) : bool { // check for "default" connection type and add them if missing // -> get() with "true" returns RAW data! important for JSON table column check! $types = (array)json_decode($this->get('type', true)); @@ -268,14 +268,14 @@ class ConnectionModel extends AbstractMapTrackingModel { * @return logging\LogInterface * @throws \Exception\ConfigException */ - public function newLog($action = ''): Logging\LogInterface{ + public function newLog($action = '') : Logging\LogInterface { return $this->getMap()->newLog($action)->setTempData($this->getLogObjectData()); } /** * @return MapModel */ - public function getMap(): MapModel{ + public function getMap() : MapModel{ return $this->get('mapId'); } @@ -414,13 +414,10 @@ class ConnectionModel extends AbstractMapTrackingModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['source', 'target', 'scope']); } - return $status; } } \ No newline at end of file diff --git a/app/main/model/connectionscopemodel.php b/app/main/model/pathfinder/connectionscopemodel.php similarity index 94% rename from app/main/model/connectionscopemodel.php rename to app/main/model/pathfinder/connectionscopemodel.php index 32525887..fd9c3021 100644 --- a/app/main/model/connectionscopemodel.php +++ b/app/main/model/pathfinder/connectionscopemodel.php @@ -6,11 +6,11 @@ * Time: 20:01 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class ConnectionScopeModel extends BasicModel{ +class ConnectionScopeModel extends AbstractPathfinderModel { protected $table = 'connection_scope'; diff --git a/app/main/model/corporationmapmodel.php b/app/main/model/pathfinder/corporationmapmodel.php similarity index 78% rename from app/main/model/corporationmapmodel.php rename to app/main/model/pathfinder/corporationmapmodel.php index d95652fb..5cdcc571 100644 --- a/app/main/model/corporationmapmodel.php +++ b/app/main/model/pathfinder/corporationmapmodel.php @@ -6,11 +6,11 @@ * Time: 20:01 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class CorporationMapModel extends BasicModel { +class CorporationMapModel extends AbstractPathfinderModel { protected $table = 'corporation_map'; @@ -24,7 +24,7 @@ class CorporationMapModel extends BasicModel { 'corporationId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CorporationModel', + 'belongs-to-one' => 'Model\Pathfinder\CorporationModel', 'constraint' => [ [ 'table' => 'corporation', @@ -35,7 +35,7 @@ class CorporationMapModel extends BasicModel { 'mapId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapModel', + 'belongs-to-one' => 'Model\Pathfinder\MapModel', 'constraint' => [ [ 'table' => 'map', @@ -61,13 +61,10 @@ class CorporationMapModel extends BasicModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['corporationId', 'mapId'], true); } - return $status; } } \ No newline at end of file diff --git a/app/main/model/corporationmodel.php b/app/main/model/pathfinder/corporationmodel.php similarity index 95% rename from app/main/model/corporationmodel.php rename to app/main/model/pathfinder/corporationmodel.php index fe80bca6..c6fbf478 100644 --- a/app/main/model/corporationmodel.php +++ b/app/main/model/pathfinder/corporationmodel.php @@ -6,12 +6,12 @@ * Time: 20:43 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; use lib\Config; -class CorporationModel extends BasicModel { +class CorporationModel extends AbstractPathfinderModel { protected $table = 'corporation'; @@ -124,19 +124,19 @@ class CorporationModel extends BasicModel { 'default' => 0 ], 'corporationCharacters' => [ - 'has-many' => ['Model\CharacterModel', 'corporationId'] + 'has-many' => ['Model\Pathfinder\CharacterModel', 'corporationId'] ], 'mapCorporations' => [ - 'has-many' => ['Model\CorporationMapModel', 'corporationId'] + 'has-many' => ['Model\Pathfinder\CorporationMapModel', 'corporationId'] ], 'corporationRights' => [ - 'has-many' => ['Model\CorporationRightModel', 'corporationId'] + 'has-many' => ['Model\Pathfinder\CorporationRightModel', 'corporationId'] ], 'corporationStructures' => [ - 'has-many' => ['Model\CorporationStructureModel', 'corporationId'] + 'has-many' => ['Model\Pathfinder\CorporationStructureModel', 'corporationId'] ], 'structures' => [ - 'has-many' => ['Model\StructureModel', 'corporationId'] + 'has-many' => ['Model\Pathfinder\StructureModel', 'corporationId'] ] ]; @@ -171,7 +171,7 @@ class CorporationModel extends BasicModel { * @param $pkeys * @return bool */ - public function beforeUpdateEvent($self, $pkeys){ + public function beforeUpdateEvent($self, $pkeys) : bool { // if model changed, 'update' col needs to be updated as well // -> data no longer "outdated" $this->touch('updated'); diff --git a/app/main/model/corporationrightmodel.php b/app/main/model/pathfinder/corporationrightmodel.php similarity index 81% rename from app/main/model/corporationrightmodel.php rename to app/main/model/pathfinder/corporationrightmodel.php index 9ef95c6c..1587968c 100644 --- a/app/main/model/corporationrightmodel.php +++ b/app/main/model/pathfinder/corporationrightmodel.php @@ -1,19 +1,25 @@ [ 'type' => Schema::DT_BOOL, @@ -24,7 +30,7 @@ class CorporationRightModel extends BasicModel { 'corporationId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CorporationModel', + 'belongs-to-one' => 'Model\Pathfinder\CorporationModel', 'constraint' => [ [ 'table' => 'corporation', @@ -35,7 +41,7 @@ class CorporationRightModel extends BasicModel { 'rightId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\RightModel', + 'belongs-to-one' => 'Model\Pathfinder\RightModel', 'constraint' => [ [ 'table' => 'right', @@ -46,7 +52,7 @@ class CorporationRightModel extends BasicModel { 'roleId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\RoleModel', + 'belongs-to-one' => 'Model\Pathfinder\RoleModel', 'constraint' => [ [ 'table' => 'role', @@ -95,13 +101,10 @@ class CorporationRightModel extends BasicModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['corporationId', 'rightId'], true); } - return $status; } } \ No newline at end of file diff --git a/app/main/model/corporationstructuremodel.php b/app/main/model/pathfinder/corporationstructuremodel.php similarity index 75% rename from app/main/model/corporationstructuremodel.php rename to app/main/model/pathfinder/corporationstructuremodel.php index d52366cd..5dcfe47b 100644 --- a/app/main/model/corporationstructuremodel.php +++ b/app/main/model/pathfinder/corporationstructuremodel.php @@ -1,16 +1,16 @@ [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CorporationModel', + 'belongs-to-one' => 'Model\Pathfinder\CorporationModel', 'constraint' => [ [ 'table' => 'corporation', @@ -35,7 +35,7 @@ class CorporationStructureModel extends BasicModel { 'structureId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\StructureModel', + 'belongs-to-one' => 'Model\Pathfinder\StructureModel', 'constraint' => [ [ 'table' => 'structure', @@ -53,13 +53,10 @@ class CorporationStructureModel extends BasicModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['corporationId', 'structureId'], true); } - return $status; } } \ No newline at end of file diff --git a/app/main/model/logmodelinterface.php b/app/main/model/pathfinder/logmodelinterface.php similarity index 83% rename from app/main/model/logmodelinterface.php rename to app/main/model/pathfinder/logmodelinterface.php index cca816aa..aa145a57 100644 --- a/app/main/model/logmodelinterface.php +++ b/app/main/model/pathfinder/logmodelinterface.php @@ -1,12 +1,12 @@ [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapScopeModel', + 'belongs-to-one' => 'Model\Pathfinder\MapScopeModel', 'constraint' => [ [ 'table' => 'map_scope', @@ -50,7 +50,7 @@ class MapModel extends AbstractMapTrackingModel { 'typeId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapTypeModel', + 'belongs-to-one' => 'Model\Pathfinder\MapTypeModel', 'constraint' => [ [ 'table' => 'map_type', @@ -152,19 +152,19 @@ class MapModel extends AbstractMapTrackingModel { 'validate' => true ], 'systems' => [ - 'has-many' => ['Model\SystemModel', 'mapId'] + 'has-many' => ['Model\Pathfinder\SystemModel', 'mapId'] ], 'connections' => [ - 'has-many' => ['Model\ConnectionModel', 'mapId'] + 'has-many' => ['Model\Pathfinder\ConnectionModel', 'mapId'] ], 'mapCharacters' => [ - 'has-many' => ['Model\CharacterMapModel', 'mapId'] + 'has-many' => ['Model\Pathfinder\CharacterMapModel', 'mapId'] ], 'mapCorporations' => [ - 'has-many' => ['Model\CorporationMapModel', 'mapId'] + 'has-many' => ['Model\Pathfinder\CorporationMapModel', 'mapId'] ], 'mapAlliances' => [ - 'has-many' => ['Model\AllianceMapModel', 'mapId'] + 'has-many' => ['Model\Pathfinder\AllianceMapModel', 'mapId'] ] ]; @@ -1421,7 +1421,7 @@ class MapModel extends AbstractMapTrackingModel { /** * @param CharacterModel|null $characterModel - * @return false|MapModel + * @return false|ConnectionModel|MapModel */ public function save(CharacterModel $characterModel = null){ /** diff --git a/app/main/model/mapscopemodel.php b/app/main/model/pathfinder/mapscopemodel.php similarity index 92% rename from app/main/model/mapscopemodel.php rename to app/main/model/pathfinder/mapscopemodel.php index 372961fa..9ae22291 100644 --- a/app/main/model/mapscopemodel.php +++ b/app/main/model/pathfinder/mapscopemodel.php @@ -6,11 +6,11 @@ * Time: 20:01 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class MapScopeModel extends BasicModel{ +class MapScopeModel extends AbstractPathfinderModel{ protected $table = 'map_scope'; diff --git a/app/main/model/maptypemodel.php b/app/main/model/pathfinder/maptypemodel.php similarity index 96% rename from app/main/model/maptypemodel.php rename to app/main/model/pathfinder/maptypemodel.php index fed21ecd..c25f2d6a 100644 --- a/app/main/model/maptypemodel.php +++ b/app/main/model/pathfinder/maptypemodel.php @@ -6,11 +6,11 @@ * Time: 20:01 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class MapTypeModel extends BasicModel { +class MapTypeModel extends AbstractPathfinderModel { protected $table = 'map_type'; diff --git a/app/main/model/rightmodel.php b/app/main/model/pathfinder/rightmodel.php similarity index 90% rename from app/main/model/rightmodel.php rename to app/main/model/pathfinder/rightmodel.php index 624c7638..71dd0fa3 100644 --- a/app/main/model/rightmodel.php +++ b/app/main/model/pathfinder/rightmodel.php @@ -1,16 +1,16 @@ '' ], 'corporationRights' => [ - 'has-many' => ['Model\CorporationRightModel', 'rightId'] + 'has-many' => ['Model\Pathfinder\CorporationRightModel', 'rightId'] ] ]; diff --git a/app/main/model/rolemodel.php b/app/main/model/pathfinder/rolemodel.php similarity index 94% rename from app/main/model/rolemodel.php rename to app/main/model/pathfinder/rolemodel.php index c0085ef9..75763924 100644 --- a/app/main/model/rolemodel.php +++ b/app/main/model/pathfinder/rolemodel.php @@ -1,16 +1,16 @@ '' ], 'corporationRights' => [ - 'has-many' => ['Model\CorporationRightModel', 'roleId'] + 'has-many' => ['Model\Pathfinder\CorporationRightModel', 'roleId'] ] ]; diff --git a/app/main/model/structuremodel.php b/app/main/model/pathfinder/structuremodel.php similarity index 93% rename from app/main/model/structuremodel.php rename to app/main/model/pathfinder/structuremodel.php index c47349c2..3f3b64d4 100644 --- a/app/main/model/structuremodel.php +++ b/app/main/model/pathfinder/structuremodel.php @@ -1,17 +1,18 @@ [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\CorporationModel', + 'belongs-to-one' => 'Model\Pathfinder\CorporationModel', 'constraint' => [ [ 'table' => 'corporation', @@ -57,7 +58,7 @@ class StructureModel extends BasicModel { 'type' => Schema::DT_INT, 'default' => 1, 'index' => true, - 'belongs-to-one' => 'Model\StructureStatusModel', + 'belongs-to-one' => 'Model\Pathfinder\StructureStatusModel', 'constraint' => [ [ 'table' => 'structure_status', @@ -76,7 +77,7 @@ class StructureModel extends BasicModel { 'default' => '' ], 'structureCorporations' => [ - 'has-many' => ['Model\CorporationStructureModel', 'structureId'] + 'has-many' => ['Model\Pathfinder\CorporationStructureModel', 'structureId'] ] ]; @@ -189,11 +190,11 @@ class StructureModel extends BasicModel { * Event "Hook" function * can be overwritten * return false will stop any further action - * @param BasicModel $self + * @param self $self * @param $pkeys * @return bool */ - public function beforeInsertEvent($self, $pkeys){ + public function beforeInsertEvent($self, $pkeys) : bool { return $this->isValid() ? parent::beforeInsertEvent($self, $pkeys) : false; } @@ -264,7 +265,7 @@ class StructureModel extends BasicModel { /** * @var $type Universe\TypeModel */ - $type = Universe\BasicUniverseModel::getNew('TypeModel'); + $type = Universe\AbstractUniverseModel::getNew('TypeModel'); $type->getById($structureId); return $type->dry() ? (object)[] : $type->getData(); } diff --git a/app/main/model/structurestatusmodel.php b/app/main/model/pathfinder/structurestatusmodel.php similarity index 91% rename from app/main/model/structurestatusmodel.php rename to app/main/model/pathfinder/structurestatusmodel.php index 22e38d80..bb37d6f1 100644 --- a/app/main/model/structurestatusmodel.php +++ b/app/main/model/pathfinder/structurestatusmodel.php @@ -1,17 +1,17 @@ '' ], 'structures' => [ - 'has-many' => ['Model\StructureModel', 'statusId'] + 'has-many' => ['Model\Pathfinder\StructureModel', 'statusId'] ] ]; diff --git a/app/main/model/systemfactionkillmodel.php b/app/main/model/pathfinder/systemfactionkillmodel.php similarity index 95% rename from app/main/model/systemfactionkillmodel.php rename to app/main/model/pathfinder/systemfactionkillmodel.php index 1eab973f..2d4d7f6b 100644 --- a/app/main/model/systemfactionkillmodel.php +++ b/app/main/model/pathfinder/systemfactionkillmodel.php @@ -6,7 +6,7 @@ * Time: 21:04 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; diff --git a/app/main/model/systemjumpmodel.php b/app/main/model/pathfinder/systemjumpmodel.php similarity index 95% rename from app/main/model/systemjumpmodel.php rename to app/main/model/pathfinder/systemjumpmodel.php index afc43b25..885a5534 100644 --- a/app/main/model/systemjumpmodel.php +++ b/app/main/model/pathfinder/systemjumpmodel.php @@ -6,7 +6,7 @@ * Time: 21:04 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; diff --git a/app/main/model/systemmodel.php b/app/main/model/pathfinder/systemmodel.php similarity index 95% rename from app/main/model/systemmodel.php rename to app/main/model/pathfinder/systemmodel.php index 268d4a40..7fe7b072 100644 --- a/app/main/model/systemmodel.php +++ b/app/main/model/pathfinder/systemmodel.php @@ -6,7 +6,7 @@ * Time: 23:56 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; use lib\logging; @@ -63,7 +63,7 @@ class SystemModel extends AbstractMapTrackingModel { 'mapId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\MapModel', + 'belongs-to-one' => 'Model\Pathfinder\MapModel', 'constraint' => [ [ 'table' => 'map', @@ -85,7 +85,7 @@ class SystemModel extends AbstractMapTrackingModel { 'typeId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\SystemTypeModel', + 'belongs-to-one' => 'Model\Pathfinder\SystemTypeModel', 'constraint' => [ [ 'table' => 'system_type', @@ -98,7 +98,7 @@ class SystemModel extends AbstractMapTrackingModel { 'nullable' => false, 'default' => 1, 'index' => true, - 'belongs-to-one' => 'Model\SystemStatusModel', + 'belongs-to-one' => 'Model\Pathfinder\SystemStatusModel', 'constraint' => [ [ 'table' => 'system_status', @@ -140,13 +140,13 @@ class SystemModel extends AbstractMapTrackingModel { 'default' => 0 ], 'signatures' => [ - 'has-many' => ['Model\SystemSignatureModel', 'systemId'] + 'has-many' => ['Model\Pathfinder\SystemSignatureModel', 'systemId'] ], 'connectionsSource' => [ - 'has-many' => ['Model\ConnectionModel', 'source'] + 'has-many' => ['Model\Pathfinder\ConnectionModel', 'source'] ], 'connectionsTarget' => [ - 'has-many' => ['Model\ConnectionModel', 'target'] + 'has-many' => ['Model\Pathfinder\ConnectionModel', 'target'] ] ]; @@ -224,6 +224,10 @@ class SystemModel extends AbstractMapTrackingModel { $systemData->planets = $this->planets ? : []; $systemData->statics = $this->statics ? : []; + if(is_object($this->faction)){ + $systemData->faction = $this->faction; + } + // max caching time for a system // the cached date has to be cleared manually on any change // this includes system, connection,... changes (all dependencies) @@ -259,7 +263,7 @@ class SystemModel extends AbstractMapTrackingModel { */ private function getStaticSystemValue(string $key){ $value = null; - if( $staticData = $this->getStaticSystemData()){ + if($staticData = $this->getStaticSystemData()){ if(isset($staticData->$key)){ $value = $staticData->$key; } @@ -273,7 +277,7 @@ class SystemModel extends AbstractMapTrackingModel { * @return bool * @throws \Exception */ - protected function validate_systemId(string $key, int $val): bool { + protected function validate_systemId(string $key, int $val) : bool { $valid = true; // check if static system data exists for systemId = $val if( !(bool)(new Universe())->getSystemData($val) ){ @@ -290,7 +294,7 @@ class SystemModel extends AbstractMapTrackingModel { * @return bool * @throws \Exception\ValidationException */ - protected function validate_statusId(string $key, int $val): bool { + protected function validate_statusId(string $key, int $val) : bool { $valid = true; if( !$this->rel('statusId')::getStatusById($val) ){ $valid = false; @@ -306,7 +310,7 @@ class SystemModel extends AbstractMapTrackingModel { * @return bool * @throws \Exception\ValidationException */ - protected function validate_description(string $key, string $val): bool { + protected function validate_description(string $key, string $val) : bool { $valid = true; if(mb_strlen($val) > 9000){ $valid = false; @@ -431,6 +435,10 @@ class SystemModel extends AbstractMapTrackingModel { return ($constellationData && $constellationData->region) ? $constellationData->region->name : null; } + public function get_faction(){ + return $this->getStaticSystemValue('faction'); + } + public function get_security(){ return $this->getStaticSystemValue('security'); } @@ -472,7 +480,7 @@ class SystemModel extends AbstractMapTrackingModel { * @param $pkeys * @return bool */ - public function beforeUpdateEvent($self, $pkeys){ + public function beforeUpdateEvent($self, $pkeys) : bool { $status = parent::beforeUpdateEvent($self, $pkeys); if( !$self->isActive()){ @@ -530,14 +538,14 @@ class SystemModel extends AbstractMapTrackingModel { * @return logging\LogInterface * @throws \Exception\ConfigException */ - public function newLog($action = ''): Logging\LogInterface{ + public function newLog($action = '') : Logging\LogInterface{ return $this->getMap()->newLog($action)->setTempData($this->getLogObjectData()); } /** * @return MapModel */ - public function getMap(): MapModel{ + public function getMap() : MapModel{ return $this->get('mapId'); } @@ -854,10 +862,8 @@ class SystemModel extends AbstractMapTrackingModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['mapId', 'systemId'], true); } diff --git a/app/main/model/systemneighbourmodel.php b/app/main/model/pathfinder/systemneighbourmodel.php similarity index 91% rename from app/main/model/systemneighbourmodel.php rename to app/main/model/pathfinder/systemneighbourmodel.php index 8ec8f9d2..289ded4f 100644 --- a/app/main/model/systemneighbourmodel.php +++ b/app/main/model/pathfinder/systemneighbourmodel.php @@ -6,11 +6,11 @@ * Time: 00:59 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class SystemNeighbourModel extends BasicModel { +class SystemNeighbourModel extends AbstractPathfinderModel { protected $table = 'system_neighbour'; diff --git a/app/main/model/systempodkillmodel.php b/app/main/model/pathfinder/systempodkillmodel.php similarity index 95% rename from app/main/model/systempodkillmodel.php rename to app/main/model/pathfinder/systempodkillmodel.php index 932f110d..d6cb5bde 100644 --- a/app/main/model/systempodkillmodel.php +++ b/app/main/model/pathfinder/systempodkillmodel.php @@ -6,7 +6,7 @@ * Time: 21:04 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; diff --git a/app/main/model/systemshipkillmodel.php b/app/main/model/pathfinder/systemshipkillmodel.php similarity index 95% rename from app/main/model/systemshipkillmodel.php rename to app/main/model/pathfinder/systemshipkillmodel.php index 082b0e49..4727b654 100644 --- a/app/main/model/systemshipkillmodel.php +++ b/app/main/model/pathfinder/systemshipkillmodel.php @@ -6,7 +6,7 @@ * Time: 21:04 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; diff --git a/app/main/model/systemsignaturemodel.php b/app/main/model/pathfinder/systemsignaturemodel.php similarity index 95% rename from app/main/model/systemsignaturemodel.php rename to app/main/model/pathfinder/systemsignaturemodel.php index e017b226..f03fc12e 100644 --- a/app/main/model/systemsignaturemodel.php +++ b/app/main/model/pathfinder/systemsignaturemodel.php @@ -6,7 +6,7 @@ * Time: 14:34 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; use lib\logging; @@ -25,7 +25,7 @@ class SystemSignatureModel extends AbstractMapTrackingModel { 'systemId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\SystemModel', + 'belongs-to-one' => 'Model\Pathfinder\SystemModel', 'constraint' => [ [ 'table' => 'system', @@ -50,7 +50,7 @@ class SystemSignatureModel extends AbstractMapTrackingModel { 'connectionId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\ConnectionModel', + 'belongs-to-one' => 'Model\Pathfinder\ConnectionModel', 'constraint' => [ [ 'table' => 'connection', @@ -186,7 +186,7 @@ class SystemSignatureModel extends AbstractMapTrackingModel { /** * get the connection (if attached) - * @return \Model\ConnectionModel|null + * @return ConnectionModel|null */ public function getConnection(){ return $this->connectionId; @@ -252,7 +252,7 @@ class SystemSignatureModel extends AbstractMapTrackingModel { * @param $pkeys * @return bool */ - public function beforeUpdateEvent($self, $pkeys){ + public function beforeUpdateEvent($self, $pkeys) : bool { // "updated" column should always be updated if no changes made this signature // -> makes it easier to see what signatures have not been updated $this->touch('updated'); @@ -299,13 +299,10 @@ class SystemSignatureModel extends AbstractMapTrackingModel { * @return bool * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['systemId', 'typeId', 'groupId']); } - return $status; } } \ No newline at end of file diff --git a/app/main/model/systemstatusmodel.php b/app/main/model/pathfinder/systemstatusmodel.php similarity index 96% rename from app/main/model/systemstatusmodel.php rename to app/main/model/pathfinder/systemstatusmodel.php index f4c18f33..65a236b4 100644 --- a/app/main/model/systemstatusmodel.php +++ b/app/main/model/pathfinder/systemstatusmodel.php @@ -6,11 +6,11 @@ * Time: 21:53 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class SystemStatusModel extends BasicModel { +class SystemStatusModel extends AbstractPathfinderModel { protected $table = 'system_status'; diff --git a/app/main/model/systemtypemodel.php b/app/main/model/pathfinder/systemtypemodel.php similarity index 92% rename from app/main/model/systemtypemodel.php rename to app/main/model/pathfinder/systemtypemodel.php index 8afe1f5a..87e0c5c7 100644 --- a/app/main/model/systemtypemodel.php +++ b/app/main/model/pathfinder/systemtypemodel.php @@ -6,11 +6,11 @@ * Time: 21:59 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class SystemTypeModel extends BasicModel { +class SystemTypeModel extends AbstractPathfinderModel { protected $table = 'system_type'; diff --git a/app/main/model/usercharactermodel.php b/app/main/model/pathfinder/usercharactermodel.php similarity index 82% rename from app/main/model/usercharactermodel.php rename to app/main/model/pathfinder/usercharactermodel.php index c6cbf84f..e96cb7ed 100644 --- a/app/main/model/usercharactermodel.php +++ b/app/main/model/pathfinder/usercharactermodel.php @@ -6,11 +6,11 @@ * Time: 21:49 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; -class UserCharacterModel extends BasicModel { +class UserCharacterModel extends AbstractPathfinderModel { protected $table = 'user_character'; @@ -24,7 +24,7 @@ class UserCharacterModel extends BasicModel { 'userId' => [ 'type' => Schema::DT_INT, 'index' => true, - 'belongs-to-one' => 'Model\UserModel', + 'belongs-to-one' => 'Model\Pathfinder\UserModel', 'constraint' => [ [ 'table' => 'user', @@ -36,7 +36,7 @@ class UserCharacterModel extends BasicModel { 'type' => Schema::DT_INT, 'index' => true, 'unique' => true, - 'belongs-to-one' => 'Model\CharacterModel', + 'belongs-to-one' => 'Model\Pathfinder\CharacterModel', 'constraint' => [ [ 'table' => 'character', @@ -75,14 +75,12 @@ class UserCharacterModel extends BasicModel { * @param null $table * @param null $fields * @return bool + * @throws \Exception */ - public static function setup($db=null, $table=null, $fields=null){ - $status = parent::setup($db,$table,$fields); - - if($status === true){ + public static function setup($db = null, $table = null, $fields = null){ + if($status = parent::setup($db, $table, $fields)){ $status = parent::setMultiColumnIndex(['userId', 'characterId'], true); } - return $status; } diff --git a/app/main/model/usermodel.php b/app/main/model/pathfinder/usermodel.php similarity index 95% rename from app/main/model/usermodel.php rename to app/main/model/pathfinder/usermodel.php index 4438c137..e7b70664 100644 --- a/app/main/model/usermodel.php +++ b/app/main/model/pathfinder/usermodel.php @@ -6,7 +6,7 @@ * Time: 20:43 */ -namespace Model; +namespace Model\Pathfinder; use DB\SQL\Schema; use Controller; @@ -15,10 +15,16 @@ use Exception; use lib\Config; use lib\logging; -class UserModel extends BasicModel { +class UserModel extends AbstractPathfinderModel { + /** + * @var string + */ protected $table = 'user'; + /** + * @var array + */ protected $fieldConf = [ 'active' => [ 'type' => Schema::DT_BOOL, @@ -40,7 +46,7 @@ class UserModel extends BasicModel { 'validate' => true ], 'userCharacters' => [ - 'has-many' => ['Model\UserCharacterModel', 'userId'] + 'has-many' => ['Model\Pathfinder\UserCharacterModel', 'userId'] ] ]; @@ -96,7 +102,7 @@ class UserModel extends BasicModel { * @return bool * @throws Exception\RegistrationException */ - public function beforeInsertEvent($self, $pkeys){ + public function beforeInsertEvent($self, $pkeys) : bool { $registrationStatus = Controller\Controller::getRegistrationStatus(); switch($registrationStatus){ case 0: @@ -111,7 +117,7 @@ class UserModel extends BasicModel { } /** - * @param BasicModel $self + * @param self $self * @param $pkeys */ public function afterEraseEvent($self, $pkeys){ @@ -195,15 +201,6 @@ class UserModel extends BasicModel { return is_object($this->userCharacters); } - /** - * search for user by unique username - * @param $name - * @return \DB\Cortex - */ - public function getByName($name){ - return $this->getByForeignKey('name', $name, []); - } - /** * get current character data from session * -> if §characterID == 0 -> get first character data (random) @@ -237,7 +234,7 @@ class UserModel extends BasicModel { /** * @var $character CharacterModel */ - $character = BasicModel::getNew('CharacterModel'); + $character = AbstractPathfinderModel::getNew('CharacterModel'); $character->getById( (int)$data['ID']); if( diff --git a/app/main/model/universe/basicuniversemodel.php b/app/main/model/universe/abstractuniversemodel.php similarity index 79% rename from app/main/model/universe/basicuniversemodel.php rename to app/main/model/universe/abstractuniversemodel.php index 8cb82230..118b379c 100644 --- a/app/main/model/universe/basicuniversemodel.php +++ b/app/main/model/universe/abstractuniversemodel.php @@ -1,33 +1,32 @@ refresh static data after X days + * alias name for database connection */ - const CACHE_MAX_DAYS = 60; + const DB_ALIAS = 'UNIVERSE'; - const CACHE_KEY_PREFIX = 'index_universe_'; + /** + * + */ + const CACHE_KEY_PREFIX = 'index_universe_'; /** * cache key for model data -> should "never" expire * -> until manual remove and or global cache clear */ - const CACHE_INDEX_EXPIRE_KEY = 86400 * 356 * 5; - - protected $db = 'DB_UNIVERSE'; + const CACHE_INDEX_EXPIRE_KEY = 86400 * 356 * 5; /** * get model data -> should be overwritten @@ -44,7 +43,7 @@ abstract class BasicUniverseModel extends BasicModel { * @param $pkeys * @return bool */ - public function beforeUpdateEvent($self, $pkeys){ + public function beforeUpdateEvent($self, $pkeys) : bool { // if model changed, 'update' col needs to be updated as well // -> data no longer "outdated" $this->touch('updated'); @@ -113,10 +112,10 @@ abstract class BasicUniverseModel extends BasicModel { /** * add $rowKeys (hashKeys) to a search index that holds all rowKeys of a table - * @param BasicUniverseModel $model + * @param AbstractUniverseModel $model * @param array $rowKeys */ - public static function buildTableIndex(BasicUniverseModel $model, array $rowKeys = []){ + public static function buildTableIndex(AbstractUniverseModel $model, array $rowKeys = []){ $hashKeyTable = self::generateHashKeyTable($model->getTable()); if( !self::getF3()->exists($hashKeyTable, $cachedData) ){ $cachedData = []; @@ -186,25 +185,4 @@ abstract class BasicUniverseModel extends BasicModel { public static function generateHashKeyTable(string $table) : string { return self::CACHE_KEY_PREFIX . strtolower($table); } - - /** - * factory for all UniverseModels - * @param string $model - * @param int $ttl - * @return BasicModel|null - * @throws \Exception - */ - public static function getNew($model, $ttl = self::DEFAULT_TTL){ - $class = null; - - $model = '\\' . __NAMESPACE__ . '\\' . $model; - if(class_exists($model)){ - $db = Database::instance()->getDB('UNIVERSE'); - $class = new $model($db, null, null, $ttl); - }else{ - throw new \Exception(sprintf(self::ERROR_INVALID_MODEL_CLASS, $model)); - } - - return $class; - } } \ No newline at end of file diff --git a/app/main/model/universe/categorymodel.php b/app/main/model/universe/categorymodel.php index 0cf4ca56..f8ba5052 100644 --- a/app/main/model/universe/categorymodel.php +++ b/app/main/model/universe/categorymodel.php @@ -1,7 +1,7 @@ [ 'type' => Schema::DT_VARCHAR128, diff --git a/app/main/model/universe/factionmodel.php b/app/main/model/universe/factionmodel.php new file mode 100644 index 00000000..11764aab --- /dev/null +++ b/app/main/model/universe/factionmodel.php @@ -0,0 +1,78 @@ + [ + 'type' => Schema::DT_VARCHAR128, + 'nullable' => false, + 'default' => '' + ], + 'description' => [ + 'type' => Schema::DT_TEXT + ], + 'sizeFactor' => [ + 'type' => Schema::DT_INT, + 'nullable' => false, + 'default' => 0 + ], + 'stationCount' => [ + 'type' => Schema::DT_INT, + 'nullable' => false, + 'default' => 0 + ], + 'stationSystemCount' => [ + 'type' => Schema::DT_INT, + 'nullable' => false, + 'default' => 0 + ], + 'systems' => [ + 'has-many' => ['Model\Universe\SystemModel', 'factionId'] + ] + ]; + + /** + * get data + * @return \stdClass + */ + public function getData(){ + $factionData = (object) []; + $factionData->id = $this->_id; + $factionData->name = $this->name; + + return $factionData; + } + + /** + * @param int $id + * @param string $accessToken + * @param array $additionalOptions + */ + protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){ + $data = self::getF3()->ccpClient()->getUniverseFactionData($id); + if(!empty($data)){ + $this->copyfrom($data, ['id', 'name', 'description', 'sizeFactor', 'stationCount', 'stationSystemCount']); + $this->save(); + } + } +} \ No newline at end of file diff --git a/app/main/model/universe/groupmodel.php b/app/main/model/universe/groupmodel.php index f0f97fc4..ec712ab9 100644 --- a/app/main/model/universe/groupmodel.php +++ b/app/main/model/universe/groupmodel.php @@ -1,7 +1,7 @@ [ 'type' => Schema::DT_VARCHAR128, @@ -25,7 +32,7 @@ class RegionModel extends BasicUniverseModel { ], 'constellations' => [ 'has-many' => ['Model\Universe\ConstellationModel', 'regionId'] - ], + ] ]; /** diff --git a/app/main/model/universe/stargatemodel.php b/app/main/model/universe/stargatemodel.php index c30baf8b..d50e5eb6 100644 --- a/app/main/model/universe/stargatemodel.php +++ b/app/main/model/universe/stargatemodel.php @@ -1,7 +1,7 @@ findQuery($schema->dataTypes[Schema::DT_BIGINT]); $db->exec("ALTER TABLE " . $db->quotekey('structure') . " MODIFY COLUMN " . $db->quotekey('id') . " " . $typeQuery . " NOT NULL"); } - return $status; } diff --git a/app/main/model/universe/systemmodel.php b/app/main/model/universe/systemmodel.php index 802a9616..b56152d6 100644 --- a/app/main/model/universe/systemmodel.php +++ b/app/main/model/universe/systemmodel.php @@ -1,7 +1,7 @@ [ 'type' => Schema::DT_VARCHAR128, @@ -46,6 +55,18 @@ class SystemModel extends BasicUniverseModel { ], 'validate' => 'notDry' ], + 'factionId' => [ + 'type' => Schema::DT_INT, + 'index' => true, + 'belongs-to-one' => 'Model\Universe\FactionModel', + 'constraint' => [ + [ + 'table' => 'faction', + 'on-delete' => 'CASCADE' + ] + ], + 'validate' => 'notDry' + ], 'security' => [ 'type' => Schema::DT_VARCHAR128 ], @@ -116,6 +137,10 @@ class SystemModel extends BasicUniverseModel { $systemData->star = $this->starId->getData(); } + if($this->factionId){ + $systemData->faction = $this->factionId->getData(); + } + if( !empty($planetsData = $this->getPlanetsData()) ){ $systemData->planets = $planetsData; } diff --git a/app/main/model/universe/systemstaticmodel.php b/app/main/model/universe/systemstaticmodel.php index 8664ef73..f736b781 100644 --- a/app/main/model/universe/systemstaticmodel.php +++ b/app/main/model/universe/systemstaticmodel.php @@ -1,7 +1,7 @@ ccpClient()->getUniverseTypesData($id); if(!empty($data)){ + /** + * @var $group GroupModel + */ $group = $this->rel('groupId'); $group->loadById($data['groupId'], $accessToken, $additionalOptions); $data['groupId'] = $group; diff --git a/app/main/model/universe/wormholemodel.php b/app/main/model/universe/wormholemodel.php index 725e5df3..93d257a0 100644 --- a/app/main/model/universe/wormholemodel.php +++ b/app/main/model/universe/wormholemodel.php @@ -1,7 +1,7 @@ { if(payload.data){ - Util.showNotify({title: 'Copied to clipbaord', text: mapUrl, type: 'success'}); + Util.showNotify({title: 'Copied to clipboard', text: mapUrl, type: 'success'}); } }); }); diff --git a/js/app/util.js b/js/app/util.js index dc181d4b..d0a56a83 100644 --- a/js/app/util.js +++ b/js/app/util.js @@ -2034,6 +2034,38 @@ define([ return table; }; + /** + * get a HTML table with universe region information + * e.g. for popover + * @param regionName + * @param faction + * @returns {string} + */ + let getSystemRegionTable = (regionName, faction) => { + let table = ''; + table += ''; + table += ''; + table += ''; + table += ''; + table += ''; + if(faction){ + table += ''; + table += ''; + table += ''; + } + table += '
'; + table += 'Region'; + table += ''; + table += regionName; + table += '
'; + table += 'Faction'; + table += ''; + table += faction.name; + table += '
'; + + return table; + }; + /** * get a HTML table with pilots/ship names * @param users @@ -3197,6 +3229,7 @@ define([ getSystemEffectData: getSystemEffectData, getSystemEffectTable: getSystemEffectTable, getSystemPlanetsTable: getSystemPlanetsTable, + getSystemRegionTable: getSystemRegionTable, getSystemPilotsTable: getSystemPilotsTable, getSystemsInfoTable: getSystemsInfoTable, getStatusInfoForCharacter: getStatusInfoForCharacter, diff --git a/public/js/v1.5.1/app/map/map.js b/public/js/v1.5.1/app/map/map.js index 237fccb1..ff6ca8d3 100644 --- a/public/js/v1.5.1/app/map/map.js +++ b/public/js/v1.5.1/app/map/map.js @@ -489,6 +489,7 @@ define([ system.data('region', data.region.name); system.data('constellationId', parseInt(data.constellation.id)); system.data('constellation', data.constellation.name); + system.data('faction', data.faction); system.data('planets', data.planets); system.data('shattered', data.shattered); system.data('statics', data.statics); @@ -2912,6 +2913,7 @@ define([ systemData.rallyUpdated = system.data('rallyUpdated') || 0; systemData.rallyPoke = system.data('rallyPoke') ? 1 : 0; systemData.currentUser = system.data('currentUser'); // if user is currently in this system + systemData.faction = system.data('faction'); systemData.planets = system.data('planets'); systemData.shattered = system.data('shattered') ? 1 : 0; systemData.statics = system.data('statics'); diff --git a/public/js/v1.5.1/app/map/overlay.js b/public/js/v1.5.1/app/map/overlay.js index 29e4ba89..331be0f4 100644 --- a/public/js/v1.5.1/app/map/overlay.js +++ b/public/js/v1.5.1/app/map/overlay.js @@ -324,24 +324,29 @@ define([ over: function(e){ let mapElement = Util.getMapElementFromOverlay(this); mapElement.find('.' + config.systemHeadClass).each(function(){ - let system = $(this); - // init tooltip if not already exists - if( !system.data('bs.tooltip') ){ - system.tooltip({ - container: mapElement, + let systemHead = $(this); + // init popover if not already exists + if(!systemHead.data('bs.popover')){ + let system = systemHead.parent(); + systemHead.popover({ placement: 'right', - title: function(){ - return $(this).parent().data('region'); - }, - trigger: 'manual' + html: true, + trigger: 'manual', + container: mapElement, + title: false, + content: Util.getSystemRegionTable( + system.data('region'), + system.data('faction') || null + ) }); } - system.tooltip('show'); + systemHead.setPopoverSmall(); + systemHead.popover('show'); }); }, out: function(e){ let mapElement = Util.getMapElementFromOverlay(this); - mapElement.find('.' + config.systemHeadClass).tooltip('hide'); + mapElement.find('.' + config.systemHeadClass).popover('hide'); } } }, diff --git a/public/js/v1.5.1/app/ui/module/system_info.js b/public/js/v1.5.1/app/ui/module/system_info.js index c3fe5bed..a59899de 100644 --- a/public/js/v1.5.1/app/ui/module/system_info.js +++ b/public/js/v1.5.1/app/ui/module/system_info.js @@ -343,7 +343,7 @@ define([ let mapUrl = $(this).attr('data-url'); Util.copyToClipboard(mapUrl).then(payload => { if(payload.data){ - Util.showNotify({title: 'Copied to clipbaord', text: mapUrl, type: 'success'}); + Util.showNotify({title: 'Copied to clipboard', text: mapUrl, type: 'success'}); } }); }); diff --git a/public/js/v1.5.1/app/util.js b/public/js/v1.5.1/app/util.js index dc181d4b..d0a56a83 100644 --- a/public/js/v1.5.1/app/util.js +++ b/public/js/v1.5.1/app/util.js @@ -2034,6 +2034,38 @@ define([ return table; }; + /** + * get a HTML table with universe region information + * e.g. for popover + * @param regionName + * @param faction + * @returns {string} + */ + let getSystemRegionTable = (regionName, faction) => { + let table = ''; + table += ''; + table += ''; + table += ''; + table += ''; + table += ''; + if(faction){ + table += ''; + table += ''; + table += ''; + } + table += '
'; + table += 'Region'; + table += ''; + table += regionName; + table += '
'; + table += 'Faction'; + table += ''; + table += faction.name; + table += '
'; + + return table; + }; + /** * get a HTML table with pilots/ship names * @param users @@ -3197,6 +3229,7 @@ define([ getSystemEffectData: getSystemEffectData, getSystemEffectTable: getSystemEffectTable, getSystemPlanetsTable: getSystemPlanetsTable, + getSystemRegionTable: getSystemRegionTable, getSystemPilotsTable: getSystemPilotsTable, getSystemsInfoTable: getSystemsInfoTable, getStatusInfoForCharacter: getStatusInfoForCharacter, diff --git a/public/templates/modules/system_info.html b/public/templates/modules/system_info.html index 896b3e2a..3d101542 100644 --- a/public/templates/modules/system_info.html +++ b/public/templates/modules/system_info.html @@ -52,7 +52,7 @@
- +
@@ -78,6 +78,12 @@ {{/effectName}} + {{#system.faction}} + + + + + {{/system.faction}} {{#planetCount}}
Name
Faction{{system.faction.name}}
Planets