From 58b4b1b0c03008f23f40dea1e9131c8a796bc939 Mon Sep 17 00:00:00 2001 From: exodus4d Date: Tue, 11 Aug 2015 19:06:53 +0200 Subject: [PATCH] Bigfixes --- app/config.ini | 26 ++- app/main/controller/AccessController.php | 7 +- app/main/controller/CcpApiController.php | 216 ++++++++++++++--------- app/main/controller/Controller.php | 26 +-- app/main/controller/MapController.php | 3 - app/main/controller/api/Access.php | 5 +- app/main/controller/api/Connection.php | 23 ++- app/main/controller/api/Map.php | 115 ++++++------ app/main/controller/api/Route.php | 79 +++++---- app/main/controller/api/Signature.php | 5 +- app/main/controller/api/System.php | 76 ++++++-- app/main/controller/api/User.php | 125 ++++++------- app/main/model/AllianceModel.php | 28 ++- app/main/model/BasicModel.php | 12 +- app/main/model/CharacterModel.php | 43 +++-- app/main/model/CorporationModel.php | 28 ++- app/main/model/MapModel.php | 65 ++++--- app/main/model/SystemModel.php | 117 ++++++++---- app/main/model/UserApiModel.php | 11 +- app/main/model/UserCharacterModel.php | 2 - app/main/model/UserModel.php | 169 ++++++++++++++---- 21 files changed, 736 insertions(+), 445 deletions(-) diff --git a/app/config.ini b/app/config.ini index 6b193ff9..9ef8f337 100644 --- a/app/config.ini +++ b/app/config.ini @@ -14,9 +14,6 @@ TZ = "UTC" ; Cache backend. Can handle Memcache module, APC, WinCache, XCache and a filesystem-based cache. CACHE = TRUE -; Cache timer in seconds -CACHE_DB_CCP = 30 - ; Path configurations ===================================================================================== ; Path to the index.php main/front controller. BASE = /exodus4d/pathfinder @@ -77,12 +74,20 @@ LIFETIME = 2 LIFETIME = 99999 [PATHFINDER.MAP.ALLIANCE] -ALLIANCE = 99999 +LIFETIME = 99999 +; ====================================================================================================== +[PATHFINDER.CACHE] + +; cache character log informations in seconds. This is ignored if ship/system switch was detected +CHARACTER_LOG = 600 + +; cache time for all system data within a constellation (this will never change) 30d +CONSTELLATION_SYSTEMS = 2592000 ; ====================================================================================================== [PATHFINDER.TIMER] -; Login time (minutes) +; login time (minutes) LOGGED = 120 ; double click timer (ms) @@ -106,13 +111,22 @@ EXECUTION_LIMIT = 50 ; map user update ping (ajax) (ms) [PATHFINDER.TIMER.UPDATE_SERVER_USER_DATA] -DELAY = 3000 +DELAY = 5000 EXECUTION_LIMIT = 200 ; update client user data (ms) [PATHFINDER.TIMER.UPDATE_CLIENT_USER_DATA] EXECUTION_LIMIT = 50 +; ====================================================================================================== +[PATHFINDER.LOGFILES] + +; just for manuel debug during development +DEBUG = "debug" + +; user login information +LOGIN = "login" + ; ====================================================================================================== [api_path] diff --git a/app/main/controller/AccessController.php b/app/main/controller/AccessController.php index 437e9736..50c1cc28 100644 --- a/app/main/controller/AccessController.php +++ b/app/main/controller/AccessController.php @@ -17,17 +17,18 @@ class AccessController extends Controller { /** * event handler + * @param $f3 */ - function beforeroute() { + function beforeroute($f3) { $loginCheck = $this->_checkLogIn(); if( !$loginCheck ){ // no user found or LogIn timer expired - $this->logOut(); + $this->logOut($f3); } - parent::beforeroute(); + parent::beforeroute($f3); } /** diff --git a/app/main/controller/CcpApiController.php b/app/main/controller/CcpApiController.php index f8fd29c2..c9972a56 100644 --- a/app/main/controller/CcpApiController.php +++ b/app/main/controller/CcpApiController.php @@ -47,98 +47,148 @@ class CcpApiController extends Controller{ } /** - * request Character data for given api models - * @param $apiModels - * @return array + * request character information from CCP API + * @param $keyID + * @param $vCode + * @return bool|\SimpleXMLElement */ - public function getCharacters($apiModels){ - + public function requestCharacters($keyID, $vCode){ $apiPath = $this->f3->get('api_path.CCP_XML') . '/account/APIKeyInfo.xml.aspx'; - $characters = []; - foreach($apiModels as $apiModel){ - // build request URL - $options = $this->getRequestOptions(); - $options['content'] = http_build_query( [ - 'keyID' => $apiModel->keyId, - 'vCode' => $apiModel->vCode - ]); + $xml = false; - $apiResponse = \Web::instance()->request($apiPath, $options ); + // build request URL + $options = $this->getRequestOptions(); + $options['content'] = http_build_query( [ + 'keyID' => $keyID, + 'vCode' => $vCode + ]); - if($apiResponse['body']){ - $xml = simplexml_load_string($apiResponse['body']); - $rowApiData = $xml->result->key->rowset; - // request successful -------------------------------------------- + $apiResponse = \Web::instance()->request($apiPath, $options ); - if($rowApiData->children()){ - $characterModel = Model\BasicModel::getNew('CharacterModel'); - $corporationModel = Model\BasicModel::getNew('CorporationModel'); - $allianceModel = Model\BasicModel::getNew('AllianceModel'); - - foreach($rowApiData->children() as $characterApiData){ - - // map attributes to array - $attributeData = current( $characterApiData->attributes() ); - - $corporationModelTemp = null; - $allianceModelTemp = null; - - // check if corporation already exists - if($attributeData['corporationID'] > 0){ - $corporationModel->getById($attributeData['corporationID']); - if( $corporationModel->dry() ){ - $corporationModel->id = $attributeData['corporationID']; - $corporationModel->name = $attributeData['corporationName']; - $corporationModel->save(); - } - $corporationModelTemp = $corporationModel; - } - - // check if alliance already exists - if($attributeData['allianceID'] > 0){ - $allianceModel->getById($attributeData['allianceID']); - if( $allianceModel->dry() ){ - $allianceModel->id = $attributeData['allianceID']; - $allianceModel->name = $attributeData['allianceName']; - $allianceModel->save(); - } - $allianceModelTemp = $allianceModel; - } - - // search for existing user character model - $userCharacterModel = $apiModel->getUserCharacterById($attributeData['characterID']); - if(is_null($userCharacterModel)){ - $userCharacterModel = Model\BasicModel::getNew('UserCharacterModel'); - } - - $characterModel->getById($attributeData['characterID']); - - $characterModel->id = $attributeData['characterID']; - $characterModel->name = $attributeData['characterName']; - $characterModel->corporationId = $corporationModelTemp; - $characterModel->allianceId = $allianceModelTemp; - $characterModel->factionId = $attributeData['factionID']; - $characterModel->factionName = $attributeData['factionName']; - - // save/update character - $characterModel->save(); - - // store "temp" character obj until obj is saved for the first time - $userCharacterModel->characterId = $characterModel; - - $characters[] = $userCharacterModel; - - $corporationModel->reset(); - $allianceModel->reset(); - $characterModel->reset(); - } - } - } + if($apiResponse['body']){ + $xml = simplexml_load_string($apiResponse['body']); } - return $characters; + return $xml; } + /** + * update all character information for a given apiModel + * @param $userApiModel + * @return int + * @throws \Exception + */ + public function updateCharacters($userApiModel){ + + $xml = $this->requestCharacters($userApiModel->keyId, $userApiModel->vCode); + + $characterCount = 0; + + // important -> user API model must be up2date + // if not -> matched userCharacter cant be found + $userApiModel->getById($userApiModel->id, 0); + + if($xml){ + // request successful + $rowApiData = $xml->result->key->rowset; + + if($rowApiData->children()){ + $characterModel = Model\BasicModel::getNew('CharacterModel'); + $corporationModel = Model\BasicModel::getNew('CorporationModel'); + $allianceModel = Model\BasicModel::getNew('AllianceModel'); + + foreach($rowApiData->children() as $characterApiData){ + // map attributes to array + $attributeData = current( $characterApiData->attributes() ); + + $newCharacter = true; + + $characterId = (int)$attributeData['characterID']; + $characterModel->getById($characterId); + + // check if corporation already exists + if($attributeData['corporationID'] > 0){ + $corporationModel->getById($attributeData['corporationID']); + if( $corporationModel->dry() ){ + $corporationModel->id = $attributeData['corporationID']; + $corporationModel->name = $attributeData['corporationName']; + $corporationModel->save(); + } + $corporationModelTemp = $corporationModel; + } + + // check if alliance already exists + if($attributeData['allianceID'] > 0){ + $allianceModel->getById($attributeData['allianceID']); + if( $allianceModel->dry() ){ + $allianceModel->id = $attributeData['allianceID']; + $allianceModel->name = $attributeData['allianceName']; + $allianceModel->save(); + } + $allianceModelTemp = $allianceModel; + } + + if($userApiModel->userCharacters){ + $userApiModel->userCharacters->rewind(); + while($userApiModel->userCharacters->valid()){ + $tempCharacterModel = $userApiModel->userCharacters->current()->getCharacter(); + + // character already exists -> update + if($tempCharacterModel->id == $characterId){ + $characterModel = $tempCharacterModel; + + // unset userCharacter -> all leftover models are no longer part of this API + // --> delete leftover models at the end + $userApiModel->userCharacters->offsetUnset($userApiModel->userCharacters->key()); + + $newCharacter = false; + break; + }else{ + $userApiModel->userCharacters->next(); + } + } + + $userApiModel->userCharacters->rewind(); + + } + + $characterModel->id = $characterId; + $characterModel->name = $attributeData['characterName']; + $characterModel->corporationId = $corporationModelTemp; + $characterModel->allianceId = $allianceModelTemp; + $characterModel->factionId = $attributeData['factionID']; + $characterModel->factionName = $attributeData['factionName']; + $characterModel->save(); + + if($newCharacter){ + // new character for this API + $userCharactersModel = Model\BasicModel::getNew('UserCharacterModel', 0); + $userCharactersModel->userId = $userApiModel->userId; + $userCharactersModel->apiId = $userApiModel; + $userCharactersModel->characterId = $characterModel; + $userCharactersModel->save(); + } + + $corporationModel->reset(); + $allianceModel->reset(); + $characterModel->reset(); + + $characterCount++; + } + } + + // delete leftover userCharacters from this API + if(count($userApiModel->userCharacters) > 0){ + while($userApiModel->userCharacters->valid()){ + $userApiModel->userCharacters->current()->erase(); + $userApiModel->userCharacters->next(); + } + } + + } + + return $characterCount; + } } \ No newline at end of file diff --git a/app/main/controller/Controller.php b/app/main/controller/Controller.php index 2e1ae3b8..f5eed12d 100644 --- a/app/main/controller/Controller.php +++ b/app/main/controller/Controller.php @@ -39,8 +39,9 @@ class Controller { /** * event handler + * @param $f3 */ - function beforeroute() { + function beforeroute($f3) { } @@ -64,18 +65,18 @@ class Controller { /** * get current user model + * @param int $ttl * @return bool|null * @throws \Exception */ - protected function _getUser(){ + protected function _getUser($ttl = 5){ $user = false; $userId = $this->f3->get('SESSION.user.id'); if($userId > 0){ $userModel = Model\BasicModel::getNew('UserModel'); - // get a fresh (not cached) user object - $userModel->getById($userId, 0); + $userModel->getById($userId, $ttl); if( !$userModel->dry() ){ $user = $userModel; @@ -145,13 +146,13 @@ class Controller { * verifies weather a given username and password is valid * @param $userName * @param $password - * @return bool user object if valid + * @return Model\UserModel|null */ protected function _verifyUser($userName, $password) { - $validUser = false; + $validUser = null; - $user = Model\BasicModel::getNew('UserModel'); + $user = Model\BasicModel::getNew('UserModel', 0); $user->getByName($userName); @@ -171,18 +172,19 @@ class Controller { /** * log the current user out + * @param $f3 */ - public function logOut(){ + public function logOut($f3){ // destroy session - $this->f3->clear('SESSION'); + $f3->clear('SESSION'); - if( !$this->f3->get('AJAX') ){ + if( !$f3->get('AJAX') ){ // redirect to landing page - $this->f3->reroute('@landing'); + $f3->reroute('@landing'); }else{ $return = (object) []; - $return->reroute = $this->f3->get('BASE') . $this->f3->alias('landing'); + $return->reroute = $f3->get('BASE') . $f3->alias('landing'); $return->error[] = $this->getUserLoggedOffError(); echo json_encode($return); diff --git a/app/main/controller/MapController.php b/app/main/controller/MapController.php index 01da30da..c3e9cfd7 100644 --- a/app/main/controller/MapController.php +++ b/app/main/controller/MapController.php @@ -28,9 +28,6 @@ class MapController extends \Controller\AccessController { // JS main file $this->f3->set('jsView', 'main'); - //$logger = self::getLogger('debug'); - //$logger->write( print_r(apache_request_headers(), true) ); - $this->setTemplate('templates/view/index.html'); } diff --git a/app/main/controller/api/Access.php b/app/main/controller/api/Access.php index 2af7f3d6..6db026aa 100644 --- a/app/main/controller/api/Access.php +++ b/app/main/controller/api/Access.php @@ -13,10 +13,11 @@ class Access extends \Controller\AccessController { /** * event handler + * @param $f3 */ - function beforeroute() { + function beforeroute($f3) { - parent::beforeroute(); + parent::beforeroute($f3); // set header for all routes header('Content-type: application/json'); diff --git a/app/main/controller/api/Connection.php b/app/main/controller/api/Connection.php index 2023b9e6..aefbca82 100644 --- a/app/main/controller/api/Connection.php +++ b/app/main/controller/api/Connection.php @@ -12,11 +12,11 @@ use Model; class Connection extends \Controller\AccessController{ /** - * event handler + * @param $f3 */ - function beforeroute() { + function beforeroute($f3) { - parent::beforeroute(); + parent::beforeroute($f3); // set header for all routes header('Content-type: application/json'); @@ -56,8 +56,25 @@ class Connection extends \Controller\AccessController{ $connection = Model\BasicModel::getNew('ConnectionModel'); $connection->getById( (int)$connectionData['id'] ); + // search if systems are neighbors + $routeController = new Route(); + $route = $routeController->findRoute($connectionData['sourceName'], $connectionData['targetName'], 1); + + if($route['routePossible'] == true){ + // systems are next to each other + $connectionData['scope'] = 'stargate'; + $connectionData['type'] = ['stargate']; + }elseif($connectionData['scope'] == 'stargate'){ + // connection scope changed -> this can not be a stargate + $connectionData['scope'] = 'wh'; + $connectionData['type'] = ['wh_fresh']; + } + $connectionData['mapId'] = $map; + // "updated" should not be set by client e.g. after manual drag&drop + unset($connectionData['updated']); + $connection->setData($connectionData); if( $connection->isValid() ){ diff --git a/app/main/controller/api/Map.php b/app/main/controller/api/Map.php index 3e349c0a..dccda3f5 100644 --- a/app/main/controller/api/Map.php +++ b/app/main/controller/api/Map.php @@ -18,13 +18,14 @@ class Map extends \Controller\AccessController { /** * event handler + * @param $f3 */ - function beforeroute() { + function beforeroute($f3) { // set header for all routes header('Content-type: application/json'); - parent::beforeroute(); + parent::beforeroute($f3); } /** @@ -152,7 +153,7 @@ class Map extends \Controller\AccessController { if( isset($formData['id']) ){ - $user = $this->_getUser(); + $user = $this->_getUser(0); if($user){ $map = Model\BasicModel::getNew('MapModel'); @@ -171,12 +172,15 @@ class Map extends \Controller\AccessController { // share map between users -> set access if(isset($formData['mapUsers'])){ + // avoid abuse -> respect share limits + $accessUsers = array_slice( $formData['mapUsers'], 0, $f3->get('PATHFINDER.MAX_SHARED_USER') ); + // clear map access. In case something has removed from access list $map->clearAccess(); $tempUser = Model\BasicModel::getNew('UserModel'); - foreach((array)$formData['mapUsers'] as $userId){ + foreach($accessUsers as $userId){ $tempUser->getById( (int)$userId ); if( @@ -205,12 +209,15 @@ class Map extends \Controller\AccessController { // share map between corporations -> set access if(isset($formData['mapCorporations'])){ + // avoid abuse -> respect share limits + $accessCorporations = array_slice( $formData['mapCorporations'], 0, $f3->get('PATHFINDER.MAX_SHARED_CORPORATION') ); + // clear map access. In case something has removed from access list $map->clearAccess(); $tempCorporation = Model\BasicModel::getNew('CorporationModel'); - foreach((array)$formData['mapCorporations'] as $corporationId){ + foreach($accessCorporations as $corporationId){ $tempCorporation->getById( (int)$corporationId ); if( @@ -240,12 +247,15 @@ class Map extends \Controller\AccessController { // share map between alliances -> set access if(isset($formData['mapAlliances'])){ + // avoid abuse -> respect share limits + $accessAlliances = array_slice( $formData['mapAlliances'], 0, $f3->get('PATHFINDER.MAX_SHARED_ALLIANCE') ); + // clear map access. In case something has removed from access list $map->clearAccess(); $tempAlliance = Model\BasicModel::getNew('AllianceModel'); - foreach((array)$formData['mapAlliances'] as $allianceId){ + foreach($accessAlliances as $allianceId){ $tempAlliance->getById( (int)$allianceId ); if( @@ -265,10 +275,10 @@ class Map extends \Controller\AccessController { } } } - // reload the same map model (refresh) // this makes sure all data is up2date - $map->getById( $map->id ); + $map->getById( $map->id, 0 ); + $return->mapData = $map->getData(); @@ -323,7 +333,6 @@ class Map extends \Controller\AccessController { $mapData = (array)$f3->get('POST.mapData'); $user = $this->_getUser(); - $return = (object) []; $return->error = []; @@ -487,71 +496,71 @@ class Map extends \Controller\AccessController { $cacheKey = null; $return = (object) []; - - $user = $this->_getUser(); - $return->error = []; - if($user){ - - // update current location (IGB data) - $user->updateCharacterLog(); - + if( !empty($f3->get('POST.mapIds')) ){ + $mapIds = (array)$f3->get('POST.mapIds'); // check if data for specific system is requested $systemData = (array)$f3->get('POST.systemData'); - // if data is requested extend the cache key in order to get new data - $requestSystemData = (object) []; - $requestSystemData->mapId = isset($systemData['mapId']) ? (int) $systemData['mapId'] : 0; - $requestSystemData->systemId = isset($systemData['systemData']['id']) ? (int) $systemData['systemData']['id'] : 0; + $user = $this->_getUser(); - // the maps are cached per user - $cacheKey = 'user_data_' . $user->id . '_' . $requestSystemData->systemId; + if($user){ + // update current location (IGB data) + $user->updateCharacterLog(60 * 5); - if( $f3->exists($cacheKey) === false ){ + // if data is requested extend the cache key in order to get new data + $requestSystemData = (object) []; + $requestSystemData->mapId = isset($systemData['mapId']) ? (int) $systemData['mapId'] : 0; + $requestSystemData->systemId = isset($systemData['systemData']['id']) ? (int) $systemData['systemData']['id'] : 0; - // get user Data for each map - $activeMaps = $user->getMaps(5); + // IMPORTANT for now -> just update a single map (save performance) + $mapIds = array_slice($mapIds, 0, 1); - foreach($activeMaps as $mapModel){ - $return->mapUserData[] = $mapModel->getUserData(); + // the maps are cached per map (this must be changed if multiple maps + // will be allowed in future... + $tempId = $mapIds[0]; + $cacheKey = 'user_data_' . $tempId . '_' . $requestSystemData->systemId; - // request signature data for a system if user has map access! - if( $mapModel->id === $requestSystemData->mapId ){ - $system = $mapModel->getSystem( $requestSystemData->systemId ); + if( $f3->exists($cacheKey) === false ){ + foreach($mapIds as $mapId){ + $map = $user->getMap($mapId); - if( !is_null($system) ){ - // data for the current selected system - $return->system = $system->getData(); - $return->system->signatures = $system->getSignaturesData(); + if( !is_null($map) ){ + $return->mapUserData[] = $map->getUserData(); + + + // request signature data for a system if user has map access! + if( $map->id === $requestSystemData->mapId ){ + $system = $map->getSystem( $requestSystemData->systemId ); + + if( !is_null($system) ){ + // data for the current selected system + $return->system = $system->getData(); + $return->system->signatures = $system->getSignaturesData(); + } + } } } - } - // cache response - if( !is_null($cacheKey) ){ + // cache response $f3->set($cacheKey, $return, $responseTTL); + }else{ + // get from cache + // this should happen if a user has multiple program instances running + // with the same main char + $return = $f3->get($cacheKey); } + // get current user data -> this should not be cached because each user has different personal data + // even if they have multiple characters using the same map! + $return->userData = $user->getData(); }else{ - // get from cache - // this should happen if a user has multiple program instances running - // with the same main char - $return = $f3->get($cacheKey); + // user logged of + $return->error[] = $this->getUserLoggedOffError(); } - - // add data that is not cacheable ----------------------------------------- - - // get current user data -> this should not be cached because each user has different personal data - // even if they have multiple characters using the same map! - $return->userData = $user->getData(); - - }else{ - // user logged of - $return->error[] = $this->getUserLoggedOffError(); } - echo json_encode( $return ); } diff --git a/app/main/controller/api/Route.php b/app/main/controller/api/Route.php index 9ef26d7a..9ade172c 100644 --- a/app/main/controller/api/Route.php +++ b/app/main/controller/api/Route.php @@ -17,12 +17,6 @@ use Model; */ class Route extends \Controller\AccessController { - /** - * search depth for recursive route search (5000 would be best but slow) - * -> in reality there are no routes > 100 jumps between systems - */ - const ROUTE_SEARCH_DEPTH = 5000; - /** * cache time for static jump data * @var int @@ -277,11 +271,14 @@ class Route extends \Controller\AccessController { /** * find a route between two systems (system names) + * $searchDepth for recursive route search (5000 would be best but slow) + * -> in reality there are no routes > 100 jumps between systems * @param $systemFrom * @param $systemTo + * @param int $searchDepth * @return array */ - private function findRoute($systemFrom, $systemTo){ + public function findRoute($systemFrom, $systemTo, $searchDepth = 5000){ $routeData = [ 'routePossible' => false, @@ -299,27 +296,14 @@ class Route extends \Controller\AccessController { // jump counter $jumpNum = 0; - // check if the system we are looking for is a direct neighbour - foreach( $this->jumpArray[$from] as $n ) { + if( isset($this->jumpArray[$from]) ){ - if ($n == $to) { - $jumpNum = 2; - $jumpNode = [ - 'system' => $n, - 'security' => $this->getSystemInfoBySystemId($this->idArray[$n], 'trueSec') - ]; + // check if the system we are looking for is a direct neighbour + foreach( $this->jumpArray[$from] as $n ) { - $routeData['route'][] = $jumpNode; - break; - } - } - - // system is not a direct neighbour -> search recursive its neighbours - if ($jumpNum == 0) { - foreach( $this->graph_find_path( $this->jumpArray, $from, $to, self::ROUTE_SEARCH_DEPTH ) as $n ) { - - if ($jumpNum > 0) { + if ($n == $to) { + $jumpNum = 2; $jumpNode = [ 'system' => $n, @@ -327,25 +311,42 @@ class Route extends \Controller\AccessController { ]; $routeData['route'][] = $jumpNode; + break; } - $jumpNum++; } - } - if ($jumpNum > 0) { - // route found - $routeData['routePossible'] = true; + // system is not a direct neighbour -> search recursive its neighbours + if ($jumpNum == 0) { + foreach( $this->graph_find_path( $this->jumpArray, $from, $to, $searchDepth ) as $n ) { - $jumpNode = [ - 'system' => $from, - 'security' => $this->getSystemInfoBySystemId($this->idArray[$from], 'trueSec') - ]; + if ($jumpNum > 0) { - // insert "from" system on top - array_unshift($routeData['route'], $jumpNode); - } else { - // route not found - $routeData['routePossible'] = true; + $jumpNode = [ + 'system' => $n, + 'security' => $this->getSystemInfoBySystemId($this->idArray[$n], 'trueSec') + ]; + + $routeData['route'][] = $jumpNode; + } + $jumpNum++; + } + } + + if ($jumpNum > 0) { + // route found + $routeData['routePossible'] = true; + + $jumpNode = [ + 'system' => $from, + 'security' => $this->getSystemInfoBySystemId($this->idArray[$from], 'trueSec') + ]; + + // insert "from" system on top + array_unshift($routeData['route'], $jumpNode); + } else { + // route not found + $routeData['routePossible'] = false; + } } // route jumps diff --git a/app/main/controller/api/Signature.php b/app/main/controller/api/Signature.php index dd697c8e..c69ef1b8 100644 --- a/app/main/controller/api/Signature.php +++ b/app/main/controller/api/Signature.php @@ -14,10 +14,11 @@ class Signature extends \Controller\AccessController{ /** * event handler + * @param $f3 */ - function beforeroute() { + function beforeroute($f3) { - parent::beforeroute(); + parent::beforeroute($f3); // set header for all routes header('Content-type: application/json'); diff --git a/app/main/controller/api/System.php b/app/main/controller/api/System.php index 941b575c..d04033b3 100644 --- a/app/main/controller/api/System.php +++ b/app/main/controller/api/System.php @@ -63,11 +63,11 @@ class System extends \Controller\AccessController { private $limitQuery = ""; /** - * event handler + * @param $f3 */ - function beforeroute() { + function beforeroute($f3) { - parent::beforeroute(); + parent::beforeroute($f3); // set header for all routes header('Content-type: application/json'); @@ -88,38 +88,42 @@ class System extends \Controller\AccessController { return $query; } - /** * get static system Data from CCPs Static DB export - * @param $systemId + * search column for IDs can be (solarSystemID, regionID, constellationID) + * @param array $columnIDs * @return null + * @throws \Exception */ - protected function _getSystemModelById($systemId){ + protected function _getSystemModelByIds($columnIDs = [], $column = 'solarSystemID'){ + + $systemModels = []; // switch DB $this->setDB('CCP'); - $this->whereQuery = "WHERE - map_sys.solarSystemID = " . (int)$systemId . ""; - - $this->limitQuery = "Limit 1"; + map_sys." . $column . " IN (" . implode(',', $columnIDs) . ")"; $query = $this->_getQuery(); - $rows = $this->f3->get('DB')->exec($query, null, 30); + $rows = $this->f3->get('DB')->exec($query, null, 60 * 60 * 24); // format result $mapper = new Mapper\CcpSystemsMapper($rows); - $ccpData = $mapper->getData(); + $ccpSystemsData = $mapper->getData(); // switch DB $this->setDB('PF'); - $system = Model\BasicModel::getNew('SystemModel'); - $system->setData(reset($ccpData)); - return $system; + foreach($ccpSystemsData as $ccpSystemData){ + $system = Model\BasicModel::getNew('SystemModel'); + $system->setData($ccpSystemData); + $systemModels[] = $system; + } + + return $systemModels; } /** @@ -222,7 +226,7 @@ class System extends \Controller\AccessController { $systemData['mapId'] = $map; // get static system data (CCP DB) - $systemModel = $this->_getSystemModelById($systemData['systemId']); + $systemModel = array_values( $this->_getSystemModelByIds([$systemData['systemId']]) )[0]; $systemModel->createdCharacterId = $activeCharacter->characterId; @@ -323,6 +327,46 @@ class System extends \Controller\AccessController { echo json_encode($graphData); } + /** + * get system data for all systems within a constellation + * @param $f3 + * @param $params + */ + public function constellationData($f3, $params){ + + $return = (object) []; + $return->error = []; + $return->systemData = []; + + $constellationId = 0; + + $user = $this->_getUser(); + + if($user){ + // check for search parameter + if( isset($params['arg1']) ){ + $constellationId = (int)$params['arg1']; + } + + $cacheKey = 'CACHE_CONSTELLATION_SYSTEMS_' . self::formatHiveKey($constellationId); + + if($f3->exists($cacheKey)){ + $return->systemData = $f3->get($cacheKey); + }else{ + if($constellationId > 0){ + $systemModels = $this->_getSystemModelByIds([$constellationId], 'constellationID'); + + foreach($systemModels as $systemModel){ + $return->systemData[] = $systemModel->getData(); + } + + $f3->set($cacheKey, $return->systemData, $f3->get('PATHFINDER.CACHE.CONSTELLATION_SYSTEMS') ); + } + } + } + + echo json_encode($return); + } } diff --git a/app/main/controller/api/User.php b/app/main/controller/api/User.php index d0bfbf19..8b26cca7 100644 --- a/app/main/controller/api/User.php +++ b/app/main/controller/api/User.php @@ -22,21 +22,23 @@ class User extends Controller\Controller{ $return = (object) []; - $loginSuccess = false; + $user = null; if($data['loginData']){ $loginData = $data['loginData']; - $loginSuccess = $this->logUserIn( $loginData['userName'], $loginData['userPassword'] ); + $user = $this->logUserIn( $loginData['userName'], $loginData['userPassword'] ); } // set "vague" error - if($loginSuccess !== true){ - + if(is_null($user)){ $return->error = []; $loginError = (object) []; $loginError->type = 'login'; $return->error[] = $loginError; }else{ + // update/check api data + $user->updateApiData(); + // route user to map app $return->reroute = $f3->get('BASE') . $f3->alias('map'); } @@ -48,10 +50,9 @@ class User extends Controller\Controller{ * core function for user login * @param $userName * @param $password - * @return bool + * @return Model\UserModel|null */ private function logUserIn($userName, $password){ - $loginSuccess = false; // try to verify user $user = $this->_verifyUser($userName, $password); @@ -65,16 +66,19 @@ class User extends Controller\Controller{ $this->f3->set('SESSION.user.name', $user->name); $this->f3->set('SESSION.user.id', $user->id); + // save user login information $user->touch('lastLogin'); $user->save(); - // update/check api data - // $this->_updateCharacterData(); - $loginSuccess = true; + // save log + $logText = "id: %s, name: %s, ip: %s"; + self::getLogger( $this->f3->get('PATHFINDER.LOGFILES.LOGIN') )->write( + sprintf($logText, $user->id, $user->name, $this->f3->get('IP')) + ); } - return $loginSuccess; + return $user; } /** @@ -100,30 +104,42 @@ class User extends Controller\Controller{ /** * delete the character log entry for the current active (main) character + * @param $f3 */ - public function deleteLog(){ + public function deleteLog($f3){ $user = $this->_getUser(); + if($user){ + $activeUserCharacter = $user->getActiveUserCharacter(); - $activeUserCharacter = $user->getActiveUserCharacter(); + if($activeUserCharacter){ + $character = $activeUserCharacter->getCharacter(); - if($activeUserCharacter){ - $character = $activeUserCharacter->getCharacter(); + if($characterLog = $character->getLog()){ + $characterLog->erase(); + $characterLog->save(); - if(is_object($character->characterLog)){ - $character->characterLog->erase(); - $character->save(); + $character->clearCacheData(); + + // delete log cache key as well + $f3->clear('LOGGED.user.character.id_' . $characterLog->characterId->id . '.systemId'); + $f3->clear('LOGGED.user.character.id_' . $characterLog->characterId->id . '.shipId'); + + } } } + + } /** * log the current user out + clear character system log data + * @param $f3 */ - public function logOut(){ - $this->deleteLog(); + public function logOut($f3){ + $this->deleteLog($f3); - return parent::logOut(); + return parent::logOut($f3); } /** @@ -284,73 +300,42 @@ class User extends Controller\Controller{ // get all existing API models for this user $apiModels = $user->getAPIs(); - // check if the user already has a main character - // if not -> save the next best character as main - $mainUserCharacter = $user->getMainUserCharacter(); - foreach($settingsData['keyId'] as $i => $keyId){ $api = null; - $userCharacters = []; // search for existing API model foreach($apiModels as $key => $apiModel){ if($apiModel->keyId == $keyId){ $api = $apiModel; - // get existing characters in case api model already exists - $userCharacters = $api->getUserCharacters(); - + // make sure model is up2data -> cast() + $api->cast(); unset($apiModels[$key]); break; } } - if(is_null($api)){ // new API Key $api = Model\BasicModel::getNew('UserApiModel'); $api->userId = $user; } + + $api->keyId = $keyId; $api->vCode = $settingsData['vCode'][$i]; - // check each API Model if valid - $newUserCharacters = $api->requestCharacters(); + // ----- + $api->save(); - if(empty($newUserCharacters)){ + $characterCount = $api->updateCharacters(); + + if($characterCount == 0){ // no characters found -> return warning $characterError = (object) []; $characterError->type = 'warning'; - $characterError->keyId = $api->keyId; - $characterError->vCode = $api->vCode; - $characterError->message = 'No characters found'; + $characterError->message = 'API verification failed. No Characters found for KeyId ' . $api->keyId; $return->error[] = $characterError; - }else{ - $api->save(); - // find existing character - foreach($newUserCharacters as $newUserCharacter){ - - $matchedUserCharacter = $newUserCharacter; - - foreach($userCharacters as $key => $userCharacter){ - if($userCharacter->characterId->id == $newUserCharacter->characterId->id){ - // user character fond -> update this one - $matchedUserCharacter = $userCharacter; - unset($userCharacters[$key]); - break; - } - } - - $matchedUserCharacter->apiId = $api; - $matchedUserCharacter->userId = $user; - - $matchedUserCharacter->save(); - } - } - - // delete characters that are no longer in this API - foreach($userCharacters as $userCharacter){ - print_r('delete Character: ' . $userCharacter->id); } } @@ -359,19 +344,22 @@ class User extends Controller\Controller{ $apiModel->delete(); } - // set main character if no main character exists - if(is_null($mainUserCharacter)){ - $user->setMainCharacterId(); - } - } - // set main character if( isset($settingsData['mainCharacterId']) ){ $user->setMainCharacterId((int)$settingsData['mainCharacterId']); } + // check if the user already has a main character + // if not -> save the next best character as main + $mainUserCharacter = $user->getMainUserCharacter(); + + // set main character if no main character exists + if(is_null($mainUserCharacter)){ + $user->setMainCharacterId(); + } + // save/update user model // this will fail if model validation fails! $user->save(); @@ -385,9 +373,8 @@ class User extends Controller\Controller{ } // get fresh updated user object - $user = $this->_getUser(); + $user = $this->_getUser(0); $newUserData = $user->getData(); - } }catch(Exception\ValidationException $e){ $validationError = (object) []; diff --git a/app/main/model/AllianceModel.php b/app/main/model/AllianceModel.php index 995c2a37..85c1e595 100644 --- a/app/main/model/AllianceModel.php +++ b/app/main/model/AllianceModel.php @@ -12,14 +12,14 @@ class AllianceModel extends BasicModel { protected $table = 'alliance'; - protected $fieldConf = array( - 'allianceCharacters' => array( - 'has-many' => array('Model\CharacterModel', 'allianceId') - ), - 'mapAlliances' => array( - 'has-many' => array('Model\AllianceMapModel', 'allianceId') - ) - ); + protected $fieldConf = [ + 'allianceCharacters' => [ + 'has-many' => ['Model\CharacterModel', 'allianceId'] + ], + 'mapAlliances' => [ + 'has-many' => ['Model\AllianceMapModel', 'allianceId'] + ] + ]; /** * get all alliance data @@ -42,6 +42,16 @@ class AllianceModel extends BasicModel { public function getMaps(){ $maps = []; + $f3 = self::getF3(); + + $this->filter('mapAlliances', + ['active = ?', 1], + [ + 'limit' => $f3->get('PATHFINDER.MAX_MAPS_ALLIANCE'), + 'order' => 'created' + ] + ); + if($this->mapAlliances){ foreach($this->mapAlliances as $mapAlliance){ if($mapAlliance->mapId->isActive()){ @@ -60,7 +70,7 @@ class AllianceModel extends BasicModel { public function getCharacters(){ $characters = []; - $this->filter('allianceCharacters', array('active = ?', 1)); + $this->filter('allianceCharacters', ['active = ?', 1]); if($this->allianceCharacters){ foreach($this->allianceCharacters as $character){ diff --git a/app/main/model/BasicModel.php b/app/main/model/BasicModel.php index a49e1d03..2e074cb2 100644 --- a/app/main/model/BasicModel.php +++ b/app/main/model/BasicModel.php @@ -85,8 +85,6 @@ class BasicModel extends \DB\Cortex { !is_object($currentVal) && $currentVal != $val ){ - //print_r($val); - //print_r($this->cast()); $this->touch('updated'); } } @@ -206,7 +204,6 @@ class BasicModel extends \DB\Cortex { $cacheKey .= '.ID_'; } $cacheKey .= (string) $this->_id; - } return $cacheKey; @@ -327,9 +324,12 @@ class BasicModel extends \DB\Cortex { $cacheKey = $this->getCacheKey($dataCacheKeyPrefix); $cacheData = null; - $f3 = self::getF3(); - if( $f3->exists($cacheKey) ){ - $cacheData = $f3->get( $cacheKey ); + if( !is_null($cacheKey) ){ + $f3 = self::getF3(); + + if( $f3->exists($cacheKey) ){ + $cacheData = $f3->get( $cacheKey ); + } } return $cacheData; diff --git a/app/main/model/CharacterModel.php b/app/main/model/CharacterModel.php index 2ff490e5..8e7ef299 100644 --- a/app/main/model/CharacterModel.php +++ b/app/main/model/CharacterModel.php @@ -27,29 +27,42 @@ class CharacterModel extends BasicModel { /** * get character data + * @param bool|false $addCharacterLogData * @return object */ public function getData($addCharacterLogData = false){ - $characterData = (object) []; - $characterData->id = $this->id; - $characterData->name = $this->name; + // check if there is cached data + $characterData = null; //$this->getCacheData(); - if($addCharacterLogData){ - $logModel = $this->getLog(); - if($logModel){ - $characterData->log = $logModel->getData(); + if(is_null($characterData)){ + // no cached character data found + + $characterData = (object) []; + + $characterData->id = $this->id; + $characterData->name = $this->name; + + if($addCharacterLogData){ + if($logModel = $this->getLog()){ + $characterData->log = $logModel->getData(); + } } - } - // check for corporation - if($this->hasCorporation()){ - $characterData->corporation = $this->getCorporation()->getData(); - } + // check for corporation + if($corporation = $this->getCorporation()){ + $characterData->corporation = $corporation->getData(); + } - // check for alliance - if($this->allianceId){ - $characterData->alliance = $this->allianceId->getData(); + // check for alliance + if($alliance = $this->getAlliance()){ + $characterData->alliance = $alliance->getData(); + } + + // max caching time for a system + // the cached date has to be cleared manually on any change + // this includes system, connection,... changes (all dependencies) + $this->updateCacheData($characterData, '', 300); } return $characterData; diff --git a/app/main/model/CorporationModel.php b/app/main/model/CorporationModel.php index 9e334edb..b2926c5e 100644 --- a/app/main/model/CorporationModel.php +++ b/app/main/model/CorporationModel.php @@ -12,14 +12,14 @@ class CorporationModel extends BasicModel { protected $table = 'corporation'; - protected $fieldConf = array( - 'corporationCharacters' => array( - 'has-many' => array('Model\CharacterModel', 'corporationId') - ), - 'mapCorporations' => array( - 'has-many' => array('Model\CorporationMapModel', 'corporationId') - ) - ); + protected $fieldConf = [ + 'corporationCharacters' => [ + 'has-many' => ['Model\CharacterModel', 'allianceId'] + ], + 'mapCorporations' => [ + 'has-many' => ['Model\CorporationMapModel', 'corporationId'] + ] + ]; /** * get all cooperation data @@ -43,6 +43,16 @@ class CorporationModel extends BasicModel { public function getMaps(){ $maps = []; + $f3 = self::getF3(); + + $this->filter('mapCorporations', + ['active = ?', 1], + [ + 'limit' => $f3->get('PATHFINDER.MAX_MAPS_CORPORATION'), + 'order' => 'created' + ] + ); + if($this->mapCorporations){ foreach($this->mapCorporations as $mapCorporation){ if($mapCorporation->mapId->isActive()){ @@ -61,7 +71,7 @@ class CorporationModel extends BasicModel { public function getCharacters(){ $characters = []; - $this->filter('corporationCharacters', array('active = ?', 1)); + $this->filter('corporationCharacters', ['active = ?', 1]); if($this->corporationCharacters){ foreach($this->corporationCharacters as $character){ diff --git a/app/main/model/MapModel.php b/app/main/model/MapModel.php index e56f9071..d8c55078 100644 --- a/app/main/model/MapModel.php +++ b/app/main/model/MapModel.php @@ -12,29 +12,29 @@ class MapModel extends BasicModel { protected $table = 'map'; - protected $fieldConf = array( - 'scopeId' => array( + protected $fieldConf = [ + 'scopeId' => [ 'belongs-to-one' => 'Model\MapScopeModel' - ), - 'typeId' => array( + ], + 'typeId' => [ 'belongs-to-one' => 'Model\MapTypeModel' - ), - 'systems' => array( - 'has-many' => array('Model\SystemModel', 'mapId') - ), - 'connections' => array( - 'has-many' => array('Model\ConnectionModel', 'mapId') - ), - 'mapUsers' => array( - 'has-many' => array('Model\UserMapModel', 'mapId') - ), - 'mapCorporations' => array( - 'has-many' => array('Model\CorporationMapModel', 'mapId') - ), - 'mapAlliances' => array('has-many' => array( - 'Model\AllianceMapModel', 'mapId') - ) - ); + ], + 'systems' => [ + 'has-many' => ['Model\SystemModel', 'mapId'] + ], + 'connections' => [ + 'has-many' => ['Model\ConnectionModel', 'mapId'] + ], + 'mapUsers' => [ + 'has-many' => ['Model\UserMapModel', 'mapId'] + ], + 'mapCorporations' => [ + 'has-many' => ['Model\CorporationMapModel', 'mapId'] + ], + 'mapAlliances' => ['has-many' => [ + 'Model\AllianceMapModel', 'mapId'] + ] + ]; protected $validate = [ 'name' => [ @@ -210,7 +210,7 @@ class MapModel extends BasicModel { * @return array|mixed */ public function getConnections(){ - $this->filter('connections', array('active = ?', 1)); + $this->filter('connections', ['active = ?', 1]); $connections = []; if($this->connections){ @@ -246,9 +246,9 @@ class MapModel extends BasicModel { if($obj instanceof UserModel){ // private map - // check whether the user already has map access - $this->has('mapUsers', array('active = 1 AND userId = :userId', ':userId' => $obj->id)); - $result = $this->findone(array('id = :id', ':id' => $this->id)); + // check whether the user has already map access + $this->has('mapUsers', ['active = 1 AND userId = :userId', ':userId' => $obj->id]); + $result = $this->findone(['id = :id', ':id' => $this->id]); if($result === false){ // grant access for the user @@ -262,8 +262,8 @@ class MapModel extends BasicModel { } elseif($obj instanceof CorporationModel){ // check whether the corporation already has map access - $this->has('mapCorporations', array('active = 1 AND corporationId = :corporationId', ':corporationId' => $obj->id)); - $result = $this->findone(array('id = :id', ':id' => $this->id)); + $this->has('mapCorporations', ['active = 1 AND corporationId = :corporationId', ':corporationId' => $obj->id]); + $result = $this->findone(['id = :id', ':id' => $this->id]); if($result === false){ // grant access for this corporation @@ -277,8 +277,8 @@ class MapModel extends BasicModel { } elseif($obj instanceof AllianceModel){ // check whether the corporation already has map access - $this->has('mapAlliances', array('active = 1 AND allianceId = :allianceId', ':allianceId' => $obj->id)); - $result = $this->findone(array('id = :id', ':id' => $this->id)); + $this->has('mapAlliances', ['active = 1 AND allianceId = :allianceId', ':allianceId' => $obj->id]); + $result = $this->findone(['id = :id', ':id' => $this->id]); if($result === false){ $allianceMap = self::getNew('AllianceMapModel'); @@ -290,7 +290,6 @@ class MapModel extends BasicModel { } } - if($newAccessGranted){ // mark this map as updated $this->setUpdated(); @@ -362,7 +361,7 @@ class MapModel extends BasicModel { $users = []; if($this->isPrivate()){ - $this->filter('mapUsers', array('active = ?', 1)); + $this->filter('mapUsers', ['active = ?', 1]); if($this->mapUsers){ foreach($this->mapUsers as $mapUser){ @@ -442,7 +441,7 @@ class MapModel extends BasicModel { $corporations = []; if($this->isCorporation()){ - $this->filter('mapCorporations', array('active = ?', 1)); + $this->filter('mapCorporations', ['active = ?', 1]); if($this->mapCorporations){ foreach($this->mapCorporations as $mapCorporation){ @@ -462,7 +461,7 @@ class MapModel extends BasicModel { $alliances = []; if($this->isAlliance()){ - $this->filter('mapAlliances', array('active = ?', 1)); + $this->filter('mapAlliances', ['active = ?', 1]); if($this->mapAlliances){ foreach($this->mapAlliances as $mapAlliance){ diff --git a/app/main/model/SystemModel.php b/app/main/model/SystemModel.php index bc99c128..7b2108ea 100644 --- a/app/main/model/SystemModel.php +++ b/app/main/model/SystemModel.php @@ -11,6 +11,9 @@ namespace Model; class SystemModel extends BasicModel { + const MAX_POS_X = 2300; + const MAX_POS_Y = 500; + protected $table = 'system'; protected $fieldConf = array( @@ -72,53 +75,97 @@ class SystemModel extends BasicModel { */ public function getData(){ - $systemData = (object) []; - $systemData->id = $this->id; - $systemData->mapId = is_object($this->mapId) ? $this->mapId->id : 0; - $systemData->systemId = $this->systemId; - $systemData->name = $this->name; - $systemData->alias = $this->alias; - $systemData->effect = $this->effect; - $systemData->security = $this->security; - $systemData->trueSec = $this->trueSec; + // check if there is cached data + $systemData = $this->getCacheData(); - $systemData->region = (object) []; - $systemData->region->id = $this->regionId; - $systemData->region->name = $this->region; + if(is_null($systemData)){ + // no cached system data found - $systemData->constellation = (object) []; - $systemData->constellation->id = $this->constellationId; - $systemData->constellation->name = $this->constellation; + $systemData = (object) []; + $systemData->id = $this->id; + $systemData->mapId = is_object($this->mapId) ? $this->mapId->id : 0; + $systemData->systemId = $this->systemId; + $systemData->name = $this->name; + $systemData->alias = $this->alias; + $systemData->effect = $this->effect; + $systemData->security = $this->security; + $systemData->trueSec = $this->trueSec; - $systemData->type = (object) []; - $systemData->type->id = $this->typeId->id; - $systemData->type->name = $this->typeId->name; + $systemData->region = (object) []; + $systemData->region->id = $this->regionId; + $systemData->region->name = $this->region; - $systemData->status = (object) []; - $systemData->status->id = is_object($this->statusId) ? $this->statusId->id : 0; - $systemData->status->name = is_object($this->statusId) ? $this->statusId->name : ''; + $systemData->constellation = (object) []; + $systemData->constellation->id = $this->constellationId; + $systemData->constellation->name = $this->constellation; - $systemData->locked = $this->locked; - $systemData->rally = $this->rally; - $systemData->description = $this->description; + $systemData->type = (object) []; + $systemData->type->id = $this->typeId->id; + $systemData->type->name = $this->typeId->name; - $systemData->statics = $this->getStaticWormholeData(); + $systemData->status = (object) []; + $systemData->status->id = is_object($this->statusId) ? $this->statusId->id : 0; + $systemData->status->name = is_object($this->statusId) ? $this->statusId->name : ''; - $systemData->position = (object) []; - $systemData->position->x = $this->posX; - $systemData->position->y = $this->posY; + $systemData->locked = $this->locked; + $systemData->rally = $this->rally; + $systemData->description = $this->description; - $systemData->created = (object) []; - $systemData->created->character = $this->createdCharacterId->getData(); - $systemData->created->created = strtotime($this->created); + $systemData->statics = $this->getStaticWormholeData(); - $systemData->updated = (object) []; - $systemData->updated->character = $this->updatedCharacterId->getData(); - $systemData->updated->updated = strtotime($this->updated); + $systemData->position = (object) []; + $systemData->position->x = $this->posX; + $systemData->position->y = $this->posY; + + if($this->createdCharacterId){ + $systemData->created = (object) []; + $systemData->created->character = $this->createdCharacterId->getData(); + $systemData->created->created = strtotime($this->created); + } + + if($this->updatedCharacterId){ + $systemData->updated = (object) []; + $systemData->updated->character = $this->updatedCharacterId->getData(); + $systemData->updated->updated = strtotime($this->updated); + } + + // max caching time for a system + // the cached date has to be cleared manually on any change + // this includes system, connection,... changes (all dependencies) + $this->updateCacheData($systemData, '', 300); + } return $systemData; } + /** + * setter validation for x coordinate + * @param $posX + * @return int|number + */ + public function set_posX($posX){ + $posX = abs($posX); + if($posX > self::MAX_POS_X){ + $posX = self::MAX_POS_X; + } + + return $posX; + } + + /** + * setter validation for y coordinate + * @param $posY + * @return int|number + */ + public function set_posY($posY){ + $posY = abs($posY); + if($posY > self::MAX_POS_Y){ + $posY = self::MAX_POS_Y; + } + + return $posY; + } + /** * check object for model access * @param $accessObject @@ -148,7 +195,7 @@ class SystemModel extends BasicModel { * @return array */ public function getSignatures(){ - $this->filter('signatures', array('active = ?', 1)); + $this->filter('signatures', ['active = ?', 1], ['order' => 'name']); $signatures = []; if($this->signatures){ diff --git a/app/main/model/UserApiModel.php b/app/main/model/UserApiModel.php index 46913e05..7bb662cc 100644 --- a/app/main/model/UserApiModel.php +++ b/app/main/model/UserApiModel.php @@ -35,13 +35,12 @@ class UserApiModel extends BasicModel { } /** - * request CCP API and get all characters for this API - * @return array + * @return int */ - public function requestCharacters(){ - + public function updateCharacters(){ $apiController = new Controller\CcpApiController(); - return $apiController->getCharacters([$this]); + + return $apiController->updateCharacters($this); } /** @@ -49,7 +48,7 @@ class UserApiModel extends BasicModel { * @return array|mixed */ public function getUserCharacters(){ - $this->filter('userCharacters', array('active = ?', 1)); + $this->filter('userCharacters', ['active = ?', 1]); $userCharacters = []; if($this->userCharacters){ diff --git a/app/main/model/UserCharacterModel.php b/app/main/model/UserCharacterModel.php index 31b990aa..d1d5b2a5 100644 --- a/app/main/model/UserCharacterModel.php +++ b/app/main/model/UserCharacterModel.php @@ -13,8 +13,6 @@ class UserCharacterModel extends BasicModel { protected $table = 'user_character'; - private $character = null; - protected $fieldConf = array( 'userId' => array( 'belongs-to-one' => 'Model\UserModel' diff --git a/app/main/model/UserModel.php b/app/main/model/UserModel.php index 58284969..04ad42ba 100644 --- a/app/main/model/UserModel.php +++ b/app/main/model/UserModel.php @@ -157,7 +157,17 @@ class UserModel extends BasicModel { * @return array */ public function getMaps(){ - $this->filter('userMaps', array('active = ?', 1)); + + $f3 = self::getF3(); + + $this->filter( + 'userMaps', + ['active = ?', 1], + [ + 'limit' => $f3->get('PATHFINDER.MAX_MAPS_PRIVATE'), + 'order' => 'created' + ] + ); $maps = []; if($this->userMaps){ @@ -190,12 +200,25 @@ class UserModel extends BasicModel { return $maps; } + public function getMap($mapId){ + $map = self::getNew('MapModel'); + $map->getById( (int)$mapId ); + + $returnMap = null; + if($map->hasAccess($this)){ + $returnMap = $map; + } + + return $returnMap; + } + + /** * get all API models for this user * @return array|mixed */ public function getAPIs(){ - $this->filter('apis', array('active = ?', 1)); + $this->filter('apis', ['active = ?', 1]); $apis = []; if($this->apis){ @@ -242,13 +265,30 @@ class UserModel extends BasicModel { * @return array|mixed */ public function getUserCharacters(){ - $this->filter('userCharacters', array('active = ?', 1)); + + $this->filter('apis', ['active = ?', 1]); $userCharacters = []; - if($this->userCharacters){ - $userCharacters = $this->userCharacters; + + if($this->apis){ + $this->apis->rewind(); + while($this->apis->valid()){ + + $this->apis->current()->filter('userCharacters', ['active = ?', 1]); + if($this->apis->current()->userCharacters){ + $this->apis->current()->userCharacters->rewind(); + while($this->apis->current()->userCharacters->valid()){ + $userCharacters[] = $this->apis->current()->userCharacters->current(); + $this->apis->current()->userCharacters->next(); + } + } + + $this->apis->next(); + } } + + return $userCharacters; } @@ -283,14 +323,23 @@ class UserModel extends BasicModel { // check if IGB Data is available if( !empty($apiController->values) ){ // search for the active character by IGB Header Data - $activeUserCharacters = $this->getActiveUserCharacters(); - foreach($activeUserCharacters as $userCharacter){ + $this->filter('userCharacters', + [ + 'active = :active AND characterId = :characterId', + ':active' => 1, + ':characterId' => intval($apiController->values['charid']) + ], + ['limit' => 1] + ); - if($userCharacter->getCharacter()->id == intval($apiController->values['charid']) ){ - $activeUserCharacter = $userCharacter; - break; - } + if($this->userCharacters){ + // check if userCharacter has active log + $userCharacter = current($this->userCharacters); + + if( $userCharacter->getCharacter()->getLog() ){ + $activeUserCharacter = $userCharacter; + } } } @@ -325,44 +374,86 @@ class UserModel extends BasicModel { } /** - * updated the character log entry for a user character by IGB Header data + * update/check API information. + * request API information from CCP */ - public function updateCharacterLog(){ + public function updateApiData(){ + $this->filter('apis', ['active = ?', 1]); + + if($this->apis){ + $this->apis->rewind(); + while($this->apis->valid()){ + $this->apis->current()->updateCharacters(); + $this->apis->next(); + } + + } + } + + /** + * updated the character log entry for a user character by IGB Header data + * @param int $ttl cache time in seconds + * @throws \Exception + */ + public function updateCharacterLog($ttl = 0){ $apiController = Controller\CcpApiController::getIGBHeaderData(); // check if IGB Data is available if( !empty($apiController->values) ){ + $f3 = self::getF3(); - $character = self::getNew('CharacterModel'); - $character->getById( $apiController->values['charid'] ); + // check if system has changed since the last call + // current location is stored in session to avoid unnecessary DB calls + $sessionCharacterKey = 'LOGGED.user.character.id_' . $apiController->values['charid']; - if( $character->dry() ){ - // this can happen if a valid user plays the game with a not registered character - // whose API is not registered -> save new character or update character data + if( + !$f3->exists($sessionCharacterKey) || + $f3->get($sessionCharacterKey . '.systemId') != $apiController->values['solarsystemid'] || + $f3->get($sessionCharacterKey . '.shipId') != $apiController->values['shiptypeid'] + ){ - $character->id = $apiController->values['charid']; - $character->name = $apiController->values['charname']; - $character->corporationId = array_key_exists('corpid', $apiController->values) ? $apiController->values['corpid'] : null; - $character->allianceId = array_key_exists('allianceid', $apiController->values) ? $apiController->values['allianceid'] : null; - $character->save(); + $cacheData = [ + 'systemId' => $apiController->values['solarsystemid'], + 'shipId' => $apiController->values['shiptypeid'] + ]; + + // character has changed system, or character just logged on + $character = self::getNew('CharacterModel'); + $character->getById( (int)$apiController->values['charid'] ); + + if( $character->dry() ){ + // this can happen if a valid user plays the game with a not registered character + // whose API is not registered -> save new character or update character data + + $character->id = (int) $apiController->values['charid']; + $character->name = $apiController->values['charname']; + $character->corporationId = array_key_exists('corpid', $apiController->values) ? $apiController->values['corpid'] : null; + $character->allianceId = array_key_exists('allianceid', $apiController->values) ? $apiController->values['allianceid'] : null; + $character->save(); + } + + // check if this character has an active log + if( !$characterLog = $character->getLog() ){ + $characterLog = self::getNew('CharacterLogModel'); + } + + // set character log values + $characterLog->characterId = $character; + $characterLog->systemId = $apiController->values['solarsystemid']; + $characterLog->systemName = $apiController->values['solarsystemname']; + $characterLog->shipId = $apiController->values['shiptypeid']; + $characterLog->shipName = $apiController->values['shipname']; + $characterLog->shipTypeName = $apiController->values['shiptypename']; + + $characterLog->save(); + + // clear cache for the characterModel as well + $character->clearCacheData(); + + // cache character log information + $f3->set($sessionCharacterKey, $cacheData, $ttl); } - // check if this character has an active log - if( is_object($character->characterLog) ){ - $characterLog = $character->characterLog; - }else{ - $characterLog = self::getNew('CharacterLogModel'); - } - - // set character log values - $characterLog->characterId = $character; - $characterLog->systemId = $apiController->values['solarsystemid']; - $characterLog->systemName = $apiController->values['solarsystemname']; - $characterLog->shipId = $apiController->values['shiptypeid']; - $characterLog->shipName = $apiController->values['shipname']; - $characterLog->shipTypeName = $apiController->values['shiptypename']; - - $characterLog->save(); } }