Files
pathfinder/app/main/model/charactermodel.php
Mark Friedrich ecd505a202 v1.0.0 (#183)
* #84 test data dump from CREST login

* updated "credits" dialog (Google+ link)
fixed login form layout

* updated Cortex Data-Mapper

* - #84 CREST Login (WIP)
- New CREST controller
- Database restructuring
- improved type-casting for some controller functions
- New login process
- Fixed some bugs during the setup process (/setup root)
- Added CREST request caching by response headers

* pathfinder-84 [Feature Request] CREST Pilot Tracking, many smaller Bugfixes

* pathfinder-84 [Feature Request] added develop JS files

* closed #121 fixed wormhole signature type caching

* closed #120 removed map-loading animation for larger maps (same behaviour as IGB)

* closed #119 fixed wormhole signature id count

* closed #114 Added check for already existing system when adding a new one. (fixed PDO 'duplicate entry' error)

* closed #112 fixed DataTables error for missing "status" data (signature table)

* closed #111 fixed convertDataToUTC(); client side date transformation

* closed #109 fixed system TrueSec rounding

* closed #103 fixed system updated timestamp in getData()

* fixed CSS class for secStatus in Routes module

* closed #121 fixed wormhole signature type caching

* changed dateTime format from German to US format
fixed some minor bugs in signatureTable module

* closed #81 fixed "signature type" overwriting by "signature reader" update

* closed #106 added new signature_types form C5/6 wormholes (gas/ore)

* closed #129 fixed parameter hinting

* closed #131 new "route search" algorithm, added current map systems to live search, added refresh/update functionality for each found route, added bulk route refresh function, added "meta map" route search (search on multiple maps), added route "filters" (restrict search on "stargates", "wormholes", "jumpbridges"), added route "filter" for wormholes (reduced/critical wormholes)
closed #89 fixed "loop connections" on same system
#84 added error messages for "invalid" CREST "Client ID"
added "bootboxjs" (customized styled checkboxes/radio buttons) CSS only
"Font Awesome" version upgrade 4.4.0 -> 4.61
"Bootbox.js" version upgrade 4.3.0 -> 4.4.0
fixed "system dialog" (added responsive layout)

* closed #134  fixed db column type DT_INT (8 bytes) to DT_BIGINT

* closed #138 added new cookie based login

* closed #137 fixed javascript errors on trying to establish an "invalid" connection

* - #84, #138 improved "character selection" on login page (expired cookies are deleted, character panel layout improvements)
- added new "Server info panel" to the login page
- added new cronjob to delete expired cookie authentication data

* #138 enables character switching between characters which have same user

* - PHP Framework upgrade 3.5.0 -> 3.5.1 (fixes some issues with CREST cURL caching, and SESSION management)
- #138 added "cookie logout" to "logout" menu entry

* - updated "feature page" with new feature descriptions and label
- added some new images to the "feature gallery"
- removed "beta" status from "magnetizing" feature on map menu
- hide "server status" panel on "mobile" breakpoint

* - #138 clear character authentication data on sold characters

* closed #142 added custom "onsuspect()" session handler

* #142 do not log suspect if no file is defined in pathfinder.ini

* #142 added NullSec Data/Relic sites to C1/2/3 wormholes as signature option

* #144 fixed "Character not found" warning

* #144 fixed "Character not found" warning

* closed #144 fixed broken routes panel in IGB

* updated README.md for upcoming release

* #147 response header validation

* #149 changed comment for 'BASE' framework var

* fixed map  import

* - added minimal SDE dump (EVE Online: Citadel)
- #147 improved CREST API error logging (WIP)
- improved SSO controller (removed access_token from public endpoints)

* closed #154 added alliance maps to CREST API

* - updated Gulp build dependencies
- increased CREST timeout from 3s -> 4s
- added "Accept" Headers for some CREST endpoints

* cloased #147

* - closed #153 added character verification check for getAll(); Signatures Ajax endpoint

* - updated README.md (added Slack developer chat information)

* Bugfix frig holes (#159)

* added missing frigate wormholes and fixed Q003 destination in shattered wormholes

* changed C7 to 0.0 for Q003

* - fixed broken "graph" data for system

* added a  "failover" system  for bad crest requests (HTTP status 5xx,.. )

* Red Gaint => Red Giant (#161)

* closed #163 added CREST endpoint support for "waypoints"

* fixed typo

* closed #160 fixed tooltip container

* - added new features to login page

* closes #154 added alliance map support

* fixed XML path for cronjobs

* fixed a bug with inactive "private" maps

* closes #175 added alternative environment configuration

* - v1.0.0  build
2016-06-03 23:05:34 +02:00

561 lines
17 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* Created by PhpStorm.
* User: exodus4d
* Date: 11.04.15
* Time: 15:20
*/
namespace Model;
use Controller;
use Controller\Ccp\Sso as Sso;
use DB\SQL\Schema;
use Data\Mapper as Mapper;
class CharacterModel extends BasicModel {
protected $table = 'character';
protected $fieldConf = [
'lastLogin' => [
'type' => Schema::DT_TIMESTAMP,
'index' => true
],
'active' => [
'type' => Schema::DT_BOOL,
'nullable' => false,
'default' => 1,
'index' => true
],
'name' => [
'type' => Schema::DT_VARCHAR128,
'nullable' => false,
'default' => ''
],
'ownerHash' => [
'type' => Schema::DT_VARCHAR128,
'nullable' => false,
'default' => ''
],
'crestAccessToken' => [
'type' => Schema::DT_VARCHAR256
],
'crestAccessTokenUpdated' => [
'type' => Schema::DT_TIMESTAMP,
'default' => Schema::DF_CURRENT_TIMESTAMP,
'index' => true
],
'crestRefreshToken' => [
'type' => Schema::DT_VARCHAR256
],
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
'belongs-to-one' => 'Model\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
'on-delete' => 'SET NULL'
]
]
],
'allianceId' => [
'type' => Schema::DT_INT,
'index' => true,
'belongs-to-one' => 'Model\AllianceModel',
'constraint' => [
[
'table' => 'alliance',
'on-delete' => 'SET NULL'
]
]
],
'factionId' => [
'type' => Schema::DT_INT,
'index' => true
],
'factionName' => [
'type' => Schema::DT_VARCHAR128,
'nullable' => false,
'default' => ''
],
'shared' => [
'type' => Schema::DT_BOOL,
'nullable' => false,
'default' => 0
],
'userCharacter' => [
'has-one' => ['Model\UserCharacterModel', 'characterId']
],
'characterLog' => [
'has-one' => ['Model\CharacterLogModel', 'characterId']
],
'characterMaps' => [
'has-many' => ['Model\CharacterMapModel', 'characterId']
],
'characterAuthentications' => [
'has-many' => ['Model\CharacterAuthenticationModel', 'characterId']
]
];
/**
* get character data
* @param bool|false $addCharacterLogData
* @return \stdClass
*/
public function getData($addCharacterLogData = false){
$cacheKeyModifier = '';
// check if there is cached data
if($addCharacterLogData){
$cacheKeyModifier = strtoupper($this->table) . '_LOG';
}
$characterData = $this->getCacheData($cacheKeyModifier);
if(is_null($characterData)){
// no cached character data found
$characterData = (object) [];
$characterData->id = $this->id;
$characterData->name = $this->name;
$characterData->shared = $this->shared;
if($addCharacterLogData){
if($logModel = $this->getLog()){
$characterData->log = $logModel->getData();
}
}
// check for corporation
if($corporation = $this->getCorporation()){
$characterData->corporation = $corporation->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, $cacheKeyModifier, 10);
}
return $characterData;
}
/**
* set unique "ownerHash" for this character
* -> Hash will change when character is transferred (sold)
* @param string $ownerHash
* @return string
*/
public function set_ownerHash($ownerHash){
if( $this->ownerHash !== $ownerHash ){
if( $this->hasUserCharacter() ){
$this->userCharacter->erase();
}
// delete all existing login-cookie data
$this->logout();
}
return $ownerHash;
}
/**
* set CREST accessToken for current session
* -> update "tokenUpdated" column on change
* -> this is required for expire checking!
* @param string $accessToken
* @return string
*/
public function set_crestAccessToken($accessToken){
if($this->crestAccessToken !== $accessToken){
$this->touch('crestAccessTokenUpdated');
}
return $accessToken;
}
/**
* check whether this character has already a user assigned to it
* @return bool
*/
public function hasUserCharacter(){
return is_object($this->userCharacter);
}
/**
* check whether this character has a corporation
* @return bool
*/
public function hasCorporation(){
return is_object($this->corporationId);
}
/**
* check whether this character has an alliance
* @return bool
*/
public function hasAlliance(){
return is_object($this->allianceId);
}
/**
* @return UserModel|null
*/
public function getUser(){
$user = null;
if($this->hasUserCharacter()){
/**
* @var $user UserModel
*/
$user = $this->userCharacter->userId;
}
return $user;
}
/**
* get the corporation for this user
* @return \Model\CorporationModel|null
*/
public function getCorporation(){
return $this->corporationId;
}
/**
* get the alliance of this user
* @return \Model\AllianceModel|null
*/
public function getAlliance(){
return $this->allianceId;
}
/**
* get CREST API "access_token" from OAuth
* @return bool|string
*/
public function getAccessToken(){
$accessToken = false;
// check if there is already an "accessToken" for this user
// check expire timer for stored "accessToken"
if(
!empty($this->crestAccessToken) &&
!empty($this->crestAccessTokenUpdated)
){
$timezone = new \DateTimeZone( $this->getF3()->get('TZ') );
$tokenTime = \DateTime::createFromFormat(
'Y-m-d H:i:s',
$this->crestAccessTokenUpdated,
$timezone
);
// add expire time buffer for this "accessToken"
// token should be marked as "deprecated" BEFORE it actually expires.
$timeBuffer = 2 * 60;
$tokenTime->add(new \DateInterval('PT' . (Sso::ACCESS_KEY_EXPIRE_TIME - $timeBuffer) . 'S'));
$now = new \DateTime('now', $timezone);
if($tokenTime->getTimestamp() > $now->getTimestamp()){
$accessToken = $this->crestAccessToken;
}
}
// if no "accessToken" was found -> get a fresh one by an existing "refreshToken"
if(
!$accessToken &&
!empty($this->crestRefreshToken)
){
// no accessToken found OR token is deprecated
$ssoController = new Sso();
$accessData = $ssoController->refreshAccessToken($this->crestRefreshToken);
if(
isset($accessData->accessToken) &&
isset($accessData->refreshToken)
){
$this->crestAccessToken = $accessData->accessToken;
$this->save();
$accessToken = $this->crestAccessToken;
}
}
return $accessToken;
}
/**
* checks whether this character is authorized to log in
* -> check corp/ally whitelist config (pathfinder.ini)
* @return bool
*/
public function isAuthorized(){
$isAuthorized = false;
$f3 = self::getF3();
$whitelistCorporations = $whitelistAlliance = [];
if( !empty($f3->get('PATHFINDER.LOGIN.CORPORATION')) ){
$whitelistCorporations = array_map('trim',(array) $f3->get('PATHFINDER.LOGIN.CORPORATION') );
}
if( !empty($f3->get('PATHFINDER.LOGIN.ALLIANCE')) ){
$whitelistAlliance = array_map('trim',(array) $f3->get('PATHFINDER.LOGIN.ALLIANCE') );
}
if(
empty($whitelistCorporations) &&
empty($whitelistAlliance)
){
// no corp/ally restrictions set -> any character is allowed to login
$isAuthorized = true;
}else{
// check if character corporation is set in whitelist
if(
!empty($whitelistCorporations) &&
$this->hasCorporation() &&
in_array($this->getCorporation()->_id, $whitelistCorporations)
){
$isAuthorized = true;
}
// check if character alliance is set in whitelist
if(
!$isAuthorized &&
!empty($whitelistAlliance) &&
$this->hasAlliance() &&
in_array($this->getAlliance()->_id, $whitelistAlliance)
){
$isAuthorized = true;
}
}
return $isAuthorized;
}
/**
* update character log (active system, ...)
* -> HTTP Header Data (if IGB)
* -> CREST API request for character log data (if not IGB)
* @param array $additionalOptions (optional) request options for cURL request
* @return $this
*/
public function updateLog($additionalOptions = []){
// check if everything is OK
// -> do not update log in case of temporary CREST timeouts
$updateLogData = false;
$logData = [];
$headerData = Controller\Controller::getIGBHeaderData();
// check if IGB Data is available
if(
$headerData->trusted === true &&
!empty($headerData->values)
){
// format header data
$formattedHeaderData = (new Mapper\IgbHeader($headerData->values))->getData();
// just for security -> check if Header Data matches THIS character
// in case current IGB-Character is NOT the one logged on -> don´t update log
if(
isset($formattedHeaderData['character']) &&
$formattedHeaderData['character']['id'] == $this->_id
){
$updateLogData = true;
$logData = $formattedHeaderData;
}
}
if($updateLogData == false){
// ... IGB Header data not found OR character does not match current active character
// -> try to pull data from CREST
$ssoController = new Sso();
$logData = $ssoController->getCharacterLocationData($this->getAccessToken(), 10, $additionalOptions);
if($logData['timeout'] === false){
$updateLogData = true;
}
}
if($updateLogData == true){
if( empty($logData['system']) ){
// character is not in-game
if(is_object($this->characterLog)){
// delete existing log
$this->characterLog->erase();
$this->save();
}
}else{
// character is currently in-game
if( !$characterLog = $this->getLog() ){
// create new log
$characterLog = $this->rel('characterLog');
$characterLog->characterId = $this->_id;
}
$characterLog->setData($logData);
$characterLog->save();
$this->characterLog = $characterLog;
}
}
return $this;
}
/**
* update character data from CCPs CREST API
* @return array (some status messages)
*/
public function updateFromCrest(){
$status = [];
if( $accessToken = $this->getAccessToken() ){
// et basic character data
// -> this is required for "ownerHash" hash check (e.g. character was sold,..)
// -> the "id" check is just for security and should NEVER fail!
$ssoController = new Sso();
if(
!is_null( $verificationCharacterData = $ssoController->verifyCharacterData($accessToken) ) &&
$verificationCharacterData->CharacterID === $this->_id
){
// get character data from CREST
$characterData = $ssoController->getCharacterData($accessToken);
if( isset($characterData->character) ){
$characterData->character['ownerHash'] = $verificationCharacterData->CharacterOwnerHash;
$corporation = null;
$alliance = null;
if( isset($characterData->corporation) ){
/**
* @var $corporation CorporationModel
*/
$corporation = $this->rel('corporationId');
$corporation->getById($characterData->corporation['id'], 0);
$corporation->copyfrom($characterData->corporation, ['id', 'name', 'isNPC']);
$corporation->save();
}
if( isset($characterData->alliance) ){
/**
* @var $alliance AllianceModel
*/
$alliance = $this->rel('allianceId');
$alliance->getById($characterData->alliance['id'], 0);
$alliance->copyfrom($characterData->alliance, ['id', 'name']);
$alliance->save();
}
$this->copyfrom($characterData->character, ['name', 'ownerHash']);
$this->set('corporationId', is_object($corporation) ? $corporation->get('id') : null);
$this->set('allianceId', is_object($alliance) ? $alliance->get('id') : null);
$this->save();
}
}else{
$status[] = sprintf(Sso::ERROR_VERIFY_CHARACTER, $this->name);
}
}else{
$status[] = sprintf(Sso::ERROR_ACCESS_TOKEN, $this->name);
}
return $status;
}
/**
* get a unique cookie name for this character
* -> cookie name does not have to be "secure"
* -> but is should be unique
* @return string
*/
public function getCookieName(){
return md5($this->name);
}
/**
* get the character log entry for this character
* @return bool|CharacterLogModel
*/
public function getLog(){
$characterLog = false;
if(
is_object($this->characterLog) &&
!$this->characterLog->dry()
){
$characterLog = &$this->characterLog;
}
return $characterLog;
}
/**
* get mapModel by id and check if user has access
* @param $mapId
* @return MapModel|null
*/
public function getMap($mapId){
/**
* @var $map MapModel
*/
$map = self::getNew('MapModel');
$map->getById( (int)$mapId );
$returnMap = null;
if($map->hasAccess($this)){
$returnMap = $map;
}
return $returnMap;
}
/**
* get all accessible map models for this character
* @return MapModel[]
*/
public function getMaps(){
$this->filter(
'characterMaps',
['active = ?', 1],
['order' => 'created']
);
$maps = [];
if($alliance = $this->getAlliance()){
$maps = array_merge($maps, $alliance->getMaps());
}
if($corporation = $this->getCorporation()){
$maps = array_merge($maps, $corporation->getMaps());
}
if($this->characterMaps){
$mapCountPrivate = 0;
foreach($this->characterMaps as &$characterMap){
if(
$mapCountPrivate < self::getF3()->get('PATHFINDER.MAX_MAPS_PRIVATE') &&
$characterMap->mapId->isActive()
){
$maps[] = &$characterMap->mapId;
$mapCountPrivate++;
}
}
}
return $maps;
}
public function logout(){
if($this->characterAuthentications){
foreach($this->characterAuthentications as $characterAuthentication){
/**
* @var $characterAuthentication CharacterAuthenticationModel
*/
$characterAuthentication->erase();
}
}
}
}