diff --git a/.gitignore b/.gitignore index f5b99ae3..0f902190 100644 --- a/.gitignore +++ b/.gitignore @@ -47,7 +47,6 @@ Temporary Items # project files # ======================== .idea -.sass-cache .usage *.gz composer-dev.lock diff --git a/.jshintrc b/.jshintrc index 2ebd120f..c61df68c 100644 --- a/.jshintrc +++ b/.jshintrc @@ -35,7 +35,7 @@ "latedef": false, // Enforce line length to 100 characters - "maxlen": 200, + "maxlen": 220, // Require capitalized names for constructor functions. "newcap": true, diff --git a/README.md b/README.md index bdf15843..bc7d3705 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,16 @@ #  *PATHFINDER* -Mapping tool for [*EVE ONLINE*](https://www.eveonline.com) +#### Mapping tool for [*EVE ONLINE*](https://www.eveonline.com) - Project URL [https://www.pathfinder-w.space](https://www.pathfinder-w.space) -- Official forum post [https://forums.eveonline.com](https://forums.eveonline.com/default.aspx?g=posts&m=6021776#post6021776) - Screenshots [imgur.com](http://imgur.com/a/k2aVa) - Videos [youtube.com](https://www.youtube.com/channel/UC7HU7XEoMbqRwqxDTbMjSPg) - Licence [MIT](http://opensource.org/licenses/MIT) #### Development -- Test server - - URL: http://www.dev.pathfinder-w.space +- Test server: [https://www.dev.pathfinder-w.space](https://www.dev.pathfinder-w.space) - Running current `develop` branch - _SISI_ _ESI_ (make sure to use your test-server client) - - Available for public testing (e.g. new feature,.. ) + - Available for public testing (e.g. new feature,… ) - Database will be cleared from time to time - Installation guide: - [wiki](https://github.com/exodus4d/pathfinder/wiki) @@ -27,52 +25,55 @@ Issues should be reported in the [Issue](https://github.com/exodus4d/pathfinder/ *** ### Project structure +
+ ─╮
+ ├─ app/ [0755] → PHP root
+ │ ├─ Controller/ → controller classes for app/ajax endpoints (see routes.ini)
+ │ ├─ Cron/ → controller classes cronjob endpoints (see cron.ini)
+ │ ├─ Data/ → classes for data handling
+ │ ├─ Db/ → classes for DB handling
+ │ ├─ Exception/ → custom exceptions
+ │ ├─ Lib/ → libs
+ │ ├─ Model/ → ORM
+ │ ├─ config.ini → config - F3 core config: SystemVariables
+ │ ├─ cron.ini → config - cronjobs
+ │ ├─ environment.ini → config - system environment
+ │ ├─ pathfinder.ini → config - pathfinder
+ │ ├─ plugin.ini → config - custom plugins
+ │ ├─ requirements.ini → config - system requirements
+ │ └─ routes.ini → config - routes
+ ├─ export/ [0755] → static data
+ │ ├─ csv/ → *.csv used by /setup page
+ │ └─ sql/ → DB dump for import (eve_universe.sql.zip)
+ ├─ favicon/ [0755] → favicons
+ ├─ history/ [0777] → log files (map history logs) [optional]
+ ├─ js/ [0755] → JS source files (not used for production)
+ │ ├─ app/ → "PATHFINDER" core files
+ │ ├─ lib/ → 3rd party libs
+ │ └─ app.js → require.js config
+ ├─ logs/ [0777] → log files
+ │ └─ …
+ ├─ public/ [0755] → static resources
+ │ ├─ css/ → CSS dist/build folder (minified)
+ │ ├─ fonts/ → icon-/fonts
+ │ ├─ img/ → images
+ │ ├─ js/ → JS dist/build folder and source maps (minified, uglified)
+ │ └─ templates/ → templates
+ ├─ sass/ → SCSS sources (not used for production)
+ ├─ tmp/ [0777] → cache folder (PHP templates)
+ │ └─ cache/ [0777] → cache folder (PHP cache)
+ ├─ .htaccess [0755] → reroute/caching rules ("Apache" only!)
+ └─ index.php [0755]
-```
- |-- [0755] app/ --> backend [*.php]
- |-- app/ --> "Fat Free Framework" extensions
- |-- lib/ --> "Fat Free Framework"
- |-- main/ --> "PATHFINDER" root
- |-- config.ini --> config "f3" framework
- |-- cron.ini --> config - cronjobs
- |-- environment.ini --> config - system environment
- |-- pathfinder.ini --> config - pathfinder
- |-- requirements.ini --> config - system requirements
- |-- routes.ini --> config - routes
- |-- [0755] export/ --> static data
- |-- csv/ --> *.csv used by /setup page
- |-- sql/ --> DB dump for import (eve_universe.sql.zip)
- |-- [0755] favicon/ --> Favicons
- |-- [0777] history/ --> log files (map history logs) [optional]
- |-- [0755] js/ --> JS source files
- |-- app/ --> "PASTHFINDER" core files (not used for production)
- |-- lib/ --> 3rd partie extension/library (not used for production)
- |-- app.js --> require.js config (!required for production!)
- |-- [0777] logs/ --> log files
- |-- ...
- |-- node_modules/ --> node.js modules (not used for production)
- |-- ...
- |-- [0755] public/ --> frontend source
- |-- css/ --> CSS dist/build folder (minified)
- |-- fonts/ --> (icon)-Fonts
- |-- img/ --> images
- |-- js/ --> JS dist/build folder and source maps (minified, uglified)
- |-- templates/ --> templates
- |-- sass/ --> SCSS source (not used for production)
- |-- [0777] tmp/ --> cache folder
- |-- [0755] .htaccess --> reroute/caching rules ("Apache" only!)
- |-- [0755] index.php
-
- --------------------------
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━
CI/CD config files:
- --------------------------
- |-- .jshintrc --> "JSHint" config (not used for production)
- |-- composer.json --> Composer package definition
- |-- config.rb --> "Compass" config (not used for production)
- |-- gulpfile.js --> "Gulp" task config (not used for production )
- |-- package.json --> "Node.js" dependency config (not used for production)
- |-- README.md --> This file :) (not used for production)
-```
+
+ ├─ .jshintrc → "JSHint" config (not used for production)
+ ├─ composer.json → "Composer" package definition
+ ├─ gulpfile.js → "Gulp" task config (not used for production)
+ ├─ package.json → "Node.js" dependency config (not used for production)
+ └─ README.md → This file :) (not used for production)
+
***
diff --git a/app/main/controller/accesscontroller.php b/app/Controller/AccessController.php
similarity index 87%
rename from app/main/controller/accesscontroller.php
rename to app/Controller/AccessController.php
index ab2dca79..63453f37 100644
--- a/app/main/controller/accesscontroller.php
+++ b/app/Controller/AccessController.php
@@ -6,10 +6,10 @@
* Time: 23:30
*/
-namespace Controller;
+namespace Exodus4D\Pathfinder\Controller;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class AccessController extends Controller {
@@ -77,11 +77,11 @@ class AccessController extends Controller {
/**
* broadcast MapModel to clients
- * @see broadcastMapData()
* @param Pathfinder\MapModel $map
+ * @param bool $noCache
*/
- protected function broadcastMap(Pathfinder\MapModel $map) : void {
- $this->broadcastMapData($this->getFormattedMapData($map));
+ protected function broadcastMap(Pathfinder\MapModel $map, bool $noCache = false) : void {
+ $this->broadcastMapData($this->getFormattedMapData($map, $noCache));
}
@@ -99,18 +99,13 @@ class AccessController extends Controller {
/**
* get formatted Map Data
* @param Pathfinder\MapModel $map
- * @return array
- * @throws \Exception
- */
-
- /**
- * @param Pathfinder\MapModel $map
+ * @param bool $noCache
* @return array|null
*/
- protected function getFormattedMapData(Pathfinder\MapModel $map) : ?array {
+ protected function getFormattedMapData(Pathfinder\MapModel $map, bool $noCache = false) : ?array {
$data = null;
try{
- $mapData = $map->getData();
+ $mapData = $map->getData($noCache);
$data = [
'config' => $mapData->mapData,
'data' => [
diff --git a/app/main/controller/admin.php b/app/Controller/Admin.php
similarity index 97%
rename from app/main/controller/admin.php
rename to app/Controller/Admin.php
index 7c9670df..b419daa5 100644
--- a/app/main/controller/admin.php
+++ b/app/Controller/Admin.php
@@ -6,15 +6,15 @@
* Time: 20:30
*/
-namespace Controller;
+namespace Exodus4D\Pathfinder\Controller;
-use Controller\Ccp\Sso;
-use lib\Config;
-use Model\Pathfinder\CharacterModel;
-use Model\Pathfinder\CorporationModel;
-use Model\Pathfinder\MapModel;
-use Model\Pathfinder\RoleModel;
+use Exodus4D\Pathfinder\Controller\Ccp\Sso;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel;
+use Exodus4D\Pathfinder\Model\Pathfinder\CorporationModel;
+use Exodus4D\Pathfinder\Model\Pathfinder\MapModel;
+use Exodus4D\Pathfinder\Model\Pathfinder\RoleModel;
class Admin extends Controller{
@@ -203,7 +203,7 @@ class Admin extends Controller{
// character has access to that corporation -> create/update/delete rights...
if($corporationRightsData = (array)$settings['rights']){
// get existing corp rights
- foreach($corporation->getRights(['addInactive' => true]) as $corporationRight){
+ foreach($corporation->getRights($corporation::RIGHTS, ['addInactive' => true]) as $corporationRight){
$corporationRightData = $corporationRightsData[$corporationRight->rightId->_id];
if(
$corporationRightData &&
diff --git a/app/main/controller/api/access.php b/app/Controller/Api/Access.php
similarity index 93%
rename from app/main/controller/api/access.php
rename to app/Controller/Api/Access.php
index 01ad9bc2..d1ca15f0 100644
--- a/app/main/controller/api/access.php
+++ b/app/Controller/Api/Access.php
@@ -6,10 +6,10 @@
* Time: 17:42
*/
-namespace Controller\Api;
+namespace Exodus4D\Pathfinder\Controller\Api;
-use Controller;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class Access extends Controller\AccessController {
diff --git a/app/main/controller/api/github.php b/app/Controller/Api/GitHub.php
similarity index 85%
rename from app/main/controller/api/github.php
rename to app/Controller/Api/GitHub.php
index 71354a4d..9f3c8c22 100644
--- a/app/main/controller/api/github.php
+++ b/app/Controller/Api/GitHub.php
@@ -7,12 +7,11 @@
* Time: 03:34
*/
-namespace Controller\Api;
+namespace Exodus4D\Pathfinder\Controller\Api;
-use lib\Config;
-use Controller;
-
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Controller;
/**
* Github controller
@@ -36,9 +35,7 @@ class GitHub extends Controller\Controller {
$return->version->delta = null;
$return->version->dev = false;
- $md = \Markdown::instance();
-
- $releases = $f3->gitHubClient()->getProjectReleases('exodus4d/pathfinder', $releaseCount);
+ $releases = $f3->gitHubClient()->send('getProjectReleases', 'exodus4d/pathfinder', $releaseCount);
foreach($releases as $key => &$release){
// check version ------------------------------------------------------------------------------------------
@@ -70,12 +67,12 @@ class GitHub extends Controller\Controller {
// convert Markdown to HTML -> use either gitHub API (in oder to create abs, issue links)
// -> or F3´s markdown as fallback
- $html = $f3->gitHubClient()->markdownToHtml('exodus4d/pathfinder', $body);
+ $html = $f3->gitHubClient()->send('markdownToHtml', 'exodus4d/pathfinder', $body);
if(!empty($html)){
$body = $html;
}else{
- $body = $md->convert(trim($body));
+ $body = \Markdown::instance()->convert(trim($body));
}
$release['body'] = $body;
diff --git a/app/main/controller/api/map.php b/app/Controller/Api/Map.php
similarity index 80%
rename from app/main/controller/api/map.php
rename to app/Controller/Api/Map.php
index 1fa570a2..14611fcf 100644
--- a/app/main/controller/api/map.php
+++ b/app/Controller/Api/Map.php
@@ -6,15 +6,15 @@
* Time: 20:23
*/
-namespace Controller\Api;
+namespace Exodus4D\Pathfinder\Controller\Api;
-use Controller;
-use data\file\FileHandler;
-use lib\Config;
-use Model\AbstractModel;
-use Model\Pathfinder;
-use Model\Universe;
-use Exception;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Data\File\FileHandler;
+use Exodus4D\Pathfinder\Model\AbstractModel;
+use Exodus4D\Pathfinder\Model\Pathfinder;
+use Exodus4D\Pathfinder\Model\Universe;
+use Exodus4D\Pathfinder\Exception;
/**
* Map controller
@@ -49,7 +49,7 @@ class Map extends Controller\AccessController {
/**
* Get all required static config data for program initialization
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function initData(\Base $f3){
$validInitData = true;
@@ -170,7 +170,7 @@ class Map extends Controller\AccessController {
// get program routes -------------------------------------------------------------------------------------
$return->routes = [
- 'ssoLogin' => $this->getF3()->alias( 'sso', ['action' => 'requestAuthorization'] )
+ 'ssoLogin' => $this->getF3()->alias('sso', ['action' => 'requestAuthorization'])
];
// get third party APIs -----------------------------------------------------------------------------------
@@ -179,7 +179,13 @@ class Map extends Controller\AccessController {
'zKillboard' => Config::getPathfinderData('api.z_killboard'),
'eveeye' => Config::getPathfinderData('api.eveeye'),
'dotlan' => Config::getPathfinderData('api.dotlan'),
- 'anoik' => Config::getPathfinderData('api.anoik')
+ 'anoik' => Config::getPathfinderData('api.anoik'),
+ 'eveScout' => Config::getPathfinderData('api.eve_scout')
+ ];
+
+ // get Plugin config --------------------------------------------------------------------------------------
+ $return->plugin = [
+ 'modules' => Config::getPluginConfig('modules')
];
// Character default config -------------------------------------------------------------------------------
@@ -254,11 +260,11 @@ class Map extends Controller\AccessController {
// get SSO error messages that should be shown immediately ----------------------------------------------------
// -> e.g. errors while character switch from previous HTTP requests
- if($f3->exists(Controller\Ccp\Sso::SESSION_KEY_SSO_ERROR, $message)){
+ if($f3->exists(Controller\Ccp\Sso::SESSION_KEY_SSO_ERROR, $text)){
$ssoError = (object) [];
$ssoError->type = 'error';
$ssoError->title = 'Login failed';
- $ssoError->message = $message;
+ $ssoError->text = $text;
$return->error[] = $ssoError;
$f3->clear(Controller\Ccp\Sso::SESSION_KEY_SSO_ERROR);
}elseif($validInitData){
@@ -272,7 +278,7 @@ class Map extends Controller\AccessController {
/**
* import new map data
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function import(\Base $f3){
$importData = (array)$f3->get('POST');
@@ -386,7 +392,7 @@ class Map extends Controller\AccessController {
}else{
$maxSystemsError = (object) [];
$maxSystemsError->type = 'error';
- $maxSystemsError->message = 'Map has to many systems (' . $systemCount . ').'
+ $maxSystemsError->text = 'Map has to many systems (' . $systemCount . ').'
.' Max system count is ' . $defaultConfig['max_systems'] . ' for ' . $mapType->name . ' maps.';
$return->error[] = $maxSystemsError;
}
@@ -394,20 +400,20 @@ class Map extends Controller\AccessController {
// systems || connections missing
$missingConfigError = (object) [];
$missingConfigError->type = 'error';
- $missingConfigError->message = 'Map data not valid (systems || connections) missing';
+ $missingConfigError->text = 'Map data not valid (systems || connections) missing';
$return->error[] = $missingConfigError;
}
}else{
$unknownMapScope= (object) [];
$unknownMapScope->type = 'error';
- $unknownMapScope->message = 'Map scope unknown!';
+ $unknownMapScope->text = 'Map scope unknown!';
$return->error[] = $unknownMapScope;
}
}else{
// map config || systems/connections missing
$missingConfigError = (object) [];
$missingConfigError->type = 'error';
- $missingConfigError->message = 'Map data not valid (config || data) missing';
+ $missingConfigError->text = 'Map data not valid (config || data) missing';
$return->error[] = $missingConfigError;
}
@@ -416,250 +422,31 @@ class Map extends Controller\AccessController {
}else{
$unknownMapType = (object) [];
$unknownMapType->type = 'error';
- $unknownMapType->message = 'Map type unknown!';
+ $unknownMapType->text = 'Map type unknown!';
$return->error[] = $unknownMapType;
}
}else{
// map data missing
$missingDataError = (object) [];
$missingDataError->type = 'error';
- $missingDataError->message = 'Map data missing';
+ $missingDataError->text = 'Map data missing';
$return->error[] = $missingDataError;
}
echo json_encode($return);
}
- /**
- * save a new map or update an existing map
- * @param \Base $f3
- * @throws Exception
- */
- public function save(\Base $f3){
- $formData = (array)$f3->get('POST.formData');
-
- $return = (object) [];
- $return->error = [];
-
- if( isset($formData['id']) ){
- $activeCharacter = $this->getCharacter();
-
- /**
- * @var $map Pathfinder\MapModel
- */
- $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel');
- $map->getById( (int)$formData['id'] );
-
- if(
- $map->dry() ||
- $map->hasAccess($activeCharacter)
- ){
- try{
- // new map
- $map->setData($formData);
- $map = $map->save($activeCharacter);
-
- $mapDefaultConf = Config::getMapsDefaultConfig();
-
- // save global map access. Depends on map "type"
- if($map->isPrivate()){
-
- // share map between characters -> set access
- if(isset($formData['mapCharacters'])){
- // remove character (re-add later)
- $accessCharacters = array_diff($formData['mapCharacters'], [$activeCharacter->_id]);
-
- // avoid abuse -> respect share limits
- $maxShared = max($mapDefaultConf['private']['max_shared'] - 1, 0);
- $accessCharacters = array_slice($accessCharacters, 0, $maxShared);
-
- // clear map access. In case something has removed from access list
- $map->clearAccess();
-
- if($accessCharacters){
- /**
- * @var $tempCharacter Pathfinder\CharacterModel
- */
- $tempCharacter = Pathfinder\AbstractPathfinderModel::getNew('CharacterModel');
-
- foreach($accessCharacters as $characterId){
- $tempCharacter->getById( (int)$characterId );
-
- if(
- !$tempCharacter->dry() &&
- $tempCharacter->shared == 1 // check if map shared is enabled
- ){
- $map->setAccess($tempCharacter);
- }
-
- $tempCharacter->reset();
- }
- }
- }
-
- // the current character itself should always have access
- // just in case he removed himself :)
- $map->setAccess($activeCharacter);
- }elseif($map->isCorporation()){
- $corporation = $activeCharacter->getCorporation();
-
- if($corporation){
- // the current user has to have a corporation when
- // working on corporation maps!
-
- // share map between corporations -> set access
- if(isset($formData['mapCorporations'])){
- // remove character corporation (re-add later)
- $accessCorporations = array_diff($formData['mapCorporations'], [$corporation->_id]);
-
- // avoid abuse -> respect share limits
- $maxShared = max($mapDefaultConf['corporation']['max_shared'] - 1, 0);
- $accessCorporations = array_slice($accessCorporations, 0, $maxShared);
-
- // clear map access. In case something has removed from access list
- $map->clearAccess();
-
- if($accessCorporations){
- /**
- * @var $tempCorporation Pathfinder\CorporationModel
- */
- $tempCorporation = Pathfinder\AbstractPathfinderModel::getNew('CorporationModel');
-
- foreach($accessCorporations as $corporationId){
- $tempCorporation->getById( (int)$corporationId );
-
- if(
- !$tempCorporation->dry() &&
- $tempCorporation->shared == 1 // check if map shared is enabled
- ){
- $map->setAccess($tempCorporation);
- }
-
- $tempCorporation->reset();
- }
- }
- }
-
- // the corporation of the current user should always have access
- $map->setAccess($corporation);
- }
- }elseif($map->isAlliance()){
- $alliance = $activeCharacter->getAlliance();
-
- if($alliance){
- // the current user has to have a alliance when
- // working on alliance maps!
-
- // share map between alliances -> set access
- if(isset($formData['mapAlliances'])){
- // remove character alliance (re-add later)
- $accessAlliances = array_diff($formData['mapAlliances'], [$alliance->_id]);
-
- // avoid abuse -> respect share limits
- $maxShared = max($mapDefaultConf['alliance']['max_shared'] - 1, 0);
- $accessAlliances = array_slice($accessAlliances, 0, $maxShared);
-
- // clear map access. In case something has removed from access list
- $map->clearAccess();
-
- if($accessAlliances){
- /**
- * @var $tempAlliance Pathfinder\AllianceModel
- */
- $tempAlliance = Pathfinder\AbstractPathfinderModel::getNew('AllianceModel');
-
- foreach($accessAlliances as $allianceId){
- $tempAlliance->getById( (int)$allianceId );
-
- if(
- !$tempAlliance->dry() &&
- $tempAlliance->shared == 1 // check if map shared is enabled
- ){
- $map->setAccess($tempAlliance);
- }
-
- $tempAlliance->reset();
- }
- }
- }
-
- // the alliance of the current user should always have access
- $map->setAccess($alliance);
- }
- }
- // reload the same map model (refresh)
- // this makes sure all data is up2date
- $map->getById($map->_id, 0);
-
- // broadcast map Access -> and send map Data
- $this->broadcastMapAccess($map);
-
- $return->mapData = $map->getData();
- }catch(Exception\ValidationException $e){
- $return->error[] = $e->getError();
- }
- }else{
- // map access denied
- $captchaError = (object) [];
- $captchaError->type = 'error';
- $captchaError->message = 'Access denied';
- $return->error[] = $captchaError;
- }
- }else{
- // map id field missing
- $idError = (object) [];
- $idError->type = 'error';
- $idError->message = 'Map id missing';
- $return->error[] = $idError;
- }
-
- echo json_encode($return);
- }
-
- /**
- * delete a map and all dependencies
- * @param \Base $f3
- * @throws Exception
- */
- public function delete(\Base $f3){
- $mapData = (array)$f3->get('POST.mapData');
- $mapId = (int)$mapData['id'];
- $return = (object) [];
- $return->deletedMapIds = [];
-
- if($mapId){
- $activeCharacter = $this->getCharacter();
-
- /**
- * @var $map Pathfinder\MapModel
- */
- $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel');
- $map->getById($mapId);
-
- if($map->hasAccess($activeCharacter)){
- $map->setActive(false);
- $map->save($activeCharacter);
- $return->deletedMapIds[] = $mapId;
-
- // broadcast map delete
- $this->broadcastMapDeleted($mapId);
- }
- }
-
- echo json_encode($return);
- }
-
/**
* broadcast characters with map access rights to WebSocket server
* -> if characters with map access found -> broadcast mapData to them
* @param Pathfinder\MapModel $map
- * @throws Exception
+ * @throws \Exception
*/
protected function broadcastMapAccess(Pathfinder\MapModel $map){
$mapAccess = [
'id' => $map->_id,
'name' => $map->name,
- 'characterIds' => array_map(function ($data){
+ 'characterIds' => array_map(function($data){
return $data->id;
}, $map->getCharactersData())
];
@@ -667,22 +454,14 @@ class Map extends Controller\AccessController {
$this->getF3()->webSocket()->write('mapAccess', $mapAccess);
// map has (probably) active connections that should receive map Data
- $this->broadcastMap($map);
- }
-
- /**
- * broadcast map delete information to clients
- * @param int $mapId
- */
- protected function broadcastMapDeleted(int $mapId){
- $this->getF3()->webSocket()->write('mapDeleted', $mapId);
+ $this->broadcastMap($map, true);
}
/**
* get map access tokens for current character
* -> send access tokens via TCP Socket for WebSocket auth
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function getAccessData(\Base $f3){
$return = (object) [];
@@ -827,7 +606,7 @@ class Map extends Controller\AccessController {
* update map data
* -> function is called continuously (trigger) by any active client
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function updateData(\Base $f3){
$postData = (array)$f3->get('POST');
@@ -851,7 +630,7 @@ class Map extends Controller\AccessController {
* onUnload map sync
* @see https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function updateUnloadData(\Base $f3){
$postData = (array)$f3->get('POST');
@@ -870,7 +649,7 @@ class Map extends Controller\AccessController {
* update map data api
* -> function is called continuously by any active client
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function updateUserData(\Base $f3){
$postData = (array)$f3->get('POST');
@@ -941,7 +720,7 @@ class Map extends Controller\AccessController {
* @param Pathfinder\CharacterModel $character
* @param array $newSystemPositions
* @return Pathfinder\MapModel
- * @throws Exception
+ * @throws \Exception
*/
protected function updateMapByCharacter(Pathfinder\MapModel $map, Pathfinder\CharacterModel $character, array $newSystemPositions = []) : Pathfinder\MapModel {
// map changed. update cache (system/connection) changed
@@ -1065,7 +844,7 @@ class Map extends Controller\AccessController {
){
// check distance between systems (in jumps)
// -> if > 1 it is !very likely! a wormhole
- $route = (new Route())->searchRoute($sourceSystem->systemId, $targetSystem->systemId, 1);
+ $route = (new Controller\Api\Rest\Route())->searchRoute($sourceSystem->systemId, $targetSystem->systemId, 1);
if(!$route['routePossible']){
$addSourceSystem = true;
@@ -1165,7 +944,7 @@ class Map extends Controller\AccessController {
// .. now we need to check jump distance between systems
// -> if > 1 it is !very likely! podded jump
if(empty($route)){
- $route = (new Route())->searchRoute($sourceSystem->systemId, $targetSystem->systemId, 1);
+ $route = (new Controller\Api\Rest\Route())->searchRoute($sourceSystem->systemId, $targetSystem->systemId, 1);
}
if(!$route['routePossible']){
@@ -1207,7 +986,7 @@ class Map extends Controller\AccessController {
/**
* get connectionData
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function getConnectionData(\Base $f3){
$postData = (array)$f3->get('POST');
@@ -1258,7 +1037,7 @@ class Map extends Controller\AccessController {
/**
* get map log data
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function getLogData(\Base $f3){
$postData = (array)$f3->get('POST');
diff --git a/app/main/controller/api/rest/abstractrestcontroller.php b/app/Controller/Api/Rest/AbstractRestController.php
similarity index 93%
rename from app/main/controller/api/rest/abstractrestcontroller.php
rename to app/Controller/Api/Rest/AbstractRestController.php
index 1d0debea..5bf26d22 100644
--- a/app/main/controller/api/rest/abstractrestcontroller.php
+++ b/app/Controller/Api/Rest/AbstractRestController.php
@@ -6,9 +6,9 @@
* Time: 16:14
*/
-namespace Controller\Api\Rest;
+namespace Exodus4D\Pathfinder\Controller\Api\Rest;
-use Controller;
+use Exodus4D\Pathfinder\Controller;
abstract class AbstractRestController extends Controller\AccessController {
diff --git a/app/main/controller/api/rest/connection.php b/app/Controller/Api/Rest/Connection.php
similarity index 60%
rename from app/main/controller/api/rest/connection.php
rename to app/Controller/Api/Rest/Connection.php
index 9c24bfb3..3b430aaf 100644
--- a/app/main/controller/api/rest/connection.php
+++ b/app/Controller/Api/Rest/Connection.php
@@ -6,12 +6,58 @@
* Time: 12:10
*/
-namespace Controller\Api\Rest;
+namespace Exodus4D\Pathfinder\Controller\Api\Rest;
-use Model\Pathfinder;
+
+use Exodus4D\Pathfinder\Model\Pathfinder;
class Connection extends AbstractRestController {
+ /**
+ * @param \Base $f3
+ * @param $params
+ * @throws \Exception
+ */
+ public function get(\Base $f3, $params){
+ $requestData = $this->getRequestData($f3);
+ $connectionIds = array_map('intval', explode(',', (string)$params['id']));
+ $addData = (array)$requestData['addData'];
+ $filterData = (array)$requestData['filterData'];
+ $connectionData = [];
+
+ if($mapId = (int)$requestData['mapId']){
+ $activeCharacter = $this->getCharacter();
+
+ /**
+ * @var $map Pathfinder\MapModel
+ */
+ $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel');
+ $map->getById($mapId);
+
+ if($map->hasAccess($activeCharacter)){
+ $connections = $map->getConnections($connectionIds, 'wh');
+ foreach($connections as $connection){
+ $check = true;
+ $data = $connection->getData(in_array('signatures', $addData), in_array('logs', $addData));
+ // filter result
+ if(in_array('signatures', $filterData) && !$data->signatures){
+ $check = false;
+ }
+
+ if(in_array('logs', $filterData) && !$data->logs){
+ $check = false;
+ }
+
+ if($check){
+ $connectionData[] = $data;
+ }
+ }
+ }
+ }
+
+ $this->out($connectionData);
+ }
+
/**
* save a new connection or updates an existing (drag/drop) between two systems
* if a connection is changed (drag&drop) to another system. -> this function is called for update
@@ -47,10 +93,16 @@ class Connection extends AbstractRestController {
$connection->mapId = $map;
$connection->source = $source;
$connection->target = $target;
- $connection->copyfrom($connectionData, ['scope', 'type']);
- // change the default type for the new connection
- $connection->setDefaultTypeData();
+ // if scope + type data send -> use them ...
+ if($requestData['scope'] && !empty($requestData['type'])){
+ $connection->copyfrom($requestData, ['scope', 'type']);
+ }
+
+ // ... set/change default scope + type
+ if(!$requestData['disableAutoScope']){
+ $connection->setAutoScopeAndType();
+ }
if($connection->save($activeCharacter)){
$connectionData = $connection->getData();
diff --git a/app/main/controller/api/rest/log.php b/app/Controller/Api/Rest/Log.php
similarity index 96%
rename from app/main/controller/api/rest/log.php
rename to app/Controller/Api/Rest/Log.php
index 8b872f0c..9696ce00 100644
--- a/app/main/controller/api/rest/log.php
+++ b/app/Controller/Api/Rest/Log.php
@@ -6,9 +6,10 @@
* Time: 15:28
*/
-namespace Controller\Api\Rest;
+namespace Exodus4D\Pathfinder\Controller\Api\Rest;
-use Model\Pathfinder;
+
+use Exodus4D\Pathfinder\Model\Pathfinder;
class Log extends AbstractRestController {
diff --git a/app/Controller/Api/Rest/Map.php b/app/Controller/Api/Rest/Map.php
new file mode 100644
index 00000000..05c64cc7
--- /dev/null
+++ b/app/Controller/Api/Rest/Map.php
@@ -0,0 +1,239 @@
+getRequestData($f3);
+
+ /**
+ * @var $map Pathfinder\MapModel
+ */
+ $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel');
+ $mapData = $this->update($map, $requestData)->getData();
+
+ $this->out($mapData);
+ }
+
+ /**
+ * @param \Base $f3
+ * @param $params
+ * @throws \Exception
+ */
+ public function patch(\Base $f3, $params){
+ $requestData = $this->getRequestData($f3);
+ $mapData = [];
+
+ if($mapId = (int)$params['id']){
+ $activeCharacter = $this->getCharacter();
+
+ /**
+ * @var $map Pathfinder\MapModel
+ */
+ $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel');
+ $map->getById($mapId);
+ if($map->hasAccess($activeCharacter)){
+ $mapData = $this->update($map, $requestData)->getData(true);
+ }
+ }
+
+ $this->out($mapData);
+ }
+
+ /**
+ * @param \Base $f3
+ * @param $params
+ * @throws \Exception
+ */
+ public function delete(\Base $f3, $params){
+ $deletedMapIds = [];
+
+ if($mapId = (int)$params['id']){
+ $activeCharacter = $this->getCharacter();
+
+ /**
+ * @var $map Pathfinder\MapModel
+ */
+ $map = Pathfinder\AbstractPathfinderModel::getNew('MapModel');
+ $map->getById($mapId);
+
+ if($map->hasAccess($activeCharacter)){
+ // check if character has delete right for map type
+ $hasRight = true;
+ if($map->isCorporation()){
+ if($corpRight = $activeCharacter->getCorporation()->getRights(['map_delete'])){
+ if($corpRight[0]->get('roleId', true) !== $activeCharacter->get('roleId', true)){
+ $hasRight = false;
+ }
+ }
+ }
+
+ if($hasRight){
+ $map->setActive(false);
+ $map->save($activeCharacter);
+ $deletedMapIds[] = $mapId;
+ // broadcast map delete
+ $this->broadcastMapDeleted($mapId);
+ }else{
+ $f3->set('HALT', true);
+ $f3->error(401, sprintf(self::ERROR_MAP_DELETE, $activeCharacter->name));
+ }
+ }
+ }
+
+ $this->out($deletedMapIds);
+ }
+
+ /**
+ * @param Pathfinder\MapModel $map
+ * @param array $mapData
+ * @return Pathfinder\MapModel
+ * @throws \Exception
+ */
+ private function update(Pathfinder\MapModel $map, array $mapData) : Pathfinder\MapModel {
+ $activeCharacter = $this->getCharacter();
+
+ $map->setData($mapData);
+ $typeChange = $map->changed('typeId');
+ $map->save($activeCharacter);
+
+ // save global map access. Depends on map "type" --------------------------------------------------------------
+ /**
+ * @param Pathfinder\AbstractPathfinderModel $primaryModel
+ * @param array|null $modelIds
+ * @param int $maxShared
+ * @return int
+ */
+ $setMapAccess = function(Pathfinder\AbstractPathfinderModel &$primaryModel, ?array $modelIds = [], int $maxShared = 3) use (&$map) : int {
+ $added = 0;
+ $deleted = 0;
+ if(is_array($modelIds)){
+ // remove primaryModel id (-> re-add later)
+ $modelIds = array_diff(array_map('intval', $modelIds), [$primaryModel->_id]);
+
+ // avoid abuse -> respect share limits (-1 is because the primaryModel has also access)
+ $modelIds = array_slice($modelIds, 0, max($maxShared - 1, 0));
+
+ // add the primaryModel id back (again)
+ $modelIds[] = $primaryModel->_id;
+
+ // clear map access for entities that do not match the map "mapType"
+ $deleted += $map->clearAccessByType();
+
+ $compare = $map->compareAccess($modelIds);
+
+ foreach((array)$compare['old'] as $modelId) {
+ $deleted += $map->removeFromAccess($modelId);
+ }
+
+ $modelClass = (new \ReflectionClass($primaryModel))->getShortName();
+ $tempModel = Pathfinder\AbstractPathfinderModel::getNew($modelClass);
+ foreach((array)$compare['new'] as $modelId) {
+ $tempModel->getById($modelId);
+ if(
+ $tempModel->valid() &&
+ (
+ $modelId == $primaryModel->_id || // primary model has always access (regardless of "shared" value)
+ $tempModel->shared == 1 // check if map shared is enabled
+ )
+ ){
+ $added += (int)$map->setAccess($tempModel);
+ }
+
+ $tempModel->reset();
+ }
+ }
+ return $added + $deleted;
+ };
+
+ $accessChangeCount = 0;
+ $mapDefaultConf = Config::getMapsDefaultConfig();
+ if($map->isPrivate()){
+ $accessChangeCount = $setMapAccess(
+ $activeCharacter,
+ $typeChange ? [$activeCharacter->_id] : $mapData['mapCharacters'],
+ (int)$mapDefaultConf['private']['max_shared']
+ );
+ }elseif($map->isCorporation()){
+ if($corporation = $activeCharacter->getCorporation()){
+ $accessChangeCount = $setMapAccess(
+ $corporation,
+ $typeChange ? [$corporation->_id] : $mapData['mapCorporations'],
+ (int)$mapDefaultConf['corporation']['max_shared']
+ );
+ }
+ }elseif($map->isAlliance()){
+ if($alliance = $activeCharacter->getAlliance()){
+ $accessChangeCount = $setMapAccess(
+ $alliance,
+ $typeChange ? [$alliance->_id] : $mapData['mapAlliances'],
+ (int)$mapDefaultConf['alliance']['max_shared']
+ );
+ }
+ }
+
+ if($accessChangeCount){
+ $map->touch('updated');
+ $map->save($activeCharacter);
+ }
+
+ // reload the same map model (refresh)
+ // this makes sure all data is up2date
+ $map->getById($map->_id, 0);
+
+ // broadcast map Access -> and send map Data
+ $this->broadcastMapAccess($map);
+
+ return $map;
+ }
+
+ /**
+ * broadcast characters with map access rights to WebSocket server
+ * -> if characters with map access found -> broadcast mapData to them
+ * @param Pathfinder\MapModel $map
+ * @throws \Exception
+ */
+ protected function broadcastMapAccess(Pathfinder\MapModel $map){
+ $mapAccess = [
+ 'id' => $map->_id,
+ 'name' => $map->name,
+ 'characterIds' => array_map(function($data){
+ return $data->id;
+ }, $map->getCharactersData())
+ ];
+
+ $this->getF3()->webSocket()->write('mapAccess', $mapAccess);
+
+ // map has (probably) active connections that should receive map Data
+ $this->broadcastMap($map, true);
+ }
+
+ /**
+ * broadcast map delete information to clients
+ * @param int $mapId
+ */
+ private function broadcastMapDeleted(int $mapId){
+ $this->getF3()->webSocket()->write('mapDeleted', $mapId);
+ }
+}
\ No newline at end of file
diff --git a/app/main/controller/api/route.php b/app/Controller/Api/Rest/Route.php
similarity index 85%
rename from app/main/controller/api/route.php
rename to app/Controller/Api/Rest/Route.php
index a19fe354..af7998a4 100644
--- a/app/main/controller/api/route.php
+++ b/app/Controller/Api/Rest/Route.php
@@ -1,24 +1,20 @@
getSystemData($row[$systemSourceKey]))
){
$jumpData[$row[$systemSourceKey]] = [
- 'systemId' => (int)$row[$systemSourceKey],
- 'systemName' => $staticData->name,
- 'constellationId' => $staticData->constellation->id,
- 'regionId' => $staticData->constellation->region->id,
- 'trueSec' => $staticData->trueSec,
+ 'systemId' => (int)$row[$systemSourceKey],
+ 'systemName' => $staticData->name,
+ 'constellationId' => $staticData->constellation->id,
+ 'regionId' => $staticData->constellation->region->id,
+ 'trueSec' => $staticData->trueSec,
];
}
@@ -247,20 +249,70 @@ class Route extends Controller\AccessController {
$enrichJumpData($rows[$i], 'systemTargetId', 'systemSourceId');
}
- // update jump data for this instance
$this->updateJumpData($jumpData);
}
}
}
}
+ /**
+ * set current Thera connections jump data for this instance
+ * -> Connected wormholes pulled from eve-scout.com
+ */
+ private function setTheraJumpData(){
+ if(!$this->getF3()->exists(self::CACHE_KEY_THERA_JUMP_DATA, $jumpData)){
+ $jumpData = [];
+ $connectionsData = $this->getF3()->eveScoutClient()->send('getTheraConnections');
+
+ if(!empty($connectionsData) && !isset($connectionsData['error'])){
+ /**
+ * map Thera jump data to Pathfinder format
+ * @param array $row
+ * @param string $systemSourceKey
+ * @param string $systemTargetKey
+ */
+ $enrichJumpData = function(array &$row, string $systemSourceKey, string $systemTargetKey) use (&$jumpData) {
+ // check if response data is valid
+ if(
+ is_object($systemSource = $row[$systemSourceKey]) && !empty((array)$systemSource) &&
+ is_object($systemTarget = $row[$systemTargetKey]) && !empty((array)$systemTarget)
+ ){
+ if(!array_key_exists($systemSource->id, $jumpData)){
+ $jumpData[$systemSource->id] = [
+ 'systemId' => (int)$systemSource->id,
+ 'systemName' => $systemSource->name,
+ 'constellationId' => (int)$systemSource->constellationID,
+ 'regionId' => (int)$systemSource->regionId,
+ 'trueSec' => $systemSource->security,
+ ];
+ }
+
+ if( !in_array((int)$systemTarget->id, (array)$jumpData[$systemSource->id]['jumpNodes']) ){
+ $jumpData[$systemSource->id]['jumpNodes'][] = (int)$systemTarget->id;
+ }
+ }
+ };
+
+ foreach((array)$connectionsData['connections'] as $connectionData){
+ $enrichJumpData($connectionData, 'source', 'target');
+ $enrichJumpData($connectionData, 'target', 'source');
+ }
+
+ if(!empty($jumpData)){
+ $this->getF3()->set(self::CACHE_KEY_THERA_JUMP_DATA, $jumpData, $this->theraJumpDataCacheTime);
+ }
+ }
+ }
+
+ $this->updateJumpData($jumpData);
+ }
+
/**
* update jump data for this instance
* -> data is either coming from CCPs [SDE] OR from map specific data
* @param array $rows
*/
private function updateJumpData(&$rows = []){
-
foreach($rows as &$row){
$regionId = (int)$row['regionId'];
$constId = (int)$row['constellationId'];
@@ -285,7 +337,7 @@ class Route extends Controller\AccessController {
if( !is_array($this->jumpArray[$systemId]) ){
$this->jumpArray[$systemId] = [];
}
- $this->jumpArray[$systemId] = array_merge($row['jumpNodes'], $this->jumpArray[$systemId]);
+ $this->jumpArray[$systemId] = array_merge((array)$row['jumpNodes'], $this->jumpArray[$systemId]);
// add systemName to end (if not already there)
if(end($this->jumpArray[$systemId]) != $systemName){
@@ -448,7 +500,7 @@ class Route extends Controller\AccessController {
// Endpoint return http:404 in case no route find (e.g. from inside a wh)
// we thread that error "no route found" as a valid response! -> no fallback to custom search
- if( !empty($routeData['error']) && strtolower($routeData['error']) !== 'no route found' ){
+ if(!empty($routeData['error']) && strtolower($routeData['error']) !== 'no route found'){
// ESI route search has errors -> fallback to custom search implementation
$routeData = $this->searchRouteCustom($systemFromId, $systemToId, $searchDepth, $mapIds, $filterData);
}
@@ -484,6 +536,11 @@ class Route extends Controller\AccessController {
// add map specific data
$this->setDynamicJumpData($mapIds, $filterData);
+ // add current Thera connections data
+ if($filterData['wormholesThera']){
+ $this->setTheraJumpData();
+ }
+
// filter jump data (e.g. remove some systems (0.0, LS)
// --> don´t filter some systems (e.g. systemFrom, systemTo) even if they are are WH,LS,0.0
$this->filterJumpData($filterData, [$systemFromId, $systemToId]);
@@ -494,10 +551,10 @@ class Route extends Controller\AccessController {
$jumpNum = 0;
$depthSearched = 0;
- if( isset($this->jumpArray[$systemFromId]) ){
+ if(isset($this->jumpArray[$systemFromId])){
// check if the system we are looking for is a direct neighbour
- foreach( $this->jumpArray[$systemFromId] as $n ) {
- if ($n == $systemToId) {
+ foreach($this->jumpArray[$systemFromId] as $n){
+ if($n == $systemToId){
$jumpNum = 2;
$routeData['route'][] = $this->getJumpNodeData($n);
break;
@@ -505,23 +562,23 @@ class Route extends Controller\AccessController {
}
// system is not a direct neighbour -> search recursive its neighbours
- if ($jumpNum == 0) {
+ if($jumpNum == 0){
$searchResult = $this->graph_find_path( $this->jumpArray, $systemFromId, $systemToId, $searchDepth );
$depthSearched = $searchResult['depth'];
- foreach( $searchResult['path'] as $systemId ) {
- if ($jumpNum > 0) {
+ foreach($searchResult['path'] as $systemId){
+ if($jumpNum > 0){
$routeData['route'][] = $this->getJumpNodeData($systemId);
}
$jumpNum++;
}
}
- if ($jumpNum > 0) {
+ if($jumpNum > 0){
// route found
$routeData['routePossible'] = true;
// insert "from" system on top
array_unshift($routeData['route'], $this->getJumpNodeData($systemFromId));
- } else {
+ }else{
// route not found
$routeData['routePossible'] = false;
}
@@ -566,6 +623,11 @@ class Route extends Controller\AccessController {
// add map specific data
$this->setDynamicJumpData($mapIds, $filterData);
+ // add current Thera connections data
+ if($filterData['wormholesThera']){
+ $this->setTheraJumpData();
+ }
+
// filter jump data (e.g. remove some systems (0.0, LS)
// --> don´t filter some systems (e.g. systemFrom, systemTo) even if they are are WH,LS,0.0
$this->filterJumpData($filterData, [$systemFromId, $systemToId]);
@@ -576,7 +638,7 @@ class Route extends Controller\AccessController {
if($count > 1){
// ... should always > 1
// loop all connections for current source system
- foreach($jumpData as $systemTargetId) {
+ foreach($jumpData as $systemTargetId){
// skip last entry
if(--$count <= 0){
break;
@@ -606,7 +668,7 @@ class Route extends Controller\AccessController {
'connections' => $connections
];
- $result = $this->getF3()->ccpClient()->getRouteData($systemFromId, $systemToId, $options);
+ $result = $this->getF3()->ccpClient()->send('getRoute', $systemFromId, $systemToId, $options);
// format result ------------------------------------------------------------------------------------------
@@ -660,9 +722,7 @@ class Route extends Controller\AccessController {
];
$keyParts += $filterData;
- $key = 'route_' . hash('md5', implode('_', $keyParts));
-
- return $key;
+ return 'route_' . hash('md5', implode('_', $keyParts));
}
/**
@@ -670,8 +730,8 @@ class Route extends Controller\AccessController {
* @param \Base $f3
* @throws \Exception
*/
- public function search($f3){
- $requestData = (array)$f3->get('POST');
+ public function post(\Base $f3){
+ $requestData = $this->getRequestData($f3);
$activeCharacter = $this->getCharacter();
@@ -736,6 +796,7 @@ class Route extends Controller\AccessController {
'wormholesReduced' => (bool) $routeData['wormholesReduced'],
'wormholesCritical' => (bool) $routeData['wormholesCritical'],
'wormholesEOL' => (bool) $routeData['wormholesEOL'],
+ 'wormholesThera' => (bool) $routeData['wormholesThera'],
'wormholesSizeMin' => (string) $routeData['wormholesSizeMin'],
'excludeTypes' => (array) $routeData['excludeTypes'],
'endpointsBubble' => (bool) $routeData['endpointsBubble'],
@@ -791,21 +852,6 @@ class Route extends Controller\AccessController {
}
}
- echo json_encode($return);
+ $this->out($return);
}
-
-
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
+}
\ No newline at end of file
diff --git a/app/main/controller/api/rest/signature.php b/app/Controller/Api/Rest/Signature.php
similarity index 98%
rename from app/main/controller/api/rest/signature.php
rename to app/Controller/Api/Rest/Signature.php
index 92a0db71..e928d9c0 100644
--- a/app/main/controller/api/rest/signature.php
+++ b/app/Controller/Api/Rest/Signature.php
@@ -6,10 +6,10 @@
* Time: 16:20
*/
-namespace Controller\Api\Rest;
+namespace Exodus4D\Pathfinder\Controller\Api\Rest;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class Signature extends AbstractRestController {
diff --git a/app/main/controller/api/rest/signaturehistory.php b/app/Controller/Api/Rest/SignatureHistory.php
similarity index 97%
rename from app/main/controller/api/rest/signaturehistory.php
rename to app/Controller/Api/Rest/SignatureHistory.php
index f431687b..ffaf2de5 100644
--- a/app/main/controller/api/rest/signaturehistory.php
+++ b/app/Controller/Api/Rest/SignatureHistory.php
@@ -6,11 +6,11 @@
* Time: 16:44
*/
-namespace Controller\Api\Rest;
+namespace Exodus4D\Pathfinder\Controller\Api\Rest;
-use Model\Pathfinder;
-use lib\Config;
+use Exodus4D\Pathfinder\Model\Pathfinder;
+use Exodus4D\Pathfinder\Lib\Config;
class SignatureHistory extends AbstractRestController {
diff --git a/app/main/controller/api/rest/structure.php b/app/Controller/Api/Rest/Structure.php
similarity index 97%
rename from app/main/controller/api/rest/structure.php
rename to app/Controller/Api/Rest/Structure.php
index b100d77e..19ea8ecb 100644
--- a/app/main/controller/api/rest/structure.php
+++ b/app/Controller/Api/Rest/Structure.php
@@ -6,10 +6,10 @@
* Time: 23:29
*/
-namespace Controller\Api\Rest;
+namespace Exodus4D\Pathfinder\Controller\Api\Rest;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class Structure extends AbstractRestController {
diff --git a/app/main/controller/api/rest/system.php b/app/Controller/Api/Rest/System.php
similarity index 98%
rename from app/main/controller/api/rest/system.php
rename to app/Controller/Api/Rest/System.php
index 4a5983a8..efceae2d 100644
--- a/app/main/controller/api/rest/system.php
+++ b/app/Controller/Api/Rest/System.php
@@ -6,10 +6,10 @@
* Time: 12:34
*/
-namespace Controller\Api\Rest;
+namespace Exodus4D\Pathfinder\Controller\Api\Rest;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class System extends AbstractRestController {
diff --git a/app/main/controller/api/system.php b/app/Controller/Api/Rest/SystemGraph.php
similarity index 52%
rename from app/main/controller/api/system.php
rename to app/Controller/Api/Rest/SystemGraph.php
index bf87bfb9..b84a7905 100644
--- a/app/main/controller/api/system.php
+++ b/app/Controller/Api/Rest/SystemGraph.php
@@ -1,40 +1,28 @@
getRequestData($f3);
+ $systemIds = (array)$requestData['systemIds'];
$graphsData = [];
- $systemIds = (array)$f3->get('GET.systemIds');
// valid response (data found) should be cached by server + client
$cacheResponse = false;
@@ -108,84 +96,17 @@ class System extends Controller\AccessController {
$f3->expire(Config::ttlLeft($exists, $ttl));
}
- echo json_encode($graphsData);
+ $this->out($graphsData);
}
+ // ----------------------------------------------------------------------------------------------------------------
+
/**
- * set destination for system, station or structure
- * @param \Base $f3
- * @throws \Exception
+ * get system graph cache key
+ * @param int $systemId
+ * @return string
*/
- public function setDestination(\Base $f3){
- $postData = (array)$f3->get('POST');
-
- $return = (object) [];
- $return->error = [];
- $return->destData = [];
-
- if(!empty($destData = (array)$postData['destData'])){
- $activeCharacter = $this->getCharacter();
-
- $return->clearOtherWaypoints = (bool)$postData['clearOtherWaypoints'];
- $return->first = (bool)$postData['first'];
-
- if($accessToken = $activeCharacter->getAccessToken()){
- $options = [
- 'clearOtherWaypoints' => $return->clearOtherWaypoints,
- 'addToBeginning' => $return->first,
- ];
-
- foreach($destData as $data){
- $response = $f3->ccpClient()->setWaypoint((int)$data['id'], $accessToken, $options);
-
- if(empty($response)){
- $return->destData[] = $data;
- }else{
- $error = (object) [];
- $error->type = 'error';
- $error->message = $response['error'];
- $return->error[] = $error;
- }
- }
-
- }
- }
-
- echo json_encode($return);
+ protected function getSystemGraphCacheKey(int $systemId): string {
+ return sprintf(self::CACHE_KEY_GRAPH, 'SYSTEM_' . $systemId);
}
-
- /**
- * send Rally Point poke
- * @param \Base $f3
- * @throws \Exception
- */
- public function pokeRally(\Base $f3){
- $rallyData = (array)$f3->get('POST');
- $systemId = (int)$rallyData['systemId'];
- $return = (object) [];
-
- if($systemId){
- $activeCharacter = $this->getCharacter();
-
- /**
- * @var $system Pathfinder\SystemModel
- */
- $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel');
- $system->getById($systemId);
-
- if($system->hasAccess($activeCharacter)){
- $rallyData['pokeDesktop'] = $rallyData['pokeDesktop'] === '1';
- $rallyData['pokeMail'] = $rallyData['pokeMail'] === '1';
- $rallyData['pokeSlack'] = $rallyData['pokeSlack'] === '1';
- $rallyData['pokeDiscord'] = $rallyData['pokeDiscord'] === '1';
- $rallyData['message'] = trim($rallyData['message']);
-
- $system->sendRallyPoke($rallyData, $activeCharacter);
- }
- }
-
- echo json_encode($return);
- }
-
-}
-
+}
\ No newline at end of file
diff --git a/app/Controller/Api/Rest/SystemThera.php b/app/Controller/Api/Rest/SystemThera.php
new file mode 100644
index 00000000..d428ca8b
--- /dev/null
+++ b/app/Controller/Api/Rest/SystemThera.php
@@ -0,0 +1,131 @@
+exists(self::CACHE_KEY_THERA_CONNECTIONS, $connectionsData)){
+ $connectionsData = $this->getEveScoutTheraConnections();
+ $f3->set(self::CACHE_KEY_THERA_CONNECTIONS, $connectionsData, $ttl);
+ }
+
+ $f3->expire(Config::ttlLeft($exists, $ttl));
+
+ $this->out($connectionsData);
+ }
+
+ /**
+ * get Thera connections data from EveScout API
+ * -> map response to Pathfinder format
+ * @return array
+ */
+ protected function getEveScoutTheraConnections() : array {
+ $connectionsData = [];
+
+ /**
+ * map system data from eveScout response to Pathfinder´s 'system' format
+ * @param string $key
+ * @param array $eveScoutConnection
+ * @param array $connectionData
+ */
+ $enrichWithSystemData = function(string $key, array $eveScoutConnection, array &$connectionData) : void {
+ $eveScoutSystem = (array)$eveScoutConnection[$key];
+ $systemData = [
+ 'id' => (int)$eveScoutSystem['id'],
+ 'name' => (string)$eveScoutSystem['name'],
+ 'trueSec' => round((float)$eveScoutSystem['security'], 4)
+ ];
+ if(!empty($eveScoutSystem['constellationID'])){
+ $systemData['constellation'] = ['id' => (int)$eveScoutSystem['constellationID']];
+ }
+ if(!empty($region = (array)$eveScoutSystem['region']) && !empty($region['id'])){
+ $systemData['region'] = ['id' => (int)$region['id'], 'name' => (string)$region['name']];
+ }
+ $connectionData[$key] = $systemData;
+ };
+
+ /**
+ * @param string $key
+ * @param array $eveScoutConnection
+ * @param array $connectionData
+ */
+ $enrichWithSignatureData = function(string $key, array $eveScoutConnection, array &$connectionData) : void {
+ $eveScoutSignature = (array)$eveScoutConnection[$key];
+ $signatureData = [
+ 'name' => $eveScoutSignature['name'] ? : null
+ ];
+ if(!empty($sigType = (array)$eveScoutSignature['type']) && !empty($sigType['name'])){
+ $signatureData['type'] = ['name' => strtoupper((string)$sigType['name'])];
+ }
+ $connectionData[$key] = $signatureData;
+ };
+
+ /**
+ * map wormhole data from eveScout to Pathfinder´s connection format
+ * @param array $wormholeData
+ * @param array $connectionsData
+ */
+ $enrichWithWormholeData = function(array $wormholeData, array &$connectionsData) : void {
+ $type = [];
+ if($wormholeData['mass'] === 'reduced'){
+ $type[] = 'wh_reduced';
+ }else if($wormholeData['mass'] === 'critical'){
+ $type[] = 'wh_critical';
+ }else{
+ $type[] = 'wh_fresh';
+ }
+
+ if($wormholeData['eol'] === 'critical'){
+ $type[] = 'wh_eol';
+ }
+ $connectionsData['type'] = $type;
+ $connectionsData['estimatedEol'] = $wormholeData['estimatedEol'];
+ };
+
+ $eveScoutResponse = $this->getF3()->eveScoutClient()->send('getTheraConnections');
+ if(!empty($eveScoutResponse) && !isset($eveScoutResponse['error'])){
+ foreach((array)$eveScoutResponse['connections'] as $eveScoutConnection){
+ if(
+ $eveScoutConnection['type'] === 'wormhole' &&
+ isset($eveScoutConnection['source']) && isset($eveScoutConnection['target'])
+ ){
+ try{
+ $data = [
+ 'id' => (int)$eveScoutConnection['id'],
+ 'scope' => 'wh',
+ 'created' => [
+ 'created' => (new \DateTime($eveScoutConnection['created']))->getTimestamp(),
+ 'character' => (array)$eveScoutConnection['character']
+ ],
+ 'updated' => (new \DateTime($eveScoutConnection['updated']))->getTimestamp()
+ ];
+ $enrichWithWormholeData((array)$eveScoutConnection['wormhole'], $data);
+ $enrichWithSystemData('source', $eveScoutConnection, $data);
+ $enrichWithSystemData('target', $eveScoutConnection, $data);
+ $enrichWithSignatureData('sourceSignature', $eveScoutConnection, $data);
+ $enrichWithSignatureData('targetSignature', $eveScoutConnection, $data);
+ $connectionsData[] = $data;
+ }catch(\Exception $e){
+ // new \DateTime Exception -> skip this data
+ }
+ }
+ }
+ }
+
+ return $connectionsData;
+ }
+}
\ No newline at end of file
diff --git a/app/main/controller/api/setup.php b/app/Controller/Api/Setup.php
similarity index 97%
rename from app/main/controller/api/setup.php
rename to app/Controller/Api/Setup.php
index 8076a9cf..31f85c78 100644
--- a/app/main/controller/api/setup.php
+++ b/app/Controller/Api/Setup.php
@@ -6,12 +6,13 @@
* Time: 14:17
*/
-namespace Controller\Api;
+namespace Exodus4D\Pathfinder\Controller\Api;
-use Controller;
-use lib\Config;
-use lib\Cron;
-use Model;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Cron;
+use Exodus4D\Pathfinder\Lib\Format\Number;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Model;
class Setup extends Controller\Controller {
@@ -91,7 +92,7 @@ class Setup extends Controller\Controller {
],
'tplCounter' => $this->counter(),
'tplConvertBytes' => function(){
- return call_user_func_array([\lib\format\Number::instance(), 'bytesToString'], func_get_args());
+ return call_user_func_array([Number::instance(), 'bytesToString'], func_get_args());
}
];
return \Template::instance()->render('templates/ui/cron_table_row.html', null, $tplData, 0);
diff --git a/app/main/controller/api/statistic.php b/app/Controller/Api/Statistic.php
similarity index 98%
rename from app/main/controller/api/statistic.php
rename to app/Controller/Api/Statistic.php
index e8fed3b8..79688023 100644
--- a/app/main/controller/api/statistic.php
+++ b/app/Controller/Api/Statistic.php
@@ -6,11 +6,11 @@
* Time: 00:29
*/
-namespace controller\api;
+namespace Exodus4D\Pathfinder\Controller\Api;
-use Controller;
-use lib\Config;
-use Model\Pathfinder\CharacterModel;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel;
class Statistic extends Controller\AccessController {
diff --git a/app/Controller/Api/System.php b/app/Controller/Api/System.php
new file mode 100644
index 00000000..8368d1b5
--- /dev/null
+++ b/app/Controller/Api/System.php
@@ -0,0 +1,94 @@
+get('POST');
+
+ $return = (object) [];
+ $return->error = [];
+ $return->destData = [];
+
+ if(!empty($destData = (array)$postData['destData'])){
+ $activeCharacter = $this->getCharacter();
+
+ $return->clearOtherWaypoints = (bool)$postData['clearOtherWaypoints'];
+ $return->first = (bool)$postData['first'];
+
+ if($accessToken = $activeCharacter->getAccessToken()){
+ $options = [
+ 'clearOtherWaypoints' => $return->clearOtherWaypoints,
+ 'addToBeginning' => $return->first,
+ ];
+
+ foreach($destData as $data){
+ $response = $f3->ccpClient()->send('setWaypoint', (int)$data['id'], $accessToken, $options);
+
+ if(empty($response)){
+ $return->destData[] = $data;
+ }else{
+ $error = (object) [];
+ $error->type = 'error';
+ $error->text = $response['error'];
+ $return->error[] = $error;
+ }
+ }
+
+ }
+ }
+
+ echo json_encode($return);
+ }
+
+ /**
+ * send Rally Point poke
+ * @param \Base $f3
+ * @throws \Exception
+ */
+ public function pokeRally(\Base $f3){
+ $rallyData = (array)$f3->get('POST');
+ $systemId = (int)$rallyData['systemId'];
+ $return = (object) [];
+
+ if($systemId){
+ $activeCharacter = $this->getCharacter();
+
+ /**
+ * @var $system Pathfinder\SystemModel
+ */
+ $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel');
+ $system->getById($systemId);
+
+ if($system->hasAccess($activeCharacter)){
+ $rallyData['pokeDesktop'] = $rallyData['pokeDesktop'] === '1';
+ $rallyData['pokeMail'] = $rallyData['pokeMail'] === '1';
+ $rallyData['pokeSlack'] = $rallyData['pokeSlack'] === '1';
+ $rallyData['pokeDiscord'] = $rallyData['pokeDiscord'] === '1';
+ $rallyData['message'] = trim($rallyData['message']);
+
+ $system->sendRallyPoke($rallyData, $activeCharacter);
+ }
+ }
+
+ echo json_encode($return);
+ }
+
+}
+
diff --git a/app/main/controller/api/universe.php b/app/Controller/Api/Universe.php
similarity index 96%
rename from app/main/controller/api/universe.php
rename to app/Controller/Api/Universe.php
index 95156955..907cb62d 100644
--- a/app/main/controller/api/universe.php
+++ b/app/Controller/Api/Universe.php
@@ -6,11 +6,11 @@
* Time: 15:49
*/
-namespace Controller\Api;
+namespace Exodus4D\Pathfinder\Controller\Api;
-use Controller;
-use Controller\Ccp as Ccp;
-use Model;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Controller\Ccp as Ccp;
+use Exodus4D\Pathfinder\Model;
class Universe extends Controller\AccessController {
diff --git a/app/main/controller/api/user.php b/app/Controller/Api/User.php
similarity index 90%
rename from app/main/controller/api/user.php
rename to app/Controller/Api/User.php
index 1a132dc0..36886452 100644
--- a/app/main/controller/api/user.php
+++ b/app/Controller/Api/User.php
@@ -6,13 +6,13 @@
* Time: 20:50
*/
-namespace Controller\Api;
+namespace Exodus4D\Pathfinder\Controller\Api;
-use Controller;
-use lib\Config;
-use Model\Pathfinder;
-use Exception;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Model\Pathfinder;
+use Exodus4D\Pathfinder\Exception;
class User extends Controller\Controller{
@@ -46,7 +46,7 @@ class User extends Controller\Controller{
* login a valid character
* @param Pathfinder\CharacterModel $character
* @return bool
- * @throws Exception
+ * @throws \Exception
*/
protected function loginByCharacter(Pathfinder\CharacterModel &$character) : bool {
$login = false;
@@ -113,7 +113,7 @@ class User extends Controller\Controller{
* validate cookie character information
* -> return character data (if valid)
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function getCookieCharacter(\Base $f3){
$data = $f3->get('POST');
@@ -140,7 +140,7 @@ class User extends Controller\Controller{
}else{
$characterError = (object) [];
$characterError->type = 'warning';
- $characterError->message = 'This can happen through "invalid cookies(SSO)", "login restrictions", "ESI problems".';
+ $characterError->text = 'This can happen through "invalid cookies(SSO)", "login restrictions", "ESI problems".';
$return->error[] = $characterError;
}
}
@@ -184,7 +184,7 @@ class User extends Controller\Controller{
}else{
$captchaError = (object) [];
$captchaError->type = 'error';
- $captchaError->message = 'Could not create captcha image';
+ $captchaError->text = 'Could not create captcha image';
$return->error[] = $captchaError;
}
@@ -194,17 +194,20 @@ class User extends Controller\Controller{
/**
* log the current user out + clear character system log data
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function logout(\Base $f3){
- $this->logoutCharacter($f3, false, true, true, true);
+ $data = $f3->get('POST');
+ $deleteCookie = (bool)$data['deleteCookie'];
+
+ $this->logoutCharacter($f3, false, true, true, $deleteCookie, 200);
}
/**
* remote open ingame information window (character, corporation or alliance) Id
* -> the type is auto-recognized by CCP
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function openIngameWindow(\Base $f3){
$data = $f3->get('POST');
@@ -215,14 +218,14 @@ class User extends Controller\Controller{
if( $targetId = (int)$data['targetId']){
$activeCharacter = $this->getCharacter();
- $response = $f3->ccpClient()->openWindow($targetId, $activeCharacter->getAccessToken());
+ $response = $f3->ccpClient()->send('openWindow', $targetId, $activeCharacter->getAccessToken());
if(empty($response)){
$return->targetId = $targetId;
}else{
$error = (object) [];
$error->type = 'error';
- $error->message = $response['error'];
+ $error->text = $response['error'];
$return->error[] = $error;
}
}
@@ -235,12 +238,12 @@ class User extends Controller\Controller{
* -> a fresh user automatically generated on first login with a new character
* -> see SSO login
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function saveAccount(\Base $f3){
$data = $f3->get('POST');
- $return = (object) [];
+ $return = (object)[];
$return->error = [];
$captcha = $f3->get(self::SESSION_CAPTCHA_ACCOUNT_UPDATE);
@@ -250,7 +253,7 @@ class User extends Controller\Controller{
$newUserData = null;
- if( isset($data['formData']) ){
+ if(isset($data['formData'])){
$formData = $data['formData'];
try{
@@ -258,18 +261,12 @@ class User extends Controller\Controller{
$user = $activeCharacter->getUser();
// captcha is send -> check captcha ---------------------------------------------------------------
- if(
- isset($formData['captcha']) &&
- !empty($formData['captcha'])
- ){
+ if(isset($formData['captcha']) && !empty($formData['captcha'])){
if($formData['captcha'] === $captcha){
// change/set sensitive user data requires captcha!
// set username
- if(
- isset($formData['name']) &&
- !empty($formData['name'])
- ){
+ if(isset($formData['name']) && !empty($formData['name'])){
$user->name = $formData['name'];
}
@@ -290,9 +287,9 @@ class User extends Controller\Controller{
}else{
// captcha was send but not valid -> return error
- $captchaError = (object) [];
+ $captchaError = (object)[];
$captchaError->type = 'error';
- $captchaError->message = 'Captcha does not match';
+ $captchaError->text = 'Captcha does not match';
$return->error[] = $captchaError;
}
}
@@ -348,7 +345,7 @@ class User extends Controller\Controller{
/**
* delete current user account from DB
* @param \Base $f3
- * @throws Exception
+ * @throws \Exception
*/
public function deleteAccount(\Base $f3){
$data = $f3->get('POST.formData');
@@ -373,14 +370,14 @@ class User extends Controller\Controller{
sprintf(self::LOG_DELETE_ACCOUNT, $user->id, $user->name)
);
- $this->logoutCharacter($f3, true, true, true, true);
+ $this->logoutCharacter($f3, true, true, true, true, 200);
$user->erase();
}
}else{
// captcha not valid -> return error
$captchaError = (object) [];
$captchaError->type = 'error';
- $captchaError->message = 'Captcha does not match';
+ $captchaError->text = 'Captcha does not match';
$return->error[] = $captchaError;
}
diff --git a/app/main/controller/appcontroller.php b/app/Controller/AppController.php
similarity index 82%
rename from app/main/controller/appcontroller.php
rename to app/Controller/AppController.php
index 529f531b..b9880f4c 100644
--- a/app/main/controller/appcontroller.php
+++ b/app/Controller/AppController.php
@@ -6,11 +6,12 @@
* Time: 21:27
*/
-namespace Controller;
+namespace Exodus4D\Pathfinder\Controller;
-use Controller\Ccp as Ccp;
-use lib\Config;
-use lib\Resource;
+
+use Exodus4D\Pathfinder\Controller\Ccp as Ccp;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Resource;
class AppController extends Controller {
@@ -67,10 +68,8 @@ class AppController extends Controller {
$resource = Resource::instance();
$resource->register('script', 'app/login');
$resource->register('script', 'app/mappage', 'prefetch');
- $resource->register('image', 'pf-bg.jpg');
- $resource->register('image', 'pf-header-bg.jpg');
- $resource->register('image', 'landing/eve_sso_login_buttons_large_black.png');
- $resource->register('image', 'landing/eve_sso_login_buttons_large_black_hover.png');
+ $resource->register('image', 'sso/signature.png');
+ $resource->register('image', 'sso/gameplay.png');
}
}
\ No newline at end of file
diff --git a/app/main/controller/ccp/sso.php b/app/Controller/Ccp/Sso.php
similarity index 97%
rename from app/main/controller/ccp/sso.php
rename to app/Controller/Ccp/Sso.php
index 2b51cdb8..542e007b 100644
--- a/app/main/controller/ccp/sso.php
+++ b/app/Controller/Ccp/Sso.php
@@ -11,12 +11,12 @@
* - Check "PATHFINDER.API" in "pathfinder.ini" for correct API URLs
*/
-namespace Controller\Ccp;
+namespace Exodus4D\Pathfinder\Controller\Ccp;
-use Controller;
-use Controller\Api as Api;
-use Model\Pathfinder;
-use Lib;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Controller\Api as Api;
+use Exodus4D\Pathfinder\Model\Pathfinder;
+use Exodus4D\Pathfinder\Lib;
class Sso extends Api\User{
@@ -390,7 +390,7 @@ class Sso extends Api\User{
$accessData->refreshToken = null;
$accessData->esiAccessTokenExpires = 0;
- $authCodeRequestData = $this->getF3()->ssoClient()->getAccessData($this->getAuthorizationData(), $requestParams);
+ $authCodeRequestData = $this->getF3()->ssoClient()->send('getAccess', $this->getAuthorizationData(), $requestParams);
if( !empty($authCodeRequestData) ){
if( !empty($authCodeRequestData['accessToken']) ){
@@ -429,7 +429,7 @@ class Sso extends Api\User{
* @return array
*/
public function verifyCharacterData(string $accessToken) : array {
- $characterData = $this->getF3()->ssoClient()->getVerifyCharacterData($accessToken);
+ $characterData = $this->getF3()->ssoClient()->send('getVerifyCharacter', $accessToken);
if( !empty($characterData) ){
// convert string with scopes to array
@@ -451,8 +451,7 @@ class Sso extends Api\User{
$characterData = (object) [];
if($characterId){
- $characterDataBasic = $this->getF3()->ccpClient()->getCharacterData($characterId);
-
+ $characterDataBasic = $this->getF3()->ccpClient()->send('getCharacter', $characterId);
if( !empty($characterDataBasic) ){
// remove some "unwanted" data -> not relevant for Pathfinder
$characterData->character = array_filter($characterDataBasic, function($key){
diff --git a/app/main/controller/ccp/universe.php b/app/Controller/Ccp/Universe.php
similarity index 95%
rename from app/main/controller/ccp/universe.php
rename to app/Controller/Ccp/Universe.php
index 67f1fc68..fe6a1e3b 100644
--- a/app/main/controller/ccp/universe.php
+++ b/app/Controller/Ccp/Universe.php
@@ -6,13 +6,13 @@
* Time: 11:31
*/
-namespace Controller\Ccp;
+namespace Exodus4D\Pathfinder\Controller\Ccp;
-use Controller\Controller;
-use lib\Util;
-use Model;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Lib\Util;
+use Exodus4D\Pathfinder\Model;
-class Universe extends Controller {
+class Universe extends Controller\Controller {
const SESSION_KEY_SYSTEM_IDS = 'SESSION.SETUP.SYSTEM_IDS';
@@ -22,7 +22,7 @@ class Universe extends Controller {
$regionsWhitelist = [
10000002 // The Forge (13 constellations -> 93 systems)
];
- $regionIds = $f3->ccpClient()->getUniverseRegions();
+ $regionIds = $f3->ccpClient()->send('getUniverseRegions');
$regionIds = array_intersect($regionsWhitelist, $regionIds);
$region = Model\Universe\AbstractUniverseModel::getNew('RegionModel');
@@ -43,7 +43,7 @@ class Universe extends Controller {
$constellationsWhitelist = [
20000014 // Mal (11 systems)
];
- $constellationIds = $f3->ccpClient()->getUniverseConstellations();
+ $constellationIds = $f3->ccpClient()->send('getUniverseConstellations');
$constellationIds = array_intersect($constellationsWhitelist, $constellationIds);
$constellation = Model\Universe\AbstractUniverseModel::getNew('ConstellationModel');
foreach($constellationIds as $constellationId){
@@ -306,13 +306,13 @@ class Universe extends Controller {
$f3 = \Base::instance();
$universeNameData = [];
if( !empty($categories) && !empty($search)){
- $universeIds = $f3->ccpClient()->search($categories, $search, $strict);
+ $universeIds = $f3->ccpClient()->send('search', $categories, $search, $strict);
if(isset($universeIds['error'])){
// ESI error
$universeNameData = $universeIds;
}elseif( !empty($universeIds) ){
$universeIds = Util::arrayFlattenByValue($universeIds);
- $universeNameData = $f3->ccpClient()->getUniverseNamesData($universeIds);
+ $universeNameData = $f3->ccpClient()->send('getUniverseNames', $universeIds);
}
}
return $universeNameData;
diff --git a/app/main/controller/controller.php b/app/Controller/Controllerr.php
similarity index 92%
rename from app/main/controller/controller.php
rename to app/Controller/Controllerr.php
index 89d78cb1..59460951 100644
--- a/app/main/controller/controller.php
+++ b/app/Controller/Controllerr.php
@@ -6,22 +6,30 @@
* Time: 23:48
*/
-namespace Controller;
+namespace Exodus4D\Pathfinder\Controller;
-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\AbstractModel;
-use Model\Pathfinder;
-use DB;
+
+use Exodus4D\Pathfinder\Controller\Api as Api;
+use Exodus4D\Pathfinder\Lib\Api\CcpClient;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Db\Sql;
+use Exodus4D\Pathfinder\Lib\Resource;
+use Exodus4D\Pathfinder\Lib\Monolog;
+use Exodus4D\Pathfinder\Lib\Util;
+use Exodus4D\Pathfinder\Lib\Format;
+use Exodus4D\Pathfinder\Model\AbstractModel;
+use Exodus4D\Pathfinder\Model\Pathfinder;
+use Exodus4D\Pathfinder\Db\Sql\Mysql;
+use Exodus4D\Pathfinder\Exception\PathfinderException;
class Controller {
+ /**
+ * default HTTP response status for users that logged out
+ * -> if it is a "graceful" logout (e.g. user clicks "logout" button, we use 200)
+ */
+ const DEFAULT_STATUS_LOGOUT = 403;
+
// cookie specific keys (names)
const COOKIE_NAME_STATE = 'cookie';
const COOKIE_PREFIX_CHARACTER = 'char';
@@ -91,12 +99,12 @@ class Controller {
header('Pf-Maintenance: ' . $modeMaintenance);
}
}else{
- $this->initResource($f3);
+ $f3->set('tplResource', $this->initResource($f3));
$this->setTemplate(Config::getPathfinderData('view.index'));
- $f3->set('tplImage', \lib\format\Image::instance());
+ $f3->set('tplImage', Format\Image::instance());
}
return true;
@@ -132,11 +140,11 @@ class Controller {
$f3->get('SESSION_CACHE') === 'mysql' &&
($db = $f3->DB->getDB('PF')) instanceof SQL
){
- if(!headers_sent() && session_status()!=PHP_SESSION_ACTIVE){
+ if(!headers_sent() && session_status() != PHP_SESSION_ACTIVE){
/**
* callback() for suspect sessions
- * @param $session
- * @param $sid
+ * @param \DB\SQL\Session $session
+ * @param string $sid
* @return bool
*/
$onSuspect = function($session, $sid){
@@ -151,7 +159,7 @@ class Controller {
return false;
};
- new DB\SQL\MySQL\Session($db, 'sessions', true, $onSuspect);
+ new Mysql\Session($db, 'sessions', true, $onSuspect);
}
}
}
@@ -159,15 +167,18 @@ class Controller {
/**
* init new Resource handler
* @param \Base $f3
+ * @return Resource
*/
protected function initResource(\Base $f3){
$resource = Resource::instance();
+ $resource->setOption('basePath', $f3->get('BASE'));
$resource->setOption('filePath', [
- 'style' => $f3->get('BASE') . '/public/css/' . Config::getPathfinderData('version'),
- 'script' => $f3->get('BASE') . '/public/js/' . Config::getPathfinderData('version'),
- 'font' => $f3->get('BASE') . '/public/fonts',
- 'document' => $f3->get('BASE') . '/public/templates',
- 'image' => $f3->get('BASE') . '/public/img'
+ 'style' => sprintf('/%scss/%s', $f3->get('UI'), Config::getPathfinderData('version')),
+ 'script' => sprintf('/%sjs/%s', $f3->get('UI'), Config::getPathfinderData('version')),
+ 'font' => sprintf('/%sfonts', $f3->get('UI')),
+ 'document' => sprintf('/%stemplates', $f3->get('UI')),
+ 'image' => sprintf('/%simg/%s', $f3->get('UI'), Config::getPathfinderData('version')),
+ 'favicon' => $f3->get('FAVICON')
], true);
$resource->register('style', 'pathfinder');
@@ -185,7 +196,7 @@ class Controller {
$resource->register('url', Config::getPathfinderData('api.ccp_image_server'), 'dns-prefetch');
$resource->register('url', '//i.ytimg.com', 'dns-prefetch'); // YouTube tiny embed domain
- $f3->set('tplResource', $resource);
+ return $resource;
}
/**
@@ -476,9 +487,17 @@ class Controller {
* @param bool $deleteSession
* @param bool $deleteLog
* @param bool $deleteCookie
+ * @param int $statusCode
* @throws \Exception
*/
- protected function logoutCharacter(\Base $f3, bool $all = false, bool $deleteSession = true, bool $deleteLog = true, bool $deleteCookie = false){
+ protected function logoutCharacter(
+ \Base $f3,
+ bool $all = false,
+ bool $deleteSession = true,
+ bool $deleteLog = true,
+ bool $deleteCookie = false,
+ int $statusCode = self::DEFAULT_STATUS_LOGOUT
+ ){
$sessionCharacterData = (array)$f3->get(Api\User::SESSION_KEY_CHARACTERS);
if($sessionCharacterData){
@@ -507,12 +526,11 @@ class Controller {
}
if($f3->get('AJAX')){
- $status = 403;
- $f3->status($status);
+ $f3->status($statusCode);
$return = (object) [];
$return->reroute = rtrim(self::getEnvironmentData('URL'), '/') . $f3->alias('login');
- $return->error[] = $this->getErrorObject($status, Config::getMessageFromHTTPStatus($status));
+ $return->error[] = $this->getErrorObject($statusCode, Config::getHttpStatusByCode($statusCode), 'Access denied: User not found');
echo json_encode($return);
}else{
@@ -560,7 +578,7 @@ class Controller {
'routes' => []
];
- $serverStatus = $client->getServerStatus();
+ $serverStatus = $client->send('getServerStatus');
if( !isset($serverStatus['error']) ){
$statusData = $serverStatus['status'];
// calculate time diff since last server restart
@@ -582,7 +600,7 @@ class Controller {
$return->error[] = (new PathfinderException($serverStatus['error'], 500))->getError();
}
- $apiStatus = $client->getStatusForRoutes('latest');
+ $apiStatus = $client->send('getStatus', 'latest', true);
if( !isset($apiStatus['error']) ){
// find top status
$status = 'OK';
@@ -621,18 +639,18 @@ class Controller {
/**
* @param int $code
- * @param string $message
* @param string $status
+ * @param string $text
* @param null $trace
* @return \stdClass
*/
- protected function getErrorObject(int $code, string $message = '', string $status = '', $trace = null): \stdClass{
+ protected function getErrorObject(int $code, string $status = '', string $text = '', $trace = null) : \stdClass {
$object = (object) [];
$object->type = 'error';
$object->code = $code;
$object->status = empty($status) ? @constant('Base::HTTP_' . $code) : $status;
- if(!empty($message)){
- $object->message = $message;
+ if(!empty($text)){
+ $object->text = $text;
}
if(!empty($trace)){
$object->trace = $trace;
@@ -642,15 +660,15 @@ class Controller {
/**
* @param string $title
- * @param string $message
+ * @param string $text
* @param string $type
* @return \stdClass
*/
- protected function getNotificationObject(string $title, $message = '', $type = 'danger') : \stdClass {
+ protected function getNotificationObject(string $title, $text = '', $type = 'danger') : \stdClass {
$notification = (object) [];
$notification->type = in_array($type, self::NOTIFICATION_TYPES) ? $type : 'danger';
$notification->title = $title;
- $notification->message = $message;
+ $notification->text = $text;
return $notification;
}
@@ -744,7 +762,7 @@ class Controller {
if(count($matches) === 2){
$error->field = $matches[1][1];
- $error->message = 'Value "' . $matches[0][1] . '" already exists';
+ $error->text = 'Value "' . $matches[0][1] . '" already exists';
}
}
diff --git a/app/main/controller/logcontroller.php b/app/Controller/LogController.php
similarity index 97%
rename from app/main/controller/logcontroller.php
rename to app/Controller/LogController.php
index 1fc900b3..b17044fa 100644
--- a/app/main/controller/logcontroller.php
+++ b/app/Controller/LogController.php
@@ -6,12 +6,12 @@
* Time: 15:24
*/
-namespace controller;
+namespace Exodus4D\Pathfinder\Controller;
-use lib\Config;
-use lib\logging\MapLog;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Logging\MapLog;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class LogController extends \Prefab {
diff --git a/app/main/controller/mapcontroller.php b/app/Controller/MapController.php
similarity index 86%
rename from app/main/controller/mapcontroller.php
rename to app/Controller/MapController.php
index 5e0e2379..fcab21e5 100644
--- a/app/main/controller/mapcontroller.php
+++ b/app/Controller/MapController.php
@@ -6,11 +6,11 @@
* Time: 21:18
*/
-namespace Controller;
+namespace Exodus4D\Pathfinder\Controller;
-use lib\Config;
-use lib\Resource;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Resource;
class MapController extends AccessController {
diff --git a/app/main/controller/setup.php b/app/Controller/Setup.php
similarity index 95%
rename from app/main/controller/setup.php
rename to app/Controller/Setup.php
index 2f61e5f8..07ebd3fa 100644
--- a/app/main/controller/setup.php
+++ b/app/Controller/Setup.php
@@ -6,17 +6,20 @@
* Time: 10:59
*/
-namespace Controller;
+namespace Exodus4D\Pathfinder\Controller;
+
-use Controller\Ccp\Universe as UniverseController;
-use data\filesystem\Search;
use DB\SQL\Schema;
-use DB\SQL\MySQL as MySQL;
-use lib\Config;
-use lib\Cron;
-use lib\Util;
-use Model\Pathfinder;
-use Model\Universe;
+use Exodus4D\Pathfinder\Db\Sql\Mysql;
+use Exodus4D\Pathfinder\Lib\Db\Sql;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Cron;
+use Exodus4D\Pathfinder\Lib\Util;
+use Exodus4D\Pathfinder\Lib\Format\Number;
+use Exodus4D\Pathfinder\Model\Pathfinder;
+use Exodus4D\Pathfinder\Model\Universe;
+use Exodus4D\Pathfinder\Controller\Ccp\Universe as UniverseController;
+use Exodus4D\Pathfinder\Data\Filesystem\Search;
class Setup extends Controller {
@@ -145,7 +148,7 @@ class Setup extends Controller {
* @return bool
*/
function beforeroute(\Base $f3, $params): bool {
- $this->initResource($f3);
+ $f3->set('tplResource', $this->initResource($f3));
// page title
$f3->set('tplPageTitle', 'Setup | ' . Config::getPathfinderData('name'));
@@ -172,7 +175,7 @@ class Setup extends Controller {
$f3->set('tplCounter', $this->counter());
$f3->set('tplConvertBytes', function(){
- return call_user_func_array([\lib\format\Number::instance(), 'bytesToString'], func_get_args());
+ return call_user_func_array([Number::instance(), 'bytesToString'], func_get_args());
});
// render view
@@ -275,7 +278,7 @@ class Setup extends Controller {
* @return array
*/
protected function getNavigationConfig() : array {
- $config = [
+ return [
'server' => [
'icon' => 'fa-home'
],
@@ -301,8 +304,6 @@ class Setup extends Controller {
'icon' => 'fa-wrench'
]
];
-
- return $config;
}
/**
@@ -351,7 +352,7 @@ class Setup extends Controller {
* @return array
*/
protected function getServerInformation(\Base $f3) : array {
- $serverInfo = [
+ return [
'time' => [
'label' => 'Time',
'value' => date('Y/m/d H:i:s') . ' - (' . $f3->get('TZ') . ')'
@@ -389,8 +390,6 @@ class Setup extends Controller {
'value' => $f3->get('SERVER.SERVER_PROTOCOL') . ' - ' . $f3->get('SCHEME')
]
];
-
- return $serverInfo;
}
/**
@@ -399,7 +398,7 @@ class Setup extends Controller {
* @return array
*/
protected function getDirectoryConfig(\Base $f3) : array {
- $directoryData = [
+ return [
'TEMP' => [
'label' => 'TEMP',
'value' => $f3->get('TEMP'),
@@ -465,8 +464,6 @@ class Setup extends Controller {
'tooltip' => 'Folder for custom *.ini files. (e.g. when overwriting of default values in app/*.ini)'
]
];
-
- return $directoryData;
}
/**
@@ -639,7 +636,7 @@ class Setup extends Controller {
$maxExecutionTime = (int)ini_get('max_execution_time'); // 0 == infinite
$htmlErrors = (int)ini_get('html_errors');
- $phpConfig = [
+ return [
'exec' => [
'label' => 'exec()',
'required' => $f3->get('REQUIREMENTS.PHP.EXEC'),
@@ -697,8 +694,6 @@ class Setup extends Controller {
'tooltip' => 'PHP Session name.'
]
];
-
- return $phpConfig;
}
/**
@@ -717,14 +712,23 @@ class Setup extends Controller {
// collection of DSN specific $conf array (host, port, db,..)
$dsnData = [];
+ /**
+ * @param int $dbNum
+ * @param string $tag
+ * @return string
+ */
+ $getDbLabel = function(int $dbNum, string $tag) : string {
+ return ' db(' . $dbNum . ') : ' . $tag;
+ };
+
/**
* get client information for a Redis client
* @param \Redis $client
- * @param array $conf
+ * @param array $conf
* @return array
*/
$getClientInfo = function(\Redis $client, array $conf) : array {
- $redisInfo = [
+ return [
'dsn' => [
'label' => 'DSN',
'value' => $conf['host'] . ':' . $conf['port']
@@ -734,8 +738,6 @@ class Setup extends Controller {
'value' => $client->isConnected()
]
];
-
- return $redisInfo;
};
/**
@@ -746,7 +748,7 @@ class Setup extends Controller {
$getClientStats = function(\Redis $client) use ($f3) : array {
$redisStats = [];
- if($client->isConnected()){
+ if($client->isConnected() && !$client->getLastError()){
$redisServerInfo = (array)$client->info('SERVER');
$redisClientsInfo = (array)$client->info('CLIENTS');
$redisMemoryInfo = (array)$client->info('MEMORY');
@@ -762,20 +764,20 @@ class Setup extends Controller {
],
'maxMemory' => [
'label' => 'maxmemory',
- 'required' => \lib\format\Number::instance()->bytesToString($f3->get('REQUIREMENTS.REDIS.MAX_MEMORY')),
- 'version' => \lib\format\Number::instance()->bytesToString($redisMemoryInfo['maxmemory']),
+ 'required' => Number::instance()->bytesToString($f3->get('REQUIREMENTS.REDIS.MAX_MEMORY')),
+ 'version' => Number::instance()->bytesToString($redisMemoryInfo['maxmemory']),
'check' => $redisMemoryInfo['maxmemory'] >= $f3->get('REQUIREMENTS.REDIS.MAX_MEMORY'),
'tooltip' => 'Max memory limit for Redis'
],
'usedMemory' => [
'label' => 'used_memory',
- 'version' => \lib\format\Number::instance()->bytesToString($redisMemoryInfo['used_memory']),
+ 'version' => Number::instance()->bytesToString($redisMemoryInfo['used_memory']),
'check' => $redisMemoryInfo['used_memory'] < $redisMemoryInfo['maxmemory'],
'tooltip' => 'Current memory used by Redis'
],
'usedMemoryPeak' => [
'label' => 'used_memory_peak',
- 'version' => \lib\format\Number::instance()->bytesToString($redisMemoryInfo['used_memory_peak']),
+ 'version' => Number::instance()->bytesToString($redisMemoryInfo['used_memory_peak']),
'check' => $redisMemoryInfo['used_memory_peak'] <= $redisMemoryInfo['maxmemory'],
'tooltip' => 'Peak memory used by Redis'
],
@@ -819,14 +821,14 @@ class Setup extends Controller {
* @param string $tag
* @return array
*/
- $getDatabaseStatus = function(\Redis $client, string $tag) : array {
+ $getDatabaseStatus = function(\Redis $client, string $tag) use ($getDbLabel) : array {
$redisDatabases = [];
- if($client->isConnected()){
+ if($client->isConnected() && !$client->getLastError()){
$dbNum = $client->getDbNum();
$dbSize = $client->dbSize();
$redisDatabases = [
'db_' . $dbNum => [
- 'label' => ' db(' . $dbNum . ') : ' . $tag,
+ 'label' => $getDbLabel($dbNum, $tag),
'version' => $dbSize . ' keys',
'check' => $dbSize > 0,
'tooltip' => 'Keys in db(' . $dbNum . ')',
@@ -854,23 +856,28 @@ class Setup extends Controller {
* build (modify) $redisConfig with DNS $conf data
* @param array $conf
*/
- $buildRedisConfig = function(array $conf) use (&$redisConfig, $getClientInfo, $getClientStats, $getDatabaseStatus){
+ $buildRedisConfig = function(array $conf) use (&$redisConfig, $getDbLabel, $getClientInfo, $getClientStats, $getDatabaseStatus){
if($conf['type'] == 'redis'){
// is Redis -> group all DNS by host:port
- $client = new \Redis();
+ $uid = $conf['host'] . ':' . $conf['port'];
+ $client = new \Redis();
try{
$client->pconnect($conf['host'], $conf['port'], 0.3);
+ if(!empty($conf['auth'])){
+ $client->auth($conf['auth']);
+ }
+
if(isset($conf['db'])) {
$client->select($conf['db']);
}
$conf['db'] = $client->getDbNum();
}catch(\RedisException $e){
- // connection failed
+ // connection failed, getLastError() is called further down
}
- if(!array_key_exists($uid = $conf['host'] . ':' . $conf['port'], $redisConfig)){
+ if(!array_key_exists($uid, $redisConfig)){
$redisConfig[$uid] = $getClientInfo($client, $conf);
$redisConfig[$uid]['status'] = $getClientStats($client) + $getDatabaseStatus($client, $conf['tag']);
}elseif(!array_key_exists($uidDb = 'db_' . $conf['db'], $redisConfig[$uid]['status'])){
@@ -879,6 +886,13 @@ class Setup extends Controller {
$redisConfig[$uid]['status'][$uidDb]['label'] .= '; ' . $conf['tag'];
}
+ if($error = $client->getLastError()){
+ $redisConfig[$uid]['errors'][] = [
+ 'label' => $getDbLabel((int)$conf['db'], $conf['tag']),
+ 'error' => $error
+ ];
+ }
+
$client->close();
}
};
@@ -910,6 +924,7 @@ class Setup extends Controller {
'host' => $parts['host'],
'port' => $parts['port'],
'db' => !empty($params['database']) ? (int)$params['database'] : 0,
+ 'auth' => !empty($params['auth']) ? $params['auth'] : null,
'tag' => 'SESSION'
];
$dsnData[] = $conf;
@@ -937,14 +952,11 @@ class Setup extends Controller {
protected function checkSystemConfig(\Base $f3): array {
$systemConf = [];
if(function_exists('exec')){
- $gitOut = $composerOut = $rubyOut = $rubyGemsOut = $compassOut = $nodeOut = $npmOut = [];
- $gitStatus = $composerStatus = $rubyStatus = $rubyGemsStatus = $compassStatus = $nodeStatus = $npmStatus = 1;
+ $gitOut = $composerOut = $nodeOut = $npmOut = [];
+ $gitStatus = $composerStatus = $nodeStatus = $npmStatus = 1;
exec('git --version', $gitOut, $gitStatus);
exec('composer -V', $composerOut, $composerStatus);
- exec('ruby -v', $rubyOut, $rubyStatus);
- exec('gem -v', $rubyGemsOut, $rubyGemsStatus);
- exec('compass -v', $compassOut, $compassStatus);
exec('node -v', $nodeOut, $nodeStatus);
exec('npm -v', $npmOut, $npmStatus);
@@ -965,24 +977,6 @@ class Setup extends Controller {
'check' => $composerStatus == 0,
'tooltip' => 'Composer # composer -V : ' . $composerOut[0]
],
- 'Ruby' => [
- 'label' => 'Ruby',
- 'version' => $rubyOut[0] ? 'installed' : 'missing',
- 'check' => $rubyStatus == 0,
- 'tooltip' => 'Ruby # ruby -v : ' . $rubyOut[0]
- ],
- 'rubyGems' => [
- 'label' => 'Ruby gem',
- 'version' => $normalizeVersion($rubyGemsOut[0]) ?: 'missing',
- 'check' => $rubyGemsStatus == 0,
- 'tooltip' => 'gem # gem -v'
- ],
- 'compass' => [
- 'label' => 'Compass',
- 'version' => $compassOut[0] ? 'installed' : 'missing',
- 'check' => $compassStatus == 0,
- 'tooltip' => 'Compass # compass -v : ' . $compassOut[0]
- ],
'node' => [
'label' => 'NodeJs',
'required' => number_format((float)$f3->get('REQUIREMENTS.PATH.NODE'), 1, '.', ''),
@@ -1110,7 +1104,7 @@ class Setup extends Controller {
// collection for errors
$dbErrors = [];
/**
- * @var $db \lib\db\SQL
+ * @var $db Sql
*/
$db = $f3->DB->getDB($dbAlias);
@@ -1133,7 +1127,7 @@ class Setup extends Controller {
// get table data from model
foreach($dbData['models'] as $model){
- $tableConfig = call_user_func($model . '::resolveConfiguration');
+ $tableConfig = call_user_func(Config::withNamespace($model) . '::resolveConfiguration');
$requiredTables[$tableConfig['table']] = [
'model' => $model,
'name' => $tableConfig['table'],
@@ -1172,7 +1166,7 @@ class Setup extends Controller {
// Table exists
$tableExists = true;
// get existing table columns and column related constraints (if exists)
- $tableModifierTemp = new MySQL\TableModifier($requiredTableName, $schema);
+ $tableModifierTemp = new Mysql\TableModifier($requiredTableName, $schema);
$currentColumns = $tableModifierTemp->getCols(true);
// get row count
$tableRows = $db->getRowCount($requiredTableName);
@@ -1220,16 +1214,16 @@ class Setup extends Controller {
// column exists
// get tableModifier -> possible column update
- $tableModifier = new MySQL\TableModifier($requiredTableName, $schema);
+ $tableModifier = new Mysql\TableModifier($requiredTableName, $schema);
// get new column and copy Schema from existing column
- $col = new MySQL\Column($columnName, $tableModifier);
+ $col = new Mysql\Column($columnName, $tableModifier);
$col->copyfrom($currentColumns[$columnName]);
$currentColType = $currentColumns[$columnName]['type'];
$currentNullable = $currentColumns[$columnName]['nullable'];
$hasNullable = $currentNullable ? '1' : '0';
- $currentColIndexData = call_user_func($data['model'] . '::indexExists', [$columnName]);
+ $currentColIndexData = call_user_func(Config::withNamespace($data['model']) . '::indexExists', [$columnName]);
$currentColIndex = is_array($currentColIndexData);
$hasIndex = ($currentColIndex) ? '1' : '0';
$hasUnique = ($currentColIndexData['unique']) ? '1' : '0';
@@ -1441,10 +1435,10 @@ class Setup extends Controller {
/**
* check MySQL params
* @param \Base $f3
- * @param \lib\db\SQL $db
+ * @param Sql $db
* @return array
*/
- protected function checkDBConfig(\Base $f3, \lib\db\SQL $db) : array {
+ protected function checkDBConfig(\Base $f3, Sql $db) : array {
$checkAll = true;
// some db like "Maria DB" have some strange version strings....
$dbVersionString = $db->version();
@@ -1555,7 +1549,7 @@ class Setup extends Controller {
// setup tables
foreach($this->databases[$dbAlias]['models'] as $modelClass){
- $checkTables[] = call_user_func($modelClass . '::setup', $db);
+ $checkTables[] = call_user_func(Config::withNamespace($modelClass) . '::setup', $db);
}
}
return $checkTables;
@@ -1624,7 +1618,7 @@ class Setup extends Controller {
$setStats((array)$payload['stats']);
});
- $socketInformation = [
+ return [
'tcpSocket' => [
'label' => 'TCP-Socket (intern)',
'icon' => 'fa-exchange-alt',
@@ -1669,8 +1663,6 @@ class Setup extends Controller {
]
]
];
-
- return $socketInformation;
}
/**
@@ -1710,13 +1702,11 @@ class Setup extends Controller {
]
];
- $config = [
+ return [
'checkCronConfig' => $cronConf,
'settings' => $f3->constants($cron, 'DEFAULT_'),
'jobs' => $cron->getJobsConfig()
];
-
- return $config;
}
/**
@@ -1950,7 +1940,7 @@ class Setup extends Controller {
}
$bytesAll += $bytes;
- $dirAll[$key]['size'] = ($maxHit ? '>' : '') . \lib\format\Number::instance()->bytesToString($bytes);
+ $dirAll[$key]['size'] = ($maxHit ? '>' : '') . Number::instance()->bytesToString($bytes);
$dirAll[$key]['task'] = [
[
'action' => http_build_query([
@@ -1965,7 +1955,7 @@ class Setup extends Controller {
}
return [
- 'sizeAll' => ($maxHitAll ? '>' : '') . \lib\format\Number::instance()->bytesToString($bytesAll),
+ 'sizeAll' => ($maxHitAll ? '>' : '') . Number::instance()->bytesToString($bytesAll),
'dirAll' => $dirAll
];
}
diff --git a/app/main/cron/abstractcron.php b/app/Cron/AbstractCron.php
similarity index 96%
rename from app/main/cron/abstractcron.php
rename to app/Cron/AbstractCron.php
index 5e98b942..2413a866 100644
--- a/app/main/cron/abstractcron.php
+++ b/app/Cron/AbstractCron.php
@@ -6,9 +6,10 @@
* Time: 12:13
*/
-namespace cron;
+namespace Exodus4D\Pathfinder\Cron;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Lib\Format\Number;
+use Exodus4D\Pathfinder\Model\Pathfinder;
abstract class AbstractCron {
@@ -90,7 +91,7 @@ abstract class AbstractCron {
protected function logStart(string $job, bool $logging = true){
$this->setMaxExecutionTime();
- $cron = \lib\Cron::instance();
+ $cron = \Exodus4D\Pathfinder\Lib\Cron::instance();
if(isset($cron->jobs[$job])){
// set "start" date for current cronjob
$jobConf = $cron->getJobDataFromConf($cron->jobs[$job]);
@@ -201,7 +202,7 @@ abstract class AbstractCron {
$text = sprintf(self::LOG_TEXT_BASE,
$state['count'], $state['importCount'], $percent, $state['total'],
- \lib\format\Number::instance()->bytesToString($memPeak), $duration
+ Number::instance()->bytesToString($memPeak), $duration
);
$text .= $logText ? $logText: '';
diff --git a/app/main/cron/cache.php b/app/Cron/Cache.php
similarity index 96%
rename from app/main/cron/cache.php
rename to app/Cron/Cache.php
index 6bafd0f7..9cc0caf4 100644
--- a/app/main/cron/cache.php
+++ b/app/Cron/Cache.php
@@ -6,9 +6,9 @@
* Time: 14:59
*/
-namespace cron;
+namespace Exodus4D\Pathfinder\Cron;
-use data\filesystem\Search;
+use Exodus4D\Pathfinder\Data\Filesystem\Search;
class Cache extends AbstractCron {
diff --git a/app/main/cron/ccpsystemsupdate.php b/app/Cron/CcpSystemsUpdate.php
similarity index 95%
rename from app/main/cron/ccpsystemsupdate.php
rename to app/Cron/CcpSystemsUpdate.php
index 20d92246..c9880f42 100644
--- a/app/main/cron/ccpsystemsupdate.php
+++ b/app/Cron/CcpSystemsUpdate.php
@@ -6,8 +6,10 @@
* Time: 21:31
*/
-namespace Cron;
-use lib\db\SQL;
+namespace Exodus4D\Pathfinder\Cron;
+
+
+use Exodus4D\Pathfinder\Lib\Db\Sql;
class CcpSystemsUpdate extends AbstractCron {
@@ -29,11 +31,11 @@ class CcpSystemsUpdate extends AbstractCron {
/**
* checks if a table exists in DB or not
- * @param SQL$db
+ * @param Sql $db
* @param string $table
* @return bool
*/
- protected function tableExists (SQL $db, string $table) : bool {
+ protected function tableExists (Sql $db, string $table) : bool {
return !empty($db->exec('SHOW TABLES LIKE :table', [':table' => $table]));
}
@@ -111,19 +113,19 @@ class CcpSystemsUpdate extends AbstractCron {
// switch DB for data import..
/**
- * @var $pfDB SQL
+ * @var $pfDB Sql
*/
$pfDB = $f3->DB->getDB('PF');
// get current jump data --------------------------------------------------------------------------------------
$time_start = microtime(true);
- $jumpData = $f3->ccpClient()->getUniverseJumps();
+ $jumpData = $f3->ccpClient()->send('getUniverseJumps');
$time_end = microtime(true);
$execTimeGetJumpData = $time_end - $time_start;
// get current kill data --------------------------------------------------------------------------------------
$time_start = microtime(true);
- $killData = $f3->ccpClient()->getUniverseKills();
+ $killData = $f3->ccpClient()->send('getUniverseKills');
$time_end = microtime(true);
$execTimeGetKillData = $time_end - $time_start;
diff --git a/app/main/cron/characterupdate.php b/app/Cron/CharacterUpdate.php
similarity index 98%
rename from app/main/cron/characterupdate.php
rename to app/Cron/CharacterUpdate.php
index e99781cb..53eb5921 100644
--- a/app/main/cron/characterupdate.php
+++ b/app/Cron/CharacterUpdate.php
@@ -6,10 +6,10 @@
* Time: 19:35
*/
-namespace Cron;
+namespace Exodus4D\Pathfinder\Cron;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class CharacterUpdate extends AbstractCron {
diff --git a/app/main/cron/maphistory.php b/app/Cron/MapHistory.php
similarity index 96%
rename from app/main/cron/maphistory.php
rename to app/Cron/MapHistory.php
index 46e24086..70da7d97 100644
--- a/app/main/cron/maphistory.php
+++ b/app/Cron/MapHistory.php
@@ -6,11 +6,11 @@
* Time: 15:48
*/
-namespace Cron;
+namespace Exodus4D\Pathfinder\Cron;
-use data\mapper\SortingIterator;
-use data\file\FileHandler;
-use data\filesystem\Search;
+use Exodus4D\Pathfinder\Data\Mapper\SortingIterator;
+use Exodus4D\Pathfinder\Data\File\FileHandler;
+use Exodus4D\Pathfinder\Data\Filesystem\Search;
class MapHistory extends AbstractCron {
diff --git a/app/main/cron/mapupdate.php b/app/Cron/MapUpdate.php
similarity index 98%
rename from app/main/cron/mapupdate.php
rename to app/Cron/MapUpdate.php
index 1535e3ba..1d619636 100644
--- a/app/main/cron/mapupdate.php
+++ b/app/Cron/MapUpdate.php
@@ -6,11 +6,11 @@
* Time: 17:54
*/
-namespace cron;
+namespace Exodus4D\Pathfinder\Cron;
-use lib\Config;
-use Model\Pathfinder;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Model\Pathfinder;
class MapUpdate extends AbstractCron {
diff --git a/app/main/cron/statisticsupdate.php b/app/Cron/StatisticsUpdate.php
similarity index 97%
rename from app/main/cron/statisticsupdate.php
rename to app/Cron/StatisticsUpdate.php
index b23e8349..b2dc743e 100644
--- a/app/main/cron/statisticsupdate.php
+++ b/app/Cron/StatisticsUpdate.php
@@ -6,7 +6,7 @@
* Time: 21:31
*/
-namespace cron;
+namespace Exodus4D\Pathfinder\Cron;
class StatisticsUpdate extends AbstractCron {
diff --git a/app/main/cron/universe.php b/app/Cron/Universe.php
similarity index 96%
rename from app/main/cron/universe.php
rename to app/Cron/Universe.php
index bfe88568..2caa9368 100644
--- a/app/main/cron/universe.php
+++ b/app/Cron/Universe.php
@@ -6,9 +6,10 @@
* Time: 03:46
*/
-namespace Cron;
+namespace Exodus4D\Pathfinder\Cron;
-use Model;
+
+use Exodus4D\Pathfinder\Model;
class Universe extends AbstractCron {
@@ -185,7 +186,7 @@ class Universe extends AbstractCron {
switch($type){
case 'system':
// load systems + dependencies (planets, star, types,...)
- $ids = $f3->ccpClient()->getUniverseSystems();
+ $ids = $f3->ccpClient()->send('getUniverseSystems');
$modelClass = 'SystemModel';
$setupModel = function(Model\Universe\SystemModel &$model, int $id){
$model->loadById($id);
@@ -194,7 +195,7 @@ class Universe extends AbstractCron {
break;
case 'stargate':
// load all stargates. Systems must be present first!
- $ids = $f3->ccpClient()->getUniverseSystems();
+ $ids = $f3->ccpClient()->send('getUniverseSystems');
$modelClass = 'SystemModel';
$setupModel = function(Model\Universe\SystemModel &$model, int $id){
$model->loadById($id);
@@ -202,7 +203,7 @@ class Universe extends AbstractCron {
};
break;
case 'station':
- $ids = $f3->ccpClient()->getUniverseSystems();
+ $ids = $f3->ccpClient()->send('getUniverseSystems');
$modelClass = 'SystemModel';
$setupModel = function(Model\Universe\SystemModel &$model, int $id){
if($model->getById($id)){
@@ -215,7 +216,7 @@ class Universe extends AbstractCron {
break;
case 'sovereignty':
// load sovereignty map data. Systems must be present first!
- $sovData = $f3->ccpClient()->getSovereigntyMap();
+ $sovData = $f3->ccpClient()->send('getSovereigntyMap');
$ids = !empty($sovData = $sovData['map']) ? array_keys($sovData): [];
$modelClass = 'SystemModel';
$setupModel = function(Model\Universe\SystemModel &$model, int $id) use ($sovData) {
@@ -228,7 +229,7 @@ class Universe extends AbstractCron {
};
break;
case 'faction_war_systems':
- $fwSystems = $f3->ccpClient()->getFactionWarSystems();
+ $fwSystems = $f3->ccpClient()->send('getFactionWarSystems');
$ids = !empty($fwSystems = $fwSystems['systems']) ? array_keys($fwSystems): [];
$modelClass = 'SystemModel';
$setupModel = function(Model\Universe\SystemModel &$model, int $id) use ($fwSystems) {
@@ -242,7 +243,7 @@ class Universe extends AbstractCron {
break;
case 'index_system':
// setup system index, Systems must be present first!
- $ids = $f3->ccpClient()->getUniverseSystems();
+ $ids = $f3->ccpClient()->send('getUniverseSystems');
$modelClass = 'SystemModel';
$setupModel = function(Model\Universe\SystemModel &$model, int $id){
$model->getById($id); // no loadById() here! would take "forever" when system not exists and must be build up first...
@@ -309,8 +310,8 @@ class Universe extends AbstractCron {
*/
$system = Model\Universe\AbstractUniverseModel::getNew('SystemModel');
- $sovData = $f3->ccpClient()->getSovereigntyMap();
- $fwSystems = $f3->ccpClient()->getFactionWarSystems();
+ $sovData = $f3->ccpClient()->send('getSovereigntyMap');
+ $fwSystems = $f3->ccpClient()->send('getFactionWarSystems');
$fwSystems = $fwSystems['systems'];
$ids = !empty($sovData = $sovData['map']) ? array_keys($sovData): [];
sort($ids, SORT_NUMERIC);
diff --git a/app/main/data/file/filehandler.php b/app/Data/File/FileHandler.php
similarity index 98%
rename from app/main/data/file/filehandler.php
rename to app/Data/File/FileHandler.php
index f1c6e75d..e6ff1ddf 100644
--- a/app/main/data/file/filehandler.php
+++ b/app/Data/File/FileHandler.php
@@ -6,7 +6,7 @@
* Time: 18:47
*/
-namespace data\file;
+namespace Exodus4D\Pathfinder\Data\File;
class FileHandler extends \Prefab {
diff --git a/app/main/data/file/reversesplfileobject.php b/app/Data/File/ReverseSplFileObject.php
similarity index 99%
rename from app/main/data/file/reversesplfileobject.php
rename to app/Data/File/ReverseSplFileObject.php
index 13b71988..829ae027 100644
--- a/app/main/data/file/reversesplfileobject.php
+++ b/app/Data/File/ReverseSplFileObject.php
@@ -6,7 +6,7 @@
* Time: 18:42
*/
-namespace data\file;
+namespace Exodus4D\Pathfinder\Data\File;
class ReverseSplFileObject extends \SplFileObject{
diff --git a/app/main/data/filesystem/search.php b/app/Data/Filesystem/Search.php
similarity index 98%
rename from app/main/data/filesystem/search.php
rename to app/Data/Filesystem/Search.php
index 8037b1f5..2872faa6 100644
--- a/app/main/data/filesystem/search.php
+++ b/app/Data/Filesystem/Search.php
@@ -6,7 +6,7 @@
* Time: 16:58
*/
-namespace data\filesystem;
+namespace Exodus4D\Pathfinder\Data\Filesystem;
class Search {
diff --git a/app/main/data/mapper/abstractiterator.php b/app/Data/Mapper/AbstractIterator.php
similarity index 92%
rename from app/main/data/mapper/abstractiterator.php
rename to app/Data/Mapper/AbstractIterator.php
index 01141172..f81b02e4 100644
--- a/app/main/data/mapper/abstractiterator.php
+++ b/app/Data/Mapper/AbstractIterator.php
@@ -6,9 +6,9 @@
* Time: 04:06
*/
-namespace data\mapper;
+namespace Exodus4D\Pathfinder\Data\Mapper;
-use lib\Util;
+use Exodus4D\Pathfinder\Lib\Util;
class AbstractIterator extends \RecursiveArrayIterator {
@@ -26,7 +26,10 @@ class AbstractIterator extends \RecursiveArrayIterator {
*/
protected static $removeUnmapped = true;
-
+ /**
+ * AbstractIterator constructor.
+ * @param $data
+ */
function __construct($data){
parent::__construct($data, \RecursiveIteratorIterator::SELF_FIRST);
}
@@ -52,10 +55,10 @@ class AbstractIterator extends \RecursiveArrayIterator {
/**
* recursive iterator function called on every node
- * @param $iterator
- * @return mixed
+ * @param AbstractIterator $iterator
+ * @return AbstractIterator
*/
- static function recursiveIterator($iterator){
+ static function recursiveIterator(AbstractIterator $iterator){
$keyWhitelist = array_keys(static::$map);
diff --git a/app/main/data/mapper/sortingiterator.php b/app/Data/Mapper/SortingIterator.php
similarity index 89%
rename from app/main/data/mapper/sortingiterator.php
rename to app/Data/Mapper/SortingIterator.php
index 875bc4dc..ceb4b7f3 100644
--- a/app/main/data/mapper/sortingiterator.php
+++ b/app/Data/Mapper/SortingIterator.php
@@ -6,7 +6,7 @@
* Time: 00:55
*/
-namespace data\mapper;
+namespace Exodus4D\Pathfinder\Data\Mapper;
class SortingIterator extends \ArrayIterator {
diff --git a/app/main/db/sql/mysql/session.php b/app/Db/Sql/Mysql/Session.php
similarity index 84%
rename from app/main/db/sql/mysql/session.php
rename to app/Db/Sql/Mysql/Session.php
index 1de0eeb8..cce602ec 100644
--- a/app/main/db/sql/mysql/session.php
+++ b/app/Db/Sql/Mysql/Session.php
@@ -6,12 +6,19 @@
* Time: 15:40
*/
-namespace DB\SQL\MySQL;
+namespace Exodus4D\Pathfinder\Db\Sql\Mysql;
class Session extends \DB\SQL\Session {
-
+ /**
+ * Session constructor.
+ * @param \DB\SQL $db
+ * @param string $table
+ * @param bool $force
+ * @param callback $onsuspect
+ * @param string $key
+ */
function __construct(\DB\SQL $db, string $table = 'sessions', bool $force = true, $onsuspect = null, $key = null){
if($force){
// create sessions table
diff --git a/app/main/db/sql/mysql/tablemodifier.php b/app/Db/Sql/Mysql/tablemodifier.php
similarity index 96%
rename from app/main/db/sql/mysql/tablemodifier.php
rename to app/Db/Sql/Mysql/tablemodifier.php
index b28b62f4..7e3312ef 100644
--- a/app/main/db/sql/mysql/tablemodifier.php
+++ b/app/Db/Sql/Mysql/tablemodifier.php
@@ -12,7 +12,9 @@
* - FOREIGN KEY CONSTRAINTS (single column key)
*/
-namespace DB\SQL\MySQL;
+namespace Exodus4D\Pathfinder\Db\Sql\Mysql;
+
+
use DB\SQL;
class TableModifier extends SQL\TableModifier {
@@ -23,7 +25,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| SQL\MySQL\Constraint $constraint
+ * @param null| Constraint $constraint
* @return Constraint[]
*/
public function listConstraint($constraint = null){
@@ -65,7 +67,7 @@ class TableModifier extends SQL\TableModifier {
/**
* checks whether a constraint name exists or not
* -> does not check constraint params
- * @param SQL\MySQL\Constraint $constraint
+ * @param Constraint $constraint
* @return bool
*/
public function constraintExists($constraint){
@@ -75,7 +77,7 @@ class TableModifier extends SQL\TableModifier {
/**
* drop foreign key constraint
- * @param SQL\MySQL\Constraint $constraint
+ * @param Constraint $constraint
*/
public function dropConstraint($constraint){
if($constraint->isValid()){
@@ -88,7 +90,7 @@ class TableModifier extends SQL\TableModifier {
/**
* Add/Update foreign key constraint
- * @param SQL\MySQL\Constraint $constraint
+ * @param Constraint $constraint
*/
public function addConstraint($constraint){
@@ -131,7 +133,6 @@ class Column extends SQL\Column {
}
/**
- * @see \DB\SQL\MySQL\TableModifier->constraintExists();
* @param Constraint $constraint
* @return mixed
*/
@@ -147,7 +148,7 @@ class Column extends SQL\Column {
* $constraintData['on-update'] => ON UPDATE action (optional) default: see \DB\SQL\MySQL\Constraint const
*
* @param array $constraintData
- * @return SQL\MySQL\Constraint
+ * @return Constraint
*/
public function newConstraint($constraintData){
diff --git a/app/main/exception/configexception.php b/app/Exception/ConfigException.php
similarity index 72%
rename from app/main/exception/configexception.php
rename to app/Exception/ConfigException.php
index 9f2bb033..d61d89e4 100644
--- a/app/main/exception/configexception.php
+++ b/app/Exception/ConfigException.php
@@ -6,11 +6,14 @@
* Time: 18:53
*/
-namespace Exception;
+namespace Exodus4D\Pathfinder\Exception;
class ConfigException extends PathfinderException {
+ /**
+ * @var array
+ */
protected $codes = [
1000 => 500
];
diff --git a/app/main/exception/databaseexception.php b/app/Exception/DatabaseException.php
similarity index 65%
rename from app/main/exception/databaseexception.php
rename to app/Exception/DatabaseException.php
index 187beeed..79ac3fe3 100644
--- a/app/main/exception/databaseexception.php
+++ b/app/Exception/DatabaseException.php
@@ -6,14 +6,22 @@
* Time: 20:31
*/
-namespace Exception;
+namespace Exodus4D\Pathfinder\Exception;
+
class DatabaseException extends PathfinderException {
+ /**
+ * @var array
+ */
protected $codes = [
1500 => 500
];
+ /**
+ * DatabaseException constructor.
+ * @param string $message
+ */
public function __construct(string $message){
parent::__construct($message, 1500);
}
diff --git a/app/main/exception/dateexception.php b/app/Exception/DateException.php
similarity index 74%
rename from app/main/exception/dateexception.php
rename to app/Exception/DateException.php
index 4b578fa7..823c49a4 100644
--- a/app/main/exception/dateexception.php
+++ b/app/Exception/DateException.php
@@ -6,10 +6,14 @@
* Time: 18:12
*/
-namespace Exception;
+namespace Exodus4D\Pathfinder\Exception;
class DateException extends PathfinderException {
+
+ /**
+ * @var array
+ */
protected $codes = [
3000 => 500 // invalid DateRange
];
diff --git a/app/main/exception/pathfinderexception.php b/app/Exception/PathfinderException.php
similarity index 86%
rename from app/main/exception/pathfinderexception.php
rename to app/Exception/PathfinderException.php
index 2636e1d4..a65164f2 100644
--- a/app/main/exception/pathfinderexception.php
+++ b/app/Exception/PathfinderException.php
@@ -6,9 +6,10 @@
* Time: 00:41
*/
-namespace Exception;
+namespace Exodus4D\Pathfinder\Exception;
-use lib\Config;
+
+use Exodus4D\Pathfinder\Lib\Config;
class PathfinderException extends \Exception {
@@ -26,6 +27,11 @@ class PathfinderException extends \Exception {
0 => self::DEFAULT_RESPONSECODE
];
+ /**
+ * PathfinderException constructor.
+ * @param string $message
+ * @param int $code
+ */
public function __construct(string $message, int $code = 0){
if( !array_key_exists($code, $this->codes) ){
// exception code not specified by child class
@@ -43,7 +49,7 @@ class PathfinderException extends \Exception {
$error->type = 'error';
$error->code = $this->getResponseCode();
$error->status = Config::getHttpStatusByCode($this->getResponseCode());
- $error->message = $this->getMessage();
+ $error->text = $this->getMessage();
if(\Base::instance()->get('DEBUG') >= 1){
$error->trace = preg_split('/\R/', $this->getTraceAsString()); // no $this->>getTrace() here -> to much data
}
diff --git a/app/main/exception/registrationexception.php b/app/Exception/RegistrationException.php
similarity index 77%
rename from app/main/exception/registrationexception.php
rename to app/Exception/RegistrationException.php
index b98e107b..bd0057b2 100644
--- a/app/main/exception/registrationexception.php
+++ b/app/Exception/RegistrationException.php
@@ -6,11 +6,14 @@
* Time: 21:21
*/
-namespace Exception;
+namespace Exodus4D\Pathfinder\Exception;
class RegistrationException extends PathfinderException{
+ /**
+ * @var array
+ */
protected $codes = [
2000 => 403
];
@@ -21,6 +24,11 @@ class RegistrationException extends PathfinderException{
*/
private $field;
+ /**
+ * RegistrationException constructor.
+ * @param string $message
+ * @param string $field
+ */
public function __construct(string $message, string $field = ''){
parent::__construct($message, 2000);
$this->field = $field;
diff --git a/app/main/exception/validationexception.php b/app/Exception/ValidationException.php
similarity index 78%
rename from app/main/exception/validationexception.php
rename to app/Exception/ValidationException.php
index abfbf668..b28e1b80 100644
--- a/app/main/exception/validationexception.php
+++ b/app/Exception/ValidationException.php
@@ -6,11 +6,14 @@
* Time: 00:12
*/
-namespace Exception;
+namespace Exodus4D\Pathfinder\Exception;
class ValidationException extends PathfinderException {
+ /**
+ * @var array
+ */
protected $codes = [
2000 => 422
];
@@ -21,6 +24,11 @@ class ValidationException extends PathfinderException {
*/
private $field;
+ /**
+ * ValidationException constructor.
+ * @param string $message
+ * @param string $field
+ */
public function __construct(string $message, string $field = ''){
parent::__construct($message, 2000);
$this->field = $field;
diff --git a/app/main/lib/api/AbstractClient.php b/app/Lib/Api/AbstractClient.php
similarity index 89%
rename from app/main/lib/api/AbstractClient.php
rename to app/Lib/Api/AbstractClient.php
index 4b8d9756..6579fa52 100644
--- a/app/main/lib/api/AbstractClient.php
+++ b/app/Lib/Api/AbstractClient.php
@@ -6,7 +6,7 @@
* Time: 17:41
*/
-namespace lib\api;
+namespace Exodus4D\Pathfinder\Lib\Api;
use Cache\Adapter\Filesystem\FilesystemCachePool;
use Cache\Adapter\PHPArray\ArrayCachePool;
@@ -14,10 +14,10 @@ use Cache\Adapter\Redis\RedisCachePool;
use Cache\Namespaced\NamespacedCachePool;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
-use lib\Config;
-use lib\Util;
-use lib\logging;
-use controller\LogController;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Util;
+use Exodus4D\Pathfinder\Lib\Logging;
+use Exodus4D\Pathfinder\Controller\LogController;
use Exodus4D\ESI\Client\ApiInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Http\Message\RequestInterface;
@@ -89,8 +89,8 @@ abstract class AbstractClient extends \Prefab {
* @return \Closure
*/
protected function newLog() : \Closure {
- return function(string $action, string $level = 'warning') : logging\LogInterface {
- $log = new logging\ApiLog($action, $level);
+ return function(string $action, string $level = 'warning') : Logging\LogInterface {
+ $log = new Logging\ApiLog($action, $level);
$log->addHandler('stream', 'json', $this->getStreamConfig($action));
return $log;
};
@@ -134,6 +134,9 @@ abstract class AbstractClient extends \Prefab {
Config::REDIS_OPT_READ_TIMEOUT
)
){
+ if(!empty($poolConfig['auth'])){
+ $client->auth($poolConfig['auth']);
+ }
if(isset($poolConfig['tag'])){
$name = 'pathfinder|php|tag:' . strtolower($poolConfig['tag']) . '|pid:' . getmypid();
@@ -298,8 +301,8 @@ abstract class AbstractClient extends \Prefab {
public function __call(string $name, array $arguments = []){
$return = [];
if(is_object($this->client)){
- if( method_exists($this->client, $name) ){
- $return = call_user_func_array([$this->client, $name], $arguments);
+ if(method_exists($this->client, $name)){
+ $return = call_user_func_array([$this->client, $name], $arguments);
}else{
$errorMsg = $this->getMissingMethodError(get_class($this->client), $name);
$this->getLogger('ERROR')->write($errorMsg);
@@ -336,18 +339,20 @@ abstract class AbstractClient extends \Prefab {
$client->setNewLog($this->newLog());
$client->setIsLoggable($this->isLoggable($f3));
- $client->setLogStats(true); // add cURL stats (e.g. transferTime) to logged requests
- $client->setLogCache(true); // add cache info (e.g. from cached) to logged requests
- //$client->setLogAllStatus(true); // log all requests regardless of response HTTP status code
- $client->setLogFile('esi_requests');//
+ $client->setLogStats(true); // add cURL stats (e.g. transferTime) to loggable requests
+ $client->setLogCache(true); // add cache info (e.g. from cached) to loggable requests
+ $client->setLogAllStatus(false); // log all requests regardless of response HTTP status code
+ $client->setLogRequestHeaders(false); // add request HTTP headers to loggable requests
+ $client->setLogResponseHeaders(false); // add response HTTP headers to loggable requests
+ $client->setLogFile('esi_requests');
$client->setRetryLogFile('esi_retry_requests');
$client->setCacheDebug(true);
$client->setCachePool($this->getCachePool($f3));
- // use local proxy server for debugging requests
- //$client->setProxy('127.0.0.1:8888');
+
+ //$client->setProxy('127.0.0.1:8888'); // use local proxy server for debugging requests
// disable SSL certificate verification -> allow proxy to decode(view) request
//$client->setVerify(false);
diff --git a/app/main/lib/api/CcpClient.php b/app/Lib/Api/CcpClient.php
similarity index 76%
rename from app/main/lib/api/CcpClient.php
rename to app/Lib/Api/CcpClient.php
index 567a5849..0d7c8933 100644
--- a/app/main/lib/api/CcpClient.php
+++ b/app/Lib/Api/CcpClient.php
@@ -6,20 +6,18 @@
* Time: 17:43
*/
-namespace lib\api;
+namespace Exodus4D\Pathfinder\Lib\Api;
-use lib\Config;
-use Exodus4D\ESI\Client\ESI as Client;
+use Exodus4D\Pathfinder\Lib\Config;
use Exodus4D\ESI\Client\ApiInterface;
-use Exodus4D\ESI\Client\EsiInterface;
-
+use Exodus4D\ESI\Client\Ccp\Esi\Esi as Client;
/**
* Class CcpClient
* @package lib\api
*
- * @method EsiInterface getServerStatus()
- * @method EsiInterface getStatusForRoutes(string $version)
+ * @method ApiInterface send(string $requestHandler, ...$handlerParams)
+ * @method ApiInterface sendBatch(array $configs)
*/
class CcpClient extends AbstractClient {
diff --git a/app/Lib/Api/EveScoutClient.php b/app/Lib/Api/EveScoutClient.php
new file mode 100644
index 00000000..1d124a33
--- /dev/null
+++ b/app/Lib/Api/EveScoutClient.php
@@ -0,0 +1,38 @@
+getLogger()->write($this->getMissingClassError(Client::class));
+ }
+
+ return $client;
+ }
+}
\ No newline at end of file
diff --git a/app/main/lib/api/GitHubClient.php b/app/Lib/Api/GitHubClient.php
similarity index 69%
rename from app/main/lib/api/GitHubClient.php
rename to app/Lib/Api/GitHubClient.php
index ff8bb52c..d87d6c23 100644
--- a/app/main/lib/api/GitHubClient.php
+++ b/app/Lib/Api/GitHubClient.php
@@ -6,12 +6,19 @@
* Time: 22:23
*/
-namespace lib\api;
+namespace Exodus4D\Pathfinder\Lib\Api;
-use lib\Config;
-use Exodus4D\ESI\Client\Github as Client;
+use Exodus4D\Pathfinder\Lib\Config;
use Exodus4D\ESI\Client\ApiInterface;
+use Exodus4D\ESI\Client\GitHub\GitHub as Client;
+/**
+ * Class GitHubClient
+ * @package lib\api
+ *
+ * @method ApiInterface send(string $requestHandler, ...$handlerParams)
+ * @method ApiInterface sendBatch(array $configs)
+ */
class GitHubClient extends AbstractClient {
/**
diff --git a/app/main/lib/api/SsoClient.php b/app/Lib/Api/SsoClient.php
similarity index 79%
rename from app/main/lib/api/SsoClient.php
rename to app/Lib/Api/SsoClient.php
index 1a0cb108..30c47327 100644
--- a/app/main/lib/api/SsoClient.php
+++ b/app/Lib/Api/SsoClient.php
@@ -6,12 +6,16 @@
* Time: 17:39
*/
-namespace lib\api;
+namespace Exodus4D\Pathfinder\Lib\Api;
-use lib\Config;
-use Exodus4D\ESI\Client\SSO as Client;
+use Exodus4D\Pathfinder\Lib\Config;
use Exodus4D\ESI\Client\ApiInterface;
+use Exodus4D\ESI\Client\Ccp\Sso\Sso as Client;
+/**
+ * Class SsoClient
+ * @package lib\api
+ */
class SsoClient extends AbstractClient {
/**
diff --git a/app/main/lib/config.php b/app/Lib/Config.php
similarity index 91%
rename from app/main/lib/config.php
rename to app/Lib/Config.php
index c87db59b..000b28c7 100644
--- a/app/main/lib/config.php
+++ b/app/Lib/Config.php
@@ -6,16 +6,16 @@
* Time: 16:05
*/
-namespace lib;
+namespace Exodus4D\Pathfinder\Lib;
-
-use lib\db\Pool;
-use lib\api\CcpClient;
-use lib\api\GitHubClient;
-use lib\api\SsoClient;
-use lib\socket\AbstractSocket;
-use lib\socket\SocketInterface;
-use lib\socket\TcpSocket;
+use Exodus4D\Pathfinder\Lib\Db\Pool;
+use Exodus4D\Pathfinder\Lib\Api\CcpClient;
+use Exodus4D\Pathfinder\Lib\Api\GitHubClient;
+use Exodus4D\Pathfinder\Lib\Api\SsoClient;
+use Exodus4D\Pathfinder\Lib\Api\EveScoutClient;
+use Exodus4D\Pathfinder\Lib\Socket\AbstractSocket;
+use Exodus4D\Pathfinder\Lib\Socket\SocketInterface;
+use Exodus4D\Pathfinder\Lib\Socket\TcpSocket;
class Config extends \Prefab {
@@ -39,6 +39,11 @@ class Config extends \Prefab {
*/
const HIVE_KEY_ENVIRONMENT = 'ENVIRONMENT';
+ /**
+ * Hive key for custom plugins (js map modules)
+ */
+ const HIVE_KEY_PLUGIN = 'PLUGIN';
+
/**
* Hive key for Socket validation check
*/
@@ -127,7 +132,7 @@ class Config extends \Prefab {
* custom HTTP status codes
*/
const
- HTTP_422='Unprocessable Entity';
+ HTTP_422 = 'Unprocessable Entity';
/**
* all environment data
@@ -177,6 +182,7 @@ class Config extends \Prefab {
$f3->set(SsoClient::CLIENT_NAME, SsoClient::instance());
$f3->set(CcpClient::CLIENT_NAME, CcpClient::instance());
$f3->set(GitHubClient::CLIENT_NAME, GitHubClient::instance());
+ $f3->set(EveScoutClient::CLIENT_NAME, EveScoutClient::instance());
// Socket connectors ------------------------------------------------------------------------------------------
$f3->set(TcpSocket::SOCKET_NAME, function(array $options = ['timeout' => 1]) : SocketInterface {
@@ -373,7 +379,7 @@ class Config extends \Prefab {
* get SMTP config values
* @return \stdClass
*/
- static function getSMTPConfig(): \stdClass{
+ static function getSMTPConfig() : \stdClass{
$config = new \stdClass();
$config->host = self::getEnvironmentData('SMTP_HOST');
$config->port = self::getEnvironmentData('SMTP_PORT');
@@ -391,9 +397,9 @@ class Config extends \Prefab {
* @param \stdClass $config
* @return bool
*/
- static function isValidSMTPConfig(\stdClass $config): bool {
+ static function isValidSMTPConfig(\stdClass $config) : bool {
// validate email from either an configured array or plain string
- $validateMailConfig = function($mailConf = null): bool {
+ $validateMailConfig = function($mailConf = null) : bool {
$email = null;
if(is_array($mailConf)){
reset($mailConf);
@@ -436,19 +442,25 @@ class Config extends \Prefab {
}
/**
- * get custom $message for a a HTTP $status
- * -> use this in addition to the very general Base::HTTP_XXX labels
- * @param int $status
- * @return string
+ * get Plugin config from `plugin.ini`
+ * @param string|null $key
+ * @param bool $checkEnabled
+ * @return array|null
*/
- static function getMessageFromHTTPStatus(int $status): string {
- switch($status){
- case 403:
- $message = 'Access denied: User not found'; break;
- default:
- $message = '';
+ static function getPluginConfig(?string $key, bool $checkEnabled = true) : ?array {
+ $isEnabled = $checkEnabled ?
+ filter_var(\Base::instance()->get(
+ self::HIVE_KEY_PLUGIN . '.' . strtoupper($key) . '_ENABLED'),
+ FILTER_VALIDATE_BOOLEAN
+ ) :
+ true;
+
+ $data = null;
+ if($isEnabled){
+ $hiveKey = self::HIVE_KEY_PLUGIN . '.' . strtoupper($key);
+ $data = (array)\Base::instance()->get($hiveKey);
}
- return $message;
+ return $data;
}
/**
@@ -541,7 +553,7 @@ class Config extends \Prefab {
}
/**
- * get HTTP status message by HTTP return code
+ * get HTTP status by HTTP return code
* -> either from F3 or from self::Config constants
* @param int $code
* @return string
@@ -568,7 +580,7 @@ class Config extends \Prefab {
if($matches = (bool)preg_match('/^(\w+)\h*=\h*(.+)/', strtolower(trim($dsn)), $parts)){
$conf['type'] = $parts[1];
if($conf['type'] == 'redis'){
- list($conf['host'], $conf['port'], $conf['db']) = explode(':', $parts[2]) + [1 => 6379, 2 => null];
+ [$conf['host'], $conf['port'], $conf['db'], $conf['auth']] = explode(':', $parts[2]) + [1 => 6379, 2 => null, 3 => null];
}elseif($conf['type'] == 'folder'){
$conf['folder'] = $parts[2];
}
@@ -640,6 +652,11 @@ class Config extends \Prefab {
return $format;
}
+ /**
+ * @param $fromExists
+ * @param int $ttlMax
+ * @return int
+ */
static function ttlLeft($fromExists, int $ttlMax) : int {
$ttlMax = max($ttlMax, 0);
if($fromExists){
@@ -654,4 +671,16 @@ class Config extends \Prefab {
return $ttlMax;
}
}
+
+ /**
+ * @param string|null $class
+ * @return string
+ */
+ static function withNamespace(?string $class) : string {
+ $path = [\Base::instance()->get('NAMESPACE')];
+ if($class){
+ $path[] = $class;
+ }
+ return implode('\\', $path);
+ }
}
\ No newline at end of file
diff --git a/app/main/lib/Cron.php b/app/Lib/Cron.php
similarity index 86%
rename from app/main/lib/Cron.php
rename to app/Lib/Cron.php
index ae5d69e1..026e8261 100644
--- a/app/main/lib/Cron.php
+++ b/app/Lib/Cron.php
@@ -1,9 +1,9 @@
getJob($name)){
- if($job->dry()){
- $job->name = $name;
+ // method is called from /setup page -> DB might not be created at this point!
+ // -> check if DB exists here. Otherwise Cortex()->__construct()
+ \Base::instance()->DB->setSilent(true);
+ if(\Base::instance()->DB->getDB(Pathfinder\AbstractPathfinderModel::DB_ALIAS)){
+ if($job = $this->getJob($name)){
+ if($job->dry()){
+ $job->name = $name;
+ }
+ $job->setData($jobConf);
+ return $job->save();
}
- $job->setData($jobConf);
- return $job->save();
}
+ \Base::instance()->DB->setSilent(false);
}
/**
diff --git a/app/main/lib/DateRange.php b/app/Lib/DateRange.php
similarity index 92%
rename from app/main/lib/DateRange.php
rename to app/Lib/DateRange.php
index 3327ebb6..f349c7f1 100644
--- a/app/main/lib/DateRange.php
+++ b/app/Lib/DateRange.php
@@ -6,9 +6,9 @@
* Time: 18:06
*/
-namespace lib;
+namespace Exodus4D\Pathfinder\Lib;
-use Exception\DateException;
+use Exodus4D\Pathfinder\Exception\DateException;
class DateRange {
diff --git a/app/main/lib/db/Pool.php b/app/Lib/Db/Pool.php
similarity index 92%
rename from app/main/lib/db/Pool.php
rename to app/Lib/Db/Pool.php
index 2a415f92..3798ea90 100644
--- a/app/main/lib/db/Pool.php
+++ b/app/Lib/Db/Pool.php
@@ -1,12 +1,12 @@
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
+ * @return Sql|null
*/
- public function connectToServer(string $alias) : ?SQL {
+ public function connectToServer(string $alias) : ?Sql {
$config = ($this->getConfig)($alias);
$config['NAME'] = '';
return $this->newDB($config);
@@ -95,9 +95,9 @@ class Pool extends \Prefab {
* tries to create a database if not exists
* -> DB user needs rights to create a DB
* @param string $alias
- * @return SQL|null
+ * @return Sql|null
*/
- public function createDB(string $alias) : ?SQL {
+ public function createDB(string $alias) : ?Sql {
$db = null;
$config = ($this->getConfig)($alias);
// remove database from $dsn (we want to crate it)
@@ -135,9 +135,9 @@ class Pool extends \Prefab {
/**
* get active connection from store or init new connection
* @param string $alias
- * @return SQL|null
+ * @return Sql|null
*/
- public function getDB(string $alias) : ?SQL {
+ public function getDB(string $alias) : ?Sql {
if(!isset($this->connectionStore[$alias])){
$db = $this->newDB(($this->getConfig)($alias));
if(!is_null($db)){
@@ -175,14 +175,14 @@ class Pool extends \Prefab {
/**
* @param array $config
- * @return SQL|null
+ * @return Sql|null
*/
- protected function newDB(array $config) : ?SQL {
+ 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']);
+ $db = new Sql($this->buildDnsFromConfig($config), $config['USER'], $config['PASS'], $config['OPTIONS']);
}catch(\PDOException $e){
$this->pushError($config['ALIAS'], $e);
diff --git a/app/main/lib/db/SQL.php b/app/Lib/Db/Sql.php
similarity index 97%
rename from app/main/lib/db/SQL.php
rename to app/Lib/Db/Sql.php
index 6ffc629f..3153e4ac 100644
--- a/app/main/lib/db/SQL.php
+++ b/app/Lib/Db/Sql.php
@@ -1,12 +1,12 @@
see $processorConfig end getProcessorParams()
+ * @var array
+ */
+ protected $processorParamsConfig = [
+ 'psr' => ['Y-m-d\A\TH:i:s.uP', false]
+ ];
+
/**
* multiple Log() objects can be marked as "grouped"
* -> Logs with Slack Handler should be grouped by map (send multiple log data in once
@@ -110,6 +144,10 @@ abstract class AbstractLog implements LogInterface {
private $buffer = true;
+ /**
+ * AbstractLog constructor.
+ * @param string $action
+ */
public function __construct(string $action){
$this->setF3();
$this->action = $action;
@@ -176,7 +214,7 @@ abstract class AbstractLog implements LogInterface {
* @param array $data
* @return LogInterface
*/
- public function setData(array $data) : LogInterface{
+ public function setData(array $data) : LogInterface {
$this->data = $data;
return $this;
}
@@ -185,7 +223,7 @@ abstract class AbstractLog implements LogInterface {
* @param array $data
* @return LogInterface
*/
- public function setTempData(array $data) : LogInterface{
+ public function setTempData(array $data) : LogInterface {
$this->tmpData = $data;
return $this;
}
@@ -227,7 +265,7 @@ abstract class AbstractLog implements LogInterface {
/**
* @return array
*/
- public function getHandlerConfig() : array{
+ public function getHandlerConfig() : array {
return $this->handlerConfig;
}
@@ -238,8 +276,6 @@ abstract class AbstractLog implements LogInterface {
* @throws \Exception
*/
public function getHandlerParams(string $handlerKey) : array {
- $params = [];
-
if($this->hasHandlerKey($handlerKey)){
switch($handlerKey){
case 'stream': $params = $this->getHandlerParamsStream();
@@ -255,10 +291,10 @@ abstract class AbstractLog implements LogInterface {
$params = $this->getHandlerParamsSlack($handlerKey);
break;
default:
- throw new \Exception( sprintf(self::ERROR_HANDLER_PARAMS, $handlerKey));
+ throw new \Exception(sprintf(self::ERROR_HANDLER_PARAMS, $handlerKey));
}
}else{
- throw new \Exception( sprintf(self::ERROR_HANDLER_KEY, $handlerKey, implode(', ', array_flip($this->handlerConfig))));
+ throw new \Exception(sprintf(self::ERROR_HANDLER_KEY, $handlerKey, implode(', ', array_flip($this->handlerConfig))));
}
return $params;
@@ -278,58 +314,79 @@ abstract class AbstractLog implements LogInterface {
return $this->processorConfig;
}
+ /**
+ * get __construct() parameters for a given $processorKey
+ * @param string $processorKey
+ * @return array
+ * @throws \Exception
+ */
+ public function getProcessorParams(string $processorKey) : array {
+ if($this->hasProcessorKey($processorKey)){
+ switch($processorKey){
+ case 'psr': $params = $this->getProcessorParamsPsr();
+ break;
+ default:
+ throw new \Exception(sprintf(self::ERROR_PROCESSOR_PARAMS, $processorKey));
+ }
+ }else{
+ throw new \Exception(sprintf(self::ERROR_PROCESSOR_KEY, $processorKey, implode(', ', array_flip($this->processorConfig))));
+ }
+
+ return $params;
+ }
+
/**
* @return string
*/
- public function getMessage() : string{
+ public function getMessage() : string {
return $this->message;
}
/**
* @return string
*/
- public function getAction() : string{
+ public function getAction() : string {
return $this->action;
}
/**
* @return string
*/
- public function getChannelType() : string{
+ public function getChannelType() : string {
return $this->channelType;
}
/**
* @return string
*/
- public function getChannelName() : string{
+ public function getChannelName() : string {
return $this->getChannelType();
}
/**
* @return string
*/
- public function getLevel() : string{
+ public function getLevel() : string {
return $this->level;
}
/**
* @return string
*/
- public function getTag() : string{
+ public function getTag() : string {
return $this->tag;
}
/**
* @return array
*/
- public function getData() : array{
+ public function getData() : array {
return $this->data;
}
/**
* @return array
*/
- public function getContext() : array{
+ public function getContext() : array {
$context = [
'data' => $this->getData(),
'tag' => $this->getTag()
@@ -351,7 +408,7 @@ abstract class AbstractLog implements LogInterface {
/**
* @return array
*/
- public function getHandlerGroups() : array{
+ public function getHandlerGroups() : array {
return $this->handlerGroups;
}
@@ -372,7 +429,7 @@ abstract class AbstractLog implements LogInterface {
* @param string $handlerKey
* @return bool
*/
- public function hasHandlerKey(string $handlerKey) : bool{
+ public function hasHandlerKey(string $handlerKey) : bool {
return array_key_exists($handlerKey, $this->handlerConfig);
}
@@ -380,21 +437,29 @@ abstract class AbstractLog implements LogInterface {
* @param string $handlerKey
* @return bool
*/
- public function hasHandlerGroupKey(string $handlerKey) : bool{
+ public function hasHandlerGroupKey(string $handlerKey) : bool {
return in_array($handlerKey, $this->getHandlerGroups());
}
+ /**
+ * @param string $processorKey
+ * @return bool
+ */
+ public function hasProcessorKey(string $processorKey) : bool {
+ return array_key_exists($processorKey, $this->processorConfig);
+ }
+
/**
* @return bool
*/
- public function hasBuffer() : bool{
+ public function hasBuffer() : bool {
return $this->buffer;
}
/**
* @return bool
*/
- public function isGrouped() : bool{
+ public function isGrouped() : bool {
return !empty($this->getHandlerGroups());
}
@@ -415,12 +480,12 @@ abstract class AbstractLog implements LogInterface {
unset($this->handlerParamsConfig[$handlerKey]);
}
- // Handler parameters for Monolog\Handler\AbstractHandler ---------------------------------------------------------
+ // Handler parameters for Monolog\Handler\* instances -------------------------------------------------------------
/**
* @return array
*/
- protected function getHandlerParamsStream() : array{
+ protected function getHandlerParamsStream() : array {
$params = [];
if( !empty($conf = $this->handlerParamsConfig['stream']) ){
$params[] = $conf->stream;
@@ -541,6 +606,16 @@ abstract class AbstractLog implements LogInterface {
return $params;
}
+ // Processor parameters for Monolog\Processor\* instances ---------------------------------------------------------
+
+ /**
+ * get __construct() params for PsrLogMessageProcessor() call
+ * @return array
+ */
+ protected function getProcessorParamsPsr() : array {
+ return !empty($conf = $this->processorParamsConfig['psr']) ? $conf : [];
+ }
+
/**
* send this Log to global log buffer storage
*/
diff --git a/app/main/lib/logging/ApiLog.php b/app/Lib/Logging/ApiLog.php
similarity index 81%
rename from app/main/lib/logging/ApiLog.php
rename to app/Lib/Logging/ApiLog.php
index f92943f8..bfb9183e 100644
--- a/app/main/lib/logging/ApiLog.php
+++ b/app/Lib/Logging/ApiLog.php
@@ -6,7 +6,7 @@
* Time: 16:42
*/
-namespace lib\logging;
+namespace Exodus4D\Pathfinder\Lib\Logging;
class ApiLog extends AbstractLog {
@@ -20,8 +20,17 @@ class ApiLog extends AbstractLog {
//'stream' => 'json'
];
+ /**
+ * @var string
+ */
protected $channelType = 'api';
+ /**
+ * ApiLog constructor.
+ * @param string $action
+ * @param string $level
+ * @throws \Exception
+ */
public function __construct(string $action, string $level){
parent::__construct($action);
diff --git a/app/main/lib/logging/DefaultLog.php b/app/Lib/Logging/DefaultLog.php
similarity index 83%
rename from app/main/lib/logging/DefaultLog.php
rename to app/Lib/Logging/DefaultLog.php
index 885917d5..6a23a2ae 100644
--- a/app/main/lib/logging/DefaultLog.php
+++ b/app/Lib/Logging/DefaultLog.php
@@ -6,7 +6,7 @@
* Time: 22:08
*/
-namespace lib\logging;
+namespace Exodus4D\Pathfinder\Lib\Logging;
class DefaultLog extends AbstractLog {
diff --git a/app/main/lib/logging/formatter/MailFormatter.php b/app/Lib/Logging/Formatter/MailFormatter.php
similarity index 84%
rename from app/main/lib/logging/formatter/MailFormatter.php
rename to app/Lib/Logging/Formatter/MailFormatter.php
index 042872d4..dc990bd3 100644
--- a/app/main/lib/logging/formatter/MailFormatter.php
+++ b/app/Lib/Logging/Formatter/MailFormatter.php
@@ -6,13 +6,17 @@
* Time: 14:49
*/
-namespace lib\logging\formatter;
+namespace Exodus4D\Pathfinder\Lib\Logging\Formatter;
-use lib\Config;
+use Exodus4D\Pathfinder\Lib\Config;
use Monolog\Formatter;
class MailFormatter implements Formatter\FormatterInterface {
+ /**
+ * @param array $record
+ * @return mixed|string
+ */
public function format(array $record){
$tplDefaultData = [
@@ -34,6 +38,10 @@ class MailFormatter implements Formatter\FormatterInterface {
return \Template::instance()->render('templates/mail/basic_inline.html', 'text/html', $tplData);
}
+ /**
+ * @param array $records
+ * @return mixed|string
+ */
public function formatBatch(array $records){
$message = '';
foreach ($records as $key => $record) {
diff --git a/app/main/lib/logging/handler/AbstractMapWebhookHandler.php b/app/Lib/Logging/Handler/AbstractMapWebhookHandler.php
similarity index 97%
rename from app/main/lib/logging/handler/AbstractMapWebhookHandler.php
rename to app/Lib/Logging/Handler/AbstractMapWebhookHandler.php
index 0a01ff32..2e34095d 100644
--- a/app/main/lib/logging/handler/AbstractMapWebhookHandler.php
+++ b/app/Lib/Logging/Handler/AbstractMapWebhookHandler.php
@@ -6,9 +6,9 @@
* Time: 10:18
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
-use lib\Util;
+use Exodus4D\Pathfinder\Lib\Util;
abstract class AbstractMapWebhookHandler extends AbstractWebhookHandler {
diff --git a/app/main/lib/logging/handler/AbstractRallyWebhookHandler.php b/app/Lib/Logging/Handler/AbstractRallyWebhookHandler.php
similarity index 98%
rename from app/main/lib/logging/handler/AbstractRallyWebhookHandler.php
rename to app/Lib/Logging/Handler/AbstractRallyWebhookHandler.php
index f77d4dd2..c8ca5ddf 100644
--- a/app/main/lib/logging/handler/AbstractRallyWebhookHandler.php
+++ b/app/Lib/Logging/Handler/AbstractRallyWebhookHandler.php
@@ -6,10 +6,10 @@
* Time: 10:09
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
use League\HTMLToMarkdown\HtmlConverter;
-use lib\Util;
+use Exodus4D\Pathfinder\Lib\Util;
abstract class AbstractRallyWebhookHandler extends AbstractWebhookHandler {
@@ -150,7 +150,6 @@ abstract class AbstractRallyWebhookHandler extends AbstractWebhookHandler {
protected function htmlToMarkdown($html){
$converter = new HtmlConverter();
$converter->getConfig()->setOption('strip_tags', true);
- $markdown = $converter->convert($html);
- return $markdown;
+ return $converter->convert($html);
}
}
\ No newline at end of file
diff --git a/app/main/lib/logging/handler/AbstractWebhookHandler.php b/app/Lib/Logging/Handler/AbstractWebhookHandler.php
similarity index 98%
rename from app/main/lib/logging/handler/AbstractWebhookHandler.php
rename to app/Lib/Logging/Handler/AbstractWebhookHandler.php
index 2bfaca53..50869218 100644
--- a/app/main/lib/logging/handler/AbstractWebhookHandler.php
+++ b/app/Lib/Logging/Handler/AbstractWebhookHandler.php
@@ -6,9 +6,9 @@
* Time: 20:08
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
-use lib\Config;
+use Exodus4D\Pathfinder\Lib\Config;
use Monolog\Handler;
use Monolog\Logger;
@@ -127,7 +127,7 @@ abstract class AbstractWebhookHandler extends Handler\AbstractProcessingHandler
*
* @param array $record
*/
- protected function write(array $record){
+ protected function write(array $record) : void {
$record = $this->excludeFields($record);
$postData = $this->getSlackData($record);
diff --git a/app/main/lib/logging/handler/DiscordMapWebhookHandler.php b/app/Lib/Logging/Handler/DiscordMapWebhookHandler.php
similarity index 76%
rename from app/main/lib/logging/handler/DiscordMapWebhookHandler.php
rename to app/Lib/Logging/Handler/DiscordMapWebhookHandler.php
index 1c6b34c0..41f8c1a9 100644
--- a/app/main/lib/logging/handler/DiscordMapWebhookHandler.php
+++ b/app/Lib/Logging/Handler/DiscordMapWebhookHandler.php
@@ -6,7 +6,7 @@
* Time: 10:23
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
class DiscordMapWebhookHandler extends AbstractMapWebhookHandler {
diff --git a/app/main/lib/logging/handler/DiscordRallyWebhookHandler.php b/app/Lib/Logging/Handler/DiscordRallyWebhookHandler.php
similarity index 78%
rename from app/main/lib/logging/handler/DiscordRallyWebhookHandler.php
rename to app/Lib/Logging/Handler/DiscordRallyWebhookHandler.php
index 1078d65e..8ed8d986 100644
--- a/app/main/lib/logging/handler/DiscordRallyWebhookHandler.php
+++ b/app/Lib/Logging/Handler/DiscordRallyWebhookHandler.php
@@ -6,11 +6,15 @@
* Time: 10:13
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
class DiscordRallyWebhookHandler extends AbstractRallyWebhookHandler {
+ /**
+ * @param $html
+ * @return string
+ */
protected function htmlToMarkdown($html){
$markdown = parent::htmlToMarkdown($html);
// Discord supports syntax highlighting for MarkDown
diff --git a/app/main/lib/logging/handler/SlackMapWebhookHandler.php b/app/Lib/Logging/Handler/SlackMapWebhookHandler.php
similarity index 76%
rename from app/main/lib/logging/handler/SlackMapWebhookHandler.php
rename to app/Lib/Logging/Handler/SlackMapWebhookHandler.php
index 72406c81..bff2a7f8 100644
--- a/app/main/lib/logging/handler/SlackMapWebhookHandler.php
+++ b/app/Lib/Logging/Handler/SlackMapWebhookHandler.php
@@ -6,9 +6,9 @@
* Time: 20:52
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
+
class SlackMapWebhookHandler extends AbstractMapWebhookHandler {
-
}
\ No newline at end of file
diff --git a/app/main/lib/logging/handler/SlackRallyWebhookHandler.php b/app/Lib/Logging/Handler/SlackRallyWebhookHandler.php
similarity index 76%
rename from app/main/lib/logging/handler/SlackRallyWebhookHandler.php
rename to app/Lib/Logging/Handler/SlackRallyWebhookHandler.php
index 319a7091..e90e2d31 100644
--- a/app/main/lib/logging/handler/SlackRallyWebhookHandler.php
+++ b/app/Lib/Logging/Handler/SlackRallyWebhookHandler.php
@@ -6,12 +6,9 @@
* Time: 17:32
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
class SlackRallyWebhookHandler extends AbstractRallyWebhookHandler {
-
-
-
}
\ No newline at end of file
diff --git a/app/main/lib/logging/handler/SocketHandler.php b/app/Lib/Logging/Handler/SocketHandler.php
similarity index 81%
rename from app/main/lib/logging/handler/SocketHandler.php
rename to app/Lib/Logging/Handler/SocketHandler.php
index 24d2b9fb..071d87e9 100644
--- a/app/main/lib/logging/handler/SocketHandler.php
+++ b/app/Lib/Logging/Handler/SocketHandler.php
@@ -6,7 +6,7 @@
* Time: 19:11
*/
-namespace lib\logging\handler;
+namespace Exodus4D\Pathfinder\Lib\Logging\Handler;
use Monolog\Logger;
@@ -19,6 +19,13 @@ class SocketHandler extends \Monolog\Handler\SocketHandler {
*/
protected $metaData = [];
+ /**
+ * SocketHandler constructor.
+ * @param $connectionString
+ * @param int $level
+ * @param bool $bubble
+ * @param array $metaData
+ */
public function __construct($connectionString, $level = Logger::DEBUG, $bubble = true, $metaData = []){
$this->metaData = $metaData;
@@ -31,7 +38,7 @@ class SocketHandler extends \Monolog\Handler\SocketHandler {
* @param array $record
* @return bool
*/
- public function handle(array $record){
+ public function handle(array $record) : bool {
if (!$this->isHandling($record)) {
return false;
}
diff --git a/app/main/lib/logging/LogCollection.php b/app/Lib/Logging/LogCollection.php
similarity index 97%
rename from app/main/lib/logging/LogCollection.php
rename to app/Lib/Logging/LogCollection.php
index 5e8ea48b..721a3972 100644
--- a/app/main/lib/logging/LogCollection.php
+++ b/app/Lib/Logging/LogCollection.php
@@ -6,7 +6,7 @@
* Time: 11:23
*/
-namespace lib\logging;
+namespace Exodus4D\Pathfinder\Lib\Logging;
class LogCollection extends AbstractLog {
@@ -32,6 +32,10 @@ class LogCollection extends AbstractLog {
*/
private $collection = null;
+ /**
+ * LogCollection constructor.
+ * @param string $action
+ */
public function __construct(string $action){
parent::__construct($action);
diff --git a/app/Lib/Logging/LogInterface.php b/app/Lib/Logging/LogInterface.php
new file mode 100644
index 00000000..e5346dd6
--- /dev/null
+++ b/app/Lib/Logging/LogInterface.php
@@ -0,0 +1,71 @@
+ 'Monolog\Formatter\LineFormatter',
'json' => 'Monolog\Formatter\JsonFormatter',
'html' => 'Monolog\Formatter\HtmlFormatter',
- 'mail' => 'lib\logging\formatter\MailFormatter'
+ 'mail' => 'Exodus4D\Pathfinder\Lib\Logging\Formatter\MailFormatter'
];
+ /**
+ * available handlers
+ */
const HANDLER = [
'stream' => 'Monolog\Handler\StreamHandler',
'mail' => 'Monolog\Handler\SwiftMailerHandler',
- 'socket' => 'lib\logging\handler\SocketHandler',
- 'slackMap' => 'lib\logging\handler\SlackMapWebhookHandler',
- 'slackRally' => 'lib\logging\handler\SlackRallyWebhookHandler',
- 'discordMap' => 'lib\logging\handler\DiscordMapWebhookHandler',
- 'discordRally' => 'lib\logging\handler\DiscordRallyWebhookHandler'
+ 'socket' => 'Exodus4D\Pathfinder\Lib\Logging\Handler\SocketHandler',
+ 'slackMap' => 'Exodus4D\Pathfinder\Lib\Logging\Handler\SlackMapWebhookHandler',
+ 'slackRally' => 'Exodus4D\Pathfinder\Lib\Logging\Handler\SlackRallyWebhookHandler',
+ 'discordMap' => 'Exodus4D\Pathfinder\Lib\Logging\Handler\DiscordMapWebhookHandler',
+ 'discordRally' => 'Exodus4D\Pathfinder\Lib\Logging\Handler\DiscordRallyWebhookHandler'
];
+ /**
+ * available processors
+ */
const PROCESSOR = [
'psr' => 'Monolog\Processor\PsrLogMessageProcessor'
];
@@ -54,12 +75,7 @@ class Monolog extends \Prefab {
];
public function __construct(){
- // set timezone for all Logger instances
- if(class_exists(Logger::class)){
- if( is_callable($getTimezone = \Base::instance()->get('getTimeZone')) ){
- Logger::setTimezone($getTimezone());
- };
- }else{
+ if(!class_exists(Logger::class)){
LogController::getLogger('ERROR')->write(sprintf(Config::ERROR_CLASS_NOT_EXISTS_COMPOSER, Logger::class));
}
}
@@ -107,6 +123,10 @@ class Monolog extends \Prefab {
}else{
$logger = new Logger($log->getChannelName());
+ if(is_callable($getTimezone = \Base::instance()->get('getTimeZone'))){
+ $logger->setTimezone($getTimezone());
+ }
+
// disable microsecond timestamps (seconds should be fine)
$logger->useMicrosecondTimestamps(true);
@@ -143,7 +163,8 @@ class Monolog extends \Prefab {
$logger->pushProcessor($processorCallback);
}else{
// get Monolog Processor class
- $processor = $this->getProcessor($processorKey);
+ $processorParams = $log->getProcessorParams($processorKey);
+ $processor = $this->getProcessor($processorKey, $processorParams);
$logger->pushProcessor($processor);
}
}
@@ -187,7 +208,7 @@ class Monolog extends \Prefab {
* @return HandlerInterface
* @throws \Exception
*/
- private function getHandler(string $handlerKey, array $handlerParams = []): HandlerInterface{
+ private function getHandler(string $handlerKey, array $handlerParams = []) : HandlerInterface{
if(array_key_exists($handlerKey, self::HANDLER)){
$handlerClass = self::HANDLER[$handlerKey];
$handler = new $handlerClass(...$handlerParams);
@@ -201,13 +222,14 @@ class Monolog extends \Prefab {
/**
* get Monolog Processor instance by key
* @param string $processorKey
- * @return callable
+ * @param array $processorParams
+ * @return ProcessorInterface
* @throws \Exception
*/
- private function getProcessor(string $processorKey): callable {
+ private function getProcessor(string $processorKey, array $processorParams = []) : ProcessorInterface {
if(array_key_exists($processorKey, self::PROCESSOR)){
$ProcessorClass = self::PROCESSOR[$processorKey];
- $processor = new $ProcessorClass();
+ $processor = new $ProcessorClass(...$processorParams);
}else{
throw new \Exception(sprintf(self::ERROR_PROCESSOR, $processorKey));
}
diff --git a/app/main/lib/PriorityCacheStore.php b/app/Lib/PriorityCacheStore.php
similarity index 98%
rename from app/main/lib/PriorityCacheStore.php
rename to app/Lib/PriorityCacheStore.php
index 740d0a32..85add008 100644
--- a/app/main/lib/PriorityCacheStore.php
+++ b/app/Lib/PriorityCacheStore.php
@@ -1,7 +1,7 @@
'style',
- 'script' => 'script',
- 'font' => 'font',
- 'document' => 'document',
- 'image' => 'image',
- 'url' => ''
+ 'style' => 'style',
+ 'script' => 'script',
+ 'font' => 'font',
+ 'document' => 'document',
+ 'image' => 'image',
+ 'url' => ''
];
/**
* default link "type" attributes
*/
const ATTR_TYPE = [
- 'font' => 'font/woff2'
+ 'font' => 'font/woff2'
];
/**
* default additional attributes by $group
*/
const ATTR_ADD = [
- 'font' => ['crossorigin' => 'anonymous']
+ 'font' => ['crossorigin' => 'anonymous']
];
+ /**
+ * BASE path
+ * @var string
+ */
+ private $basePath = '';
+
/**
* absolute file path -> use setOption() for update
* @var array
*/
private $filePath = [
- 'style' => '',
- 'script' => '',
- 'font' => '',
- 'document' => '',
- 'image' => '',
- 'url' => ''
+ 'style' => '',
+ 'script' => '',
+ 'font' => '',
+ 'document' => '',
+ 'image' => '',
+ 'favicon' => '',
+ 'url' => ''
];
/**
@@ -62,10 +69,10 @@ class Resource extends \Prefab {
* @var array
*/
private $fileExt = [
- 'style' => 'css',
- 'script' => 'js',
- 'document' => 'html',
- 'font' => 'woff2'
+ 'style' => 'css',
+ 'script' => 'js',
+ 'document' => 'html',
+ 'font' => 'woff2'
];
/**
@@ -76,7 +83,7 @@ class Resource extends \Prefab {
* @see buildHeader()
* @var string
*/
- private $output = 'inline';
+ private $output = 'inline';
/**
* resource file cache
@@ -134,7 +141,7 @@ class Resource extends \Prefab {
* @return string
*/
public function getPath(string $group) : string {
- return $this->filePath[$group];
+ return rtrim($this->basePath, '/\\') . $this->filePath[$group];
}
/**
diff --git a/app/main/lib/socket/AbstractSocket.php b/app/Lib/Socket/AbstractSocket.php
similarity index 99%
rename from app/main/lib/socket/AbstractSocket.php
rename to app/Lib/Socket/AbstractSocket.php
index 90c79419..94daba1d 100644
--- a/app/main/lib/socket/AbstractSocket.php
+++ b/app/Lib/Socket/AbstractSocket.php
@@ -6,7 +6,7 @@
* Time: 19:13
*/
-namespace lib\socket;
+namespace Exodus4D\Pathfinder\Lib\Socket;
use React\EventLoop;
@@ -237,12 +237,10 @@ abstract class AbstractSocket implements SocketInterface {
* @return array
*/
protected function newPayload(string $task, $load = null) : array {
- $payload = [
+ return [
'task' => $task,
'load' => $load
];
-
- return $payload;
}
/**
diff --git a/app/main/lib/socket/NullSocket.php b/app/Lib/Socket/NullSocket.php
similarity index 94%
rename from app/main/lib/socket/NullSocket.php
rename to app/Lib/Socket/NullSocket.php
index 9b60e3cb..7702f642 100644
--- a/app/main/lib/socket/NullSocket.php
+++ b/app/Lib/Socket/NullSocket.php
@@ -6,7 +6,7 @@
* Time: 23:22
*/
-namespace lib\socket;
+namespace Exodus4D\Pathfinder\Lib\Socket;
use React\Socket;
diff --git a/app/main/lib/socket/SocketInterface.php b/app/Lib/Socket/SocketInterface.php
similarity index 93%
rename from app/main/lib/socket/SocketInterface.php
rename to app/Lib/Socket/SocketInterface.php
index e56bf33d..238c97a9 100644
--- a/app/main/lib/socket/SocketInterface.php
+++ b/app/Lib/Socket/SocketInterface.php
@@ -6,10 +6,9 @@
* Time: 11:26
*/
-namespace lib\socket;
+namespace Exodus4D\Pathfinder\Lib\Socket;
-use React\EventLoop;
use React\Promise;
interface SocketInterface {
diff --git a/app/main/lib/socket/TcpSocket.php b/app/Lib/Socket/TcpSocket.php
similarity index 91%
rename from app/main/lib/socket/TcpSocket.php
rename to app/Lib/Socket/TcpSocket.php
index 68dbb875..651a79db 100644
--- a/app/main/lib/socket/TcpSocket.php
+++ b/app/Lib/Socket/TcpSocket.php
@@ -6,7 +6,7 @@
* Time: 10:04
*/
-namespace lib\socket;
+namespace Exodus4D\Pathfinder\Lib\Socket;
use React\Socket;
diff --git a/app/main/lib/util.php b/app/Lib/Util.php
similarity index 99%
rename from app/main/lib/util.php
rename to app/Lib/Util.php
index 8d031de6..ec9d3324 100644
--- a/app/main/lib/util.php
+++ b/app/Lib/Util.php
@@ -6,7 +6,8 @@
* Time: 17:32
*/
-namespace lib;
+namespace Exodus4D\Pathfinder\Lib;
+
class Util {
diff --git a/app/main/model/abstractmodel.php b/app/Model/AbstractModell.php
similarity index 98%
rename from app/main/model/abstractmodel.php
rename to app/Model/AbstractModell.php
index 42411ede..f87e8ad5 100644
--- a/app/main/model/abstractmodel.php
+++ b/app/Model/AbstractModell.php
@@ -6,16 +6,17 @@
* Time: 22:11
*/
-namespace Model;
+namespace Exodus4D\Pathfinder\Model;
use DB\Cortex;
use DB\CortexCollection;
use DB\SQL\Schema;
-use lib\Util;
-use lib\logging;
-use Controller;
-use Exception\ValidationException;
-use Exception\DatabaseException;
+use Exodus4D\Pathfinder\Lib\Util;
+use Exodus4D\Pathfinder\Lib\Logging;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Db\Sql\Mysql;
+use Exodus4D\Pathfinder\Exception\ValidationException;
+use Exodus4D\Pathfinder\Exception\DatabaseException;
abstract class AbstractModel extends Cortex {
@@ -326,7 +327,7 @@ abstract class AbstractModel extends Cortex {
$valid = $this->$method($key, $val);
}else{
self::getF3()->error(501, 'Method ' . get_class($this) . '->' . $method . '() is not implemented');
- };
+ }
}
}
@@ -1053,13 +1054,12 @@ abstract class AbstractModel extends Cortex {
/**
* get tableModifier class for this table
- * @return bool|\DB\SQL\TableModifier
+ * @return bool|Mysql\TableModifier
*/
public static function getTableModifier(){
$df = parent::resolveConfiguration();
$schema = new Schema($df['db']);
- $tableModifier = $schema->alterTable($df['table']);
- return $tableModifier;
+ return $schema->alterTable($df['table']);
}
/**
diff --git a/app/main/model/pathfinder/abstractmaptrackingmodel.php b/app/Model/Pathfinder/AbstractMapTrackingModel.php
similarity index 90%
rename from app/main/model/pathfinder/abstractmaptrackingmodel.php
rename to app/Model/Pathfinder/AbstractMapTrackingModel.php
index 8f4b65cf..510a86a8 100644
--- a/app/main/model/pathfinder/abstractmaptrackingmodel.php
+++ b/app/Model/Pathfinder/AbstractMapTrackingModel.php
@@ -6,9 +6,10 @@
* Time: 18:45
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
+use Exodus4D\Pathfinder\Exception;
abstract class AbstractMapTrackingModel extends AbstractPathfinderModel implements LogModelInterface {
@@ -19,7 +20,7 @@ abstract class AbstractMapTrackingModel extends AbstractPathfinderModel implemen
'createdCharacterId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CharacterModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel',
'constraint' => [
[
'table' => 'character',
@@ -31,7 +32,7 @@ abstract class AbstractMapTrackingModel extends AbstractPathfinderModel implemen
'updatedCharacterId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CharacterModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel',
'constraint' => [
[
'table' => 'character',
@@ -70,7 +71,7 @@ abstract class AbstractMapTrackingModel extends AbstractPathfinderModel implemen
/**
* validates all required columns of this class
* @return bool
- * @throws \Exception\DatabaseException
+ * @throws Exception\DatabaseException
*/
public function isValid(): bool {
if($valid = parent::isValid()){
diff --git a/app/main/model/pathfinder/abstractpathfindermodel.php b/app/Model/Pathfinder/AbstractPathfinderModell.php
similarity index 84%
rename from app/main/model/pathfinder/abstractpathfindermodel.php
rename to app/Model/Pathfinder/AbstractPathfinderModell.php
index bbd7532f..4f487c18 100644
--- a/app/main/model/pathfinder/abstractpathfindermodel.php
+++ b/app/Model/Pathfinder/AbstractPathfinderModell.php
@@ -1,10 +1,9 @@
_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
@@ -79,7 +63,7 @@ abstract class AbstractPathfinderModel extends AbstractModel {
if($this->enableActivityLogging){
// filter fields, where "activity" (changes) should be logged
- $fieldConf = array_filter($this->fieldConf, function($fieldConf, $key) {
+ $fieldConf = array_filter($this->fieldConf, function($fieldConf, $key){
return isset($fieldConf['activity-log']) ? (bool)$fieldConf['activity-log'] : false;
}, ARRAY_FILTER_USE_BOTH);
diff --git a/app/main/model/pathfinder/abstractsystemapibasicmodel.php b/app/Model/Pathfinder/AbstractSystemApiBasicModel.php
similarity index 98%
rename from app/main/model/pathfinder/abstractsystemapibasicmodel.php
rename to app/Model/Pathfinder/AbstractSystemApiBasicModel.php
index b603dd13..89728c64 100644
--- a/app/main/model/pathfinder/abstractsystemapibasicmodel.php
+++ b/app/Model/Pathfinder/AbstractSystemApiBasicModel.php
@@ -6,7 +6,7 @@
* Time: 22:11
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
diff --git a/app/main/model/pathfinder/activitylogmodel.php b/app/Model/Pathfinder/ActivityLogModel.php
similarity index 92%
rename from app/main/model/pathfinder/activitylogmodel.php
rename to app/Model/Pathfinder/ActivityLogModel.php
index efb8631b..bfe47e39 100644
--- a/app/main/model/pathfinder/activitylogmodel.php
+++ b/app/Model/Pathfinder/ActivityLogModel.php
@@ -6,14 +6,20 @@
* Time: 15:11
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class ActivityLogModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'activity_log';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -24,7 +30,7 @@ class ActivityLogModel extends AbstractPathfinderModel {
'characterId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CharacterModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel',
'constraint' => [
[
'table' => 'character',
@@ -35,7 +41,7 @@ class ActivityLogModel extends AbstractPathfinderModel {
'mapId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapModel',
'constraint' => [
[
'table' => 'map',
@@ -129,6 +135,13 @@ class ActivityLogModel extends AbstractPathfinderModel {
],
];
+ /**
+ * ActivityLogModel constructor.
+ * @param null $db
+ * @param null $table
+ * @param null $fluid
+ * @param int $ttl
+ */
public function __construct($db = NULL, $table = NULL, $fluid = NULL, $ttl = 0){
$this->addStaticDateFieldConfig();
diff --git a/app/main/model/pathfinder/alliancemapmodel.php b/app/Model/Pathfinder/AllianceMapModel.php
similarity index 88%
rename from app/main/model/pathfinder/alliancemapmodel.php
rename to app/Model/Pathfinder/AllianceMapModel.php
index 0152b5ff..e13a39de 100644
--- a/app/main/model/pathfinder/alliancemapmodel.php
+++ b/app/Model/Pathfinder/AllianceMapModel.php
@@ -6,7 +6,7 @@
* Time: 20:14
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
@@ -30,7 +30,7 @@ class AllianceMapModel extends AbstractPathfinderModel {
'allianceId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\AllianceModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\AllianceModel',
'constraint' => [
[
'table' => 'alliance',
@@ -41,7 +41,7 @@ class AllianceMapModel extends AbstractPathfinderModel {
'mapId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapModel',
'constraint' => [
[
'table' => 'map',
diff --git a/app/main/model/pathfinder/alliancemodel.php b/app/Model/Pathfinder/AllianceModel.php
similarity index 91%
rename from app/main/model/pathfinder/alliancemodel.php
rename to app/Model/Pathfinder/AllianceModel.php
index 680dcacd..7d9e408d 100644
--- a/app/main/model/pathfinder/alliancemodel.php
+++ b/app/Model/Pathfinder/AllianceModel.php
@@ -6,10 +6,10 @@
* Time: 20:43
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use lib\Config;
+use Exodus4D\Pathfinder\Lib\Config;
class AllianceModel extends AbstractPathfinderModel {
@@ -44,10 +44,10 @@ class AllianceModel extends AbstractPathfinderModel {
'default' => 0
],
'allianceCharacters' => [
- 'has-many' => ['Model\Pathfinder\CharacterModel', 'allianceId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel', 'allianceId']
],
'mapAlliances' => [
- 'has-many' => ['Model\Pathfinder\AllianceMapModel', 'allianceId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\AllianceMapModel', 'allianceId']
]
];
@@ -63,7 +63,7 @@ class AllianceModel extends AbstractPathfinderModel {
$allianceData->shared = $this->shared;
return $allianceData;
- }/** @noinspection PhpHierarchyChecksInspection */
+ }
/**
* Event "Hook" function
@@ -150,7 +150,7 @@ class AllianceModel extends AbstractPathfinderModel {
$loaded = parent::getById($id, $ttl, $isActive);
if($this->isOutdated()){
// request alliance data
- $allianceData = self::getF3()->ccpClient()->getAllianceData($id);
+ $allianceData = self::getF3()->ccpClient()->send('getAlliance', $id);
if(!empty($allianceData) && !isset($allianceData['error'])){
$this->copyfrom($allianceData, ['id', 'name', 'ticker']);
$this->save();
diff --git a/app/main/model/pathfinder/characterauthenticationmodel.php b/app/Model/Pathfinder/CharacterAuthenticationModel.php
similarity index 87%
rename from app/main/model/pathfinder/characterauthenticationmodel.php
rename to app/Model/Pathfinder/CharacterAuthenticationModel.php
index b80e773b..f73101c5 100644
--- a/app/main/model/pathfinder/characterauthenticationmodel.php
+++ b/app/Model/Pathfinder/CharacterAuthenticationModel.php
@@ -6,15 +6,21 @@
* Time: 19:33
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use Controller;
+use Exodus4D\Pathfinder\Controller;
class CharacterAuthenticationModel extends AbstractPathfinderModel{
+ /**
+ * @var string
+ */
protected $table = 'character_authentication';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -25,7 +31,7 @@ class CharacterAuthenticationModel extends AbstractPathfinderModel{
'characterId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CharacterModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel',
'constraint' => [
[
'table' => 'character',
diff --git a/app/main/model/pathfinder/characterlogmodel.php b/app/Model/Pathfinder/CharacterLogModel.php
similarity index 98%
rename from app/main/model/pathfinder/characterlogmodel.php
rename to app/Model/Pathfinder/CharacterLogModel.php
index 1e4a6b10..82afa5d0 100644
--- a/app/main/model/pathfinder/characterlogmodel.php
+++ b/app/Model/Pathfinder/CharacterLogModel.php
@@ -6,7 +6,7 @@
* Time: 00:04
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
@@ -37,7 +37,7 @@ class CharacterLogModel extends AbstractPathfinderModel {
'type' => Schema::DT_INT,
'index' => true,
'unique' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CharacterModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel',
'constraint' => [
[
'table' => 'character',
diff --git a/app/main/model/pathfinder/charactermapmodel.php b/app/Model/Pathfinder/CharacterMapModel.php
similarity index 84%
rename from app/main/model/pathfinder/charactermapmodel.php
rename to app/Model/Pathfinder/CharacterMapModel.php
index 688ce91e..83428264 100644
--- a/app/main/model/pathfinder/charactermapmodel.php
+++ b/app/Model/Pathfinder/CharacterMapModel.php
@@ -6,14 +6,20 @@
* Time: 12:31
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class CharacterMapModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'character_map';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -24,7 +30,7 @@ class CharacterMapModel extends AbstractPathfinderModel {
'characterId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CharacterModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel',
'constraint' => [
[
'table' => 'character',
@@ -35,7 +41,7 @@ class CharacterMapModel extends AbstractPathfinderModel {
'mapId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapModel',
'constraint' => [
[
'table' => 'map',
diff --git a/app/main/model/pathfinder/charactermodel.php b/app/Model/Pathfinder/CharacterModel.php
similarity index 96%
rename from app/main/model/pathfinder/charactermodel.php
rename to app/Model/Pathfinder/CharacterModel.php
index 49082bf6..ac6af0df 100644
--- a/app/main/model/pathfinder/charactermodel.php
+++ b/app/Model/Pathfinder/CharacterModel.php
@@ -6,13 +6,13 @@
* Time: 15:20
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
-use Controller\Ccp\Sso as Sso;
-use Controller\Api\User as User;
+use Exodus4D\Pathfinder\Controller\Ccp\Sso as Sso;
+use Exodus4D\Pathfinder\Controller\Api\User as User;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
-use lib\Config;
-use Model\Universe;
class CharacterModel extends AbstractPathfinderModel {
@@ -116,7 +116,7 @@ class CharacterModel extends AbstractPathfinderModel {
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CorporationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
@@ -127,7 +127,7 @@ class CharacterModel extends AbstractPathfinderModel {
'allianceId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\AllianceModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\AllianceModel',
'constraint' => [
[
'table' => 'alliance',
@@ -140,7 +140,7 @@ class CharacterModel extends AbstractPathfinderModel {
'nullable' => false,
'default' => 1,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\RoleModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\RoleModel',
'constraint' => [
[
'table' => 'role',
@@ -187,16 +187,16 @@ class CharacterModel extends AbstractPathfinderModel {
'default' => 0
],
'userCharacter' => [
- 'has-one' => ['Model\Pathfinder\UserCharacterModel', 'characterId']
+ 'has-one' => ['Exodus4D\Pathfinder\Model\Pathfinder\UserCharacterModel', 'characterId']
],
'characterLog' => [
- 'has-one' => ['Model\Pathfinder\CharacterLogModel', 'characterId']
+ 'has-one' => ['Exodus4D\Pathfinder\Model\Pathfinder\CharacterLogModel', 'characterId']
],
'characterMaps' => [
- 'has-many' => ['Model\Pathfinder\CharacterMapModel', 'characterId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CharacterMapModel', 'characterId']
],
'characterAuthentications' => [
- 'has-many' => ['Model\Pathfinder\CharacterAuthenticationModel', 'characterId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CharacterAuthenticationModel', 'characterId']
]
];
@@ -707,7 +707,7 @@ class CharacterModel extends AbstractPathfinderModel {
* @return RoleModel
* @throws \Exception
*/
- protected function requestRole() : RoleModel {
+ protected function getRole() : RoleModel {
$role = null;
// check config files for hardcoded character roles
@@ -730,11 +730,12 @@ class CharacterModel extends AbstractPathfinderModel {
// check in-game roles
if(
is_null($role) &&
- !empty($rolesData = $this->requestRoles())
+ !empty($rolesData = $this->requestRoles()) &&
+ !empty($roles = $rolesData['roles'])
){
// roles that grant admin access for this character
- $adminRoles = array_intersect(CorporationModel::ADMIN_ROLES, $rolesData);
- if( !empty($adminRoles) ){
+ $adminRoles = array_intersect(CorporationModel::ADMIN_ROLES, $roles);
+ if(!empty($adminRoles)){
$role = RoleModel::getCorporationManagerRole();
}
}
@@ -748,26 +749,16 @@ class CharacterModel extends AbstractPathfinderModel {
}
/**
- * request all corporation roles granted to this character
+ * get all character roles grouped by 'role type'
+ * -> 'role types' are 'roles', 'rolesAtBase', 'rolesAtHq', 'rolesAtOther'
* @return array
- * @throws \Exception
*/
protected function requestRoles() : array {
$rolesData = [];
-
- // check if character has accepted all admin scopes (one of them is required for "role" request)
- if( $this->hasAdminScopes() ){
- if( $accessToken = $this->getAccessToken() ){
- // check if corporation exists (should never fail)
- if( $corporation = $this->getCorporation() ){
- $characterRolesData = $corporation->getCharactersRoles($accessToken);
- if( !empty($characterRolesData[$this->_id]) ){
- $rolesData = $characterRolesData[$this->_id];
- }
- }
- }
+ $response = self::getF3()->ccpClient()->send('getCharacterRoles', $this->_id, $this->getAccessToken());
+ if(!empty($response) && !isset($response['error'])){
+ $rolesData = $response;
}
-
return $rolesData;
}
@@ -792,7 +783,7 @@ class CharacterModel extends AbstractPathfinderModel {
*/
public function updateCloneData(){
if($accessToken = $this->getAccessToken()){
- $clonesData = self::getF3()->ccpClient()->getCharacterClonesData($this->_id, $accessToken);
+ $clonesData = self::getF3()->ccpClient()->send('getCharacterClones', $this->_id, $accessToken);
if(!isset($clonesData['error'])){
if(!empty($homeLocationData = $clonesData['home']['location'])){
// clone home location data
@@ -807,7 +798,7 @@ class CharacterModel extends AbstractPathfinderModel {
* @throws \Exception
*/
public function updateRoleData(){
- $this->roleId = $this->requestRole();
+ $this->roleId = $this->getRole();
}
/**
@@ -816,7 +807,7 @@ class CharacterModel extends AbstractPathfinderModel {
* @return array
*/
protected function getOnlineData(string $accessToken) : array {
- return self::getF3()->ccpClient()->getCharacterOnlineData($this->_id, $accessToken);
+ return self::getF3()->ccpClient()->send('getCharacterOnline', $this->_id, $accessToken);
}
/**
@@ -855,7 +846,7 @@ class CharacterModel extends AbstractPathfinderModel {
// Try to pull data from API
if($accessToken = $this->getAccessToken()){
if($this->isOnline($accessToken)){
- $locationData = self::getF3()->ccpClient()->getCharacterLocationData($this->_id, $accessToken);
+ $locationData = self::getF3()->ccpClient()->send('getCharacterLocation', $this->_id, $accessToken);
if(!empty($locationData['system']['id'])){
// character is currently in-game
@@ -886,7 +877,7 @@ class CharacterModel extends AbstractPathfinderModel {
// get "more" data for systemId ---------------------------------------------------------------
if(!empty($lookupUniverseIds)){
// get "more" information for some Ids (e.g. name)
- $universeData = self::getF3()->ccpClient()->getUniverseNamesData($lookupUniverseIds);
+ $universeData = self::getF3()->ccpClient()->send('getUniverseNames', $lookupUniverseIds);
if(!empty($universeData) && !isset($universeData['error'])){
// We expect max ONE system AND/OR station data, not an array of e.g. systems
@@ -967,7 +958,7 @@ class CharacterModel extends AbstractPathfinderModel {
// check ship data for changes ----------------------------------------------------------------
if(!$deleteLog){
- $shipData = self::getF3()->ccpClient()->getCharacterShipData($this->_id, $accessToken);
+ $shipData = self::getF3()->ccpClient()->send('getCharacterShip', $this->_id, $accessToken);
// IDs for "shipTypeId" that require more data
$lookupShipTypeId = 0;
@@ -1098,7 +1089,7 @@ class CharacterModel extends AbstractPathfinderModel {
if($logHistoryData = $this->getLogsHistory()){
// skip logging if no relevant fields changed
- list($historyEntryPrev) = $logHistoryData;
+ [$historyEntryPrev] = $logHistoryData;
if($historyLogPrev = $historyEntryPrev['log']){
if(
$historyLog['system']['id'] === $historyLogPrev['system']['id'] &&
diff --git a/app/main/model/pathfinder/characterstatusmodel.php b/app/Model/Pathfinder/CharacterStatusModel.php
similarity index 87%
rename from app/main/model/pathfinder/characterstatusmodel.php
rename to app/Model/Pathfinder/CharacterStatusModel.php
index 1d5eab8f..ba98c2e3 100644
--- a/app/main/model/pathfinder/characterstatusmodel.php
+++ b/app/Model/Pathfinder/CharacterStatusModel.php
@@ -6,14 +6,20 @@
* Time: 21:12
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class CharacterStatusModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'character_status';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -33,6 +39,9 @@ class CharacterStatusModel extends AbstractPathfinderModel {
]
];
+ /**
+ * @var array
+ */
protected static $tableData = [
[
'id' => 1,
diff --git a/app/main/model/pathfinder/connectionlogmodel.php b/app/Model/Pathfinder/ConnectionLogModel.php
similarity index 94%
rename from app/main/model/pathfinder/connectionlogmodel.php
rename to app/Model/Pathfinder/ConnectionLogModel.php
index 8f3aab9c..96ffa6cf 100644
--- a/app/main/model/pathfinder/connectionlogmodel.php
+++ b/app/Model/Pathfinder/ConnectionLogModel.php
@@ -6,14 +6,20 @@
* Time: 17:51
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class ConnectionLogModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'connection_log';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -24,7 +30,7 @@ class ConnectionLogModel extends AbstractPathfinderModel {
'connectionId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\ConnectionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\ConnectionModel',
'constraint' => [
[
'table' => 'connection',
diff --git a/app/main/model/pathfinder/connectionmodel.php b/app/Model/Pathfinder/ConnectionModel.php
similarity index 89%
rename from app/main/model/pathfinder/connectionmodel.php
rename to app/Model/Pathfinder/ConnectionModel.php
index 9eb3139e..11919d7d 100644
--- a/app/main/model/pathfinder/connectionmodel.php
+++ b/app/Model/Pathfinder/ConnectionModel.php
@@ -6,11 +6,12 @@
* Time: 21:12
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use Controller\Api\Route;
-use lib\logging;
+use Exodus4D\Pathfinder\Controller\Api\Rest\Route;
+use Exodus4D\Pathfinder\Lib\Logging;
+use Exodus4D\Pathfinder\Exception;
class ConnectionModel extends AbstractMapTrackingModel {
@@ -32,7 +33,7 @@ class ConnectionModel extends AbstractMapTrackingModel {
'mapId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapModel',
'constraint' => [
[
'table' => 'map',
@@ -43,7 +44,7 @@ class ConnectionModel extends AbstractMapTrackingModel {
'source' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -55,7 +56,7 @@ class ConnectionModel extends AbstractMapTrackingModel {
'target' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -87,10 +88,10 @@ class ConnectionModel extends AbstractMapTrackingModel {
'default' => null
],
'signatures' => [
- 'has-many' => ['Model\Pathfinder\SystemSignatureModel', 'connectionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\SystemSignatureModel', 'connectionId']
],
'connectionLog' => [
- 'has-many' => ['Model\Pathfinder\ConnectionLogModel', 'connectionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\ConnectionLogModel', 'connectionId']
]
];
@@ -129,7 +130,7 @@ class ConnectionModel extends AbstractMapTrackingModel {
$connectionData->source = $this->source->id;
$connectionData->target = $this->target->id;
$connectionData->scope = $this->scope;
- $connectionData->type = $this->type;
+ $connectionData->type = (array)json_decode($this->get('type', true));
$connectionData->updated = strtotime($this->updated);
$connectionData->created = strtotime($this->created);
$connectionData->eolUpdated = strtotime($this->eolUpdated);
@@ -156,7 +157,7 @@ class ConnectionModel extends AbstractMapTrackingModel {
/**
* setter for connection type
* @param $type
- * @return int|number
+ * @return array
*/
public function set_type($type){
// remove unwanted types -> they should not be send from client
@@ -218,10 +219,10 @@ class ConnectionModel extends AbstractMapTrackingModel {
}
/**
- * set default connection type by search route between endpoints
+ * set default connection scope + type by search route between endpoints
* @throws \Exception
*/
- public function setDefaultTypeData(){
+ public function setAutoScopeAndType(){
if(
is_object($this->source) &&
is_object($this->target)
@@ -232,17 +233,16 @@ class ConnectionModel extends AbstractMapTrackingModel {
){
$this->scope = 'abyssal';
$this->type = ['abyssal'];
+ }elseif(
+ $this->source->isKspace() &&
+ $this->target->isKspace() &&
+ (new Route())->searchRoute($this->source->systemId, $this->target->systemId, 1)['routePossible']
+ ){
+ $this->scope = 'stargate';
+ $this->type = ['stargate'];
}else{
- $routeController = new Route();
- $route = $routeController->searchRoute($this->source->systemId, $this->target->systemId, 1);
-
- if($route['routePossible']){
- $this->scope = 'stargate';
- $this->type = ['stargate'];
- }else{
- $this->scope = 'wh';
- $this->type = ['wh_fresh'];
- }
+ $this->scope = 'wh';
+ $this->type = ['wh_fresh'];
}
}
}
@@ -258,7 +258,7 @@ class ConnectionModel extends AbstractMapTrackingModel {
/**
* check whether this model is valid or not
* @return bool
- * @throws \Exception\DatabaseException
+ * @throws Exception\DatabaseException
*/
public function isValid() : bool {
if($valid = parent::isValid()){
@@ -278,13 +278,14 @@ class ConnectionModel extends AbstractMapTrackingModel {
}
/**
- * Event "Hook" function
+ * Event "Hook" function
* can be overwritten
* return false will stop any further action
- * @param self $self
+ * @param \Exodus4D\Pathfinder\Model\AbstractModel $self
* @param $pkeys
* @return bool
- * @throws \Exception\DatabaseException
+ * @throws Exception\DatabaseException
+ * @throws \Exception
*/
public function beforeInsertEvent($self, $pkeys) : bool {
// check for "default" connection type and add them if missing
@@ -294,7 +295,7 @@ class ConnectionModel extends AbstractMapTrackingModel {
!$this->scope ||
empty($types)
){
- $this->setDefaultTypeData();
+ $this->setAutoScopeAndType();
}
return $this->isValid() ? parent::beforeInsertEvent($self, $pkeys) : false;
@@ -335,8 +336,8 @@ class ConnectionModel extends AbstractMapTrackingModel {
/**
* @param string $action
- * @return logging\LogInterface
- * @throws \Exception\ConfigException
+ * @return Logging\LogInterface
+ * @throws Exception\ConfigException
*/
public function newLog(string $action = '') : Logging\LogInterface {
return $this->getMap()->newLog($action)->setTempData($this->getLogObjectData());
diff --git a/app/main/model/pathfinder/connectionscopemodel.php b/app/Model/Pathfinder/ConnectionScopeModel.php
similarity index 91%
rename from app/main/model/pathfinder/connectionscopemodel.php
rename to app/Model/Pathfinder/ConnectionScopeModel.php
index fd9c3021..5d07fea9 100644
--- a/app/main/model/pathfinder/connectionscopemodel.php
+++ b/app/Model/Pathfinder/ConnectionScopeModel.php
@@ -6,14 +6,20 @@
* Time: 20:01
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class ConnectionScopeModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'connection_scope';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -38,6 +44,9 @@ class ConnectionScopeModel extends AbstractPathfinderModel {
]
];
+ /**
+ * @var array
+ */
protected static $tableData = [
[
'id' => 1,
@@ -63,7 +72,6 @@ class ConnectionScopeModel extends AbstractPathfinderModel {
'label' => 'abyssal',
'connectorDefinition' => '[ "Straight", { "stub": [5, 5], "gap": 0 } ]'
]
-
];
}
\ No newline at end of file
diff --git a/app/main/model/pathfinder/corporationmapmodel.php b/app/Model/Pathfinder/CorporationMapModel.php
similarity index 87%
rename from app/main/model/pathfinder/corporationmapmodel.php
rename to app/Model/Pathfinder/CorporationMapModel.php
index 8fe73e1c..24ada8c9 100644
--- a/app/main/model/pathfinder/corporationmapmodel.php
+++ b/app/Model/Pathfinder/CorporationMapModel.php
@@ -6,7 +6,7 @@
* Time: 20:01
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
@@ -30,7 +30,7 @@ class CorporationMapModel extends AbstractPathfinderModel {
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CorporationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
@@ -41,7 +41,7 @@ class CorporationMapModel extends AbstractPathfinderModel {
'mapId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapModel',
'constraint' => [
[
'table' => 'map',
diff --git a/app/main/model/pathfinder/corporationmodel.php b/app/Model/Pathfinder/CorporationModel.php
similarity index 90%
rename from app/main/model/pathfinder/corporationmodel.php
rename to app/Model/Pathfinder/CorporationModel.php
index b2a5cb71..17e39b26 100644
--- a/app/main/model/pathfinder/corporationmodel.php
+++ b/app/Model/Pathfinder/CorporationModel.php
@@ -6,10 +6,10 @@
* Time: 20:43
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use lib\Config;
+use Exodus4D\Pathfinder\Lib\Config;
class CorporationModel extends AbstractPathfinderModel {
@@ -88,10 +88,12 @@ class CorporationModel extends AbstractPathfinderModel {
* corp rights that can be stored to a corp
*/
const RIGHTS = [
+ 'map_create',
'map_update',
'map_delete',
'map_import',
- 'map_export'
+ 'map_export',
+ 'map_share'
];
/**
@@ -130,19 +132,19 @@ class CorporationModel extends AbstractPathfinderModel {
'default' => 0
],
'corporationCharacters' => [
- 'has-many' => ['Model\Pathfinder\CharacterModel', 'corporationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel', 'corporationId']
],
'mapCorporations' => [
- 'has-many' => ['Model\Pathfinder\CorporationMapModel', 'corporationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CorporationMapModel', 'corporationId']
],
'corporationRights' => [
- 'has-many' => ['Model\Pathfinder\CorporationRightModel', 'corporationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CorporationRightModel', 'corporationId']
],
'corporationStructures' => [
- 'has-many' => ['Model\Pathfinder\CorporationStructureModel', 'corporationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CorporationStructureModel', 'corporationId']
],
'structures' => [
- 'has-many' => ['Model\Pathfinder\StructureModel', 'corporationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\StructureModel', 'corporationId']
]
];
@@ -292,7 +294,7 @@ class CorporationModel extends AbstractPathfinderModel {
!empty($accessToken) &&
!$this->isNPC
){
- $response = self::getF3()->ccpClient()->getCorporationRoles($this->_id, $accessToken);
+ $response = self::getF3()->ccpClient()->send('getCorporationRoles', $this->_id, $accessToken);
if( !empty($response['roles']) ){
$characterRolesData = (array)$response['roles'];
}
@@ -303,15 +305,16 @@ class CorporationModel extends AbstractPathfinderModel {
/**
* get all corporation rights
+ * @param array $names
* @param array $options
* @return CorporationRightModel[]
* @throws \Exception
*/
- public function getRights($options = []) : array {
+ public function getRights($names = self::RIGHTS, $options = []) : array {
$corporationRights = [];
// get available rights
$right = self::getNew('RightModel');
- if($rights = $right->find(['active = ? AND name IN (?)', 1, self::RIGHTS])){
+ if($rights = $right->find(['active = ? AND name IN (?)', 1, $names])){
// get already stored rights
if( !$options['addInactive'] ){
$this->filter('corporationRights', ['active = ?', 1]);
@@ -356,10 +359,10 @@ class CorporationModel extends AbstractPathfinderModel {
$loaded = parent::getById($id, $ttl, $isActive);
if($this->isOutdated()){
// request corporation data
- $corporationData = self::getF3()->ccpClient()->getCorporationData($id);
+ $corporationData = self::getF3()->ccpClient()->send('getCorporation', $id);
if(!empty($corporationData) && !isset($corporationData['error'])){
// check for NPC corporation
- $corporationData['isNPC'] = self::getF3()->ccpClient()->isNpcCorporation($id);
+ $corporationData['isNPC'] = in_array($id, self::getF3()->ccpClient()->send('getNpcCorporations'));
$this->copyfrom($corporationData, ['id', 'name', 'ticker', 'memberCount', 'isNPC']);
$this->save();
diff --git a/app/main/model/pathfinder/corporationrightmodel.php b/app/Model/Pathfinder/CorporationRightModel.php
similarity index 89%
rename from app/main/model/pathfinder/corporationrightmodel.php
rename to app/Model/Pathfinder/CorporationRightModel.php
index 1587968c..b42b8c45 100644
--- a/app/main/model/pathfinder/corporationrightmodel.php
+++ b/app/Model/Pathfinder/CorporationRightModel.php
@@ -6,7 +6,7 @@
* Time: 15:37
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
@@ -30,7 +30,7 @@ class CorporationRightModel extends AbstractPathfinderModel {
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CorporationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
@@ -41,7 +41,7 @@ class CorporationRightModel extends AbstractPathfinderModel {
'rightId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\RightModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\RightModel',
'constraint' => [
[
'table' => 'right',
@@ -52,7 +52,7 @@ class CorporationRightModel extends AbstractPathfinderModel {
'roleId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\RoleModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\RoleModel',
'constraint' => [
[
'table' => 'role',
diff --git a/app/main/model/pathfinder/corporationstructuremodel.php b/app/Model/Pathfinder/CorporationStructureModel.php
similarity index 86%
rename from app/main/model/pathfinder/corporationstructuremodel.php
rename to app/Model/Pathfinder/CorporationStructureModel.php
index a9aab364..5ee8f4a7 100644
--- a/app/main/model/pathfinder/corporationstructuremodel.php
+++ b/app/Model/Pathfinder/CorporationStructureModel.php
@@ -6,7 +6,7 @@
* Time: 19:23
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
@@ -30,7 +30,7 @@ class CorporationStructureModel extends AbstractPathfinderModel {
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CorporationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
@@ -41,7 +41,7 @@ class CorporationStructureModel extends AbstractPathfinderModel {
'structureId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\StructureModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\StructureModel',
'constraint' => [
[
'table' => 'structure',
diff --git a/app/main/model/pathfinder/cronmodel.php b/app/Model/Pathfinder/CronModel.php
similarity index 98%
rename from app/main/model/pathfinder/cronmodel.php
rename to app/Model/Pathfinder/CronModel.php
index 3708f6ca..973f9c11 100644
--- a/app/main/model/pathfinder/cronmodel.php
+++ b/app/Model/Pathfinder/CronModel.php
@@ -1,7 +1,7 @@
[
'type' => 'warning',
@@ -160,6 +163,7 @@ class CronModel extends AbstractPathfinderModel {
/**
* @param bool $addLastIfFinished
* @return array
+ * @throws \Exception
*/
protected function getHistory(bool $addLastIfFinished = false) : array {
$history = $this->history ? : [];
@@ -183,6 +187,7 @@ class CronModel extends AbstractPathfinderModel {
/**
* get current job status based on its current data
* @return array
+ * @throws \Exception
*/
protected function getStatus() : array {
$status = [];
diff --git a/app/main/model/pathfinder/logmodelinterface.php b/app/Model/Pathfinder/LogModelInterface.php
similarity index 84%
rename from app/main/model/pathfinder/logmodelinterface.php
rename to app/Model/Pathfinder/LogModelInterface.php
index aa145a57..b2e7245e 100644
--- a/app/main/model/pathfinder/logmodelinterface.php
+++ b/app/Model/Pathfinder/LogModelInterface.php
@@ -6,7 +6,7 @@
* Time: 04:10
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
interface LogModelInterface {
diff --git a/app/main/model/pathfinder/mapmodel.php b/app/Model/Pathfinder/MapModel.php
similarity index 89%
rename from app/main/model/pathfinder/mapmodel.php
rename to app/Model/Pathfinder/MapModel.php
index 2be5ad10..93e37f4d 100644
--- a/app/main/model/pathfinder/mapmodel.php
+++ b/app/Model/Pathfinder/MapModel.php
@@ -6,14 +6,14 @@
* Time: 22:10
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\CortexCollection;
use DB\SQL\Schema;
-use data\file\FileHandler;
-use Exception\ConfigException;
-use lib\Config;
-use lib\logging;
+use Exodus4D\Pathfinder\Data\File\FileHandler;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Logging;
+use Exodus4D\Pathfinder\Exception;
class MapModel extends AbstractMapTrackingModel {
@@ -44,7 +44,7 @@ class MapModel extends AbstractMapTrackingModel {
'scopeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapScopeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapScopeModel',
'constraint' => [
[
'table' => 'map_scope',
@@ -57,7 +57,7 @@ class MapModel extends AbstractMapTrackingModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapTypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapTypeModel',
'constraint' => [
[
'table' => 'map_type',
@@ -171,19 +171,19 @@ class MapModel extends AbstractMapTrackingModel {
'validate' => true
],
'systems' => [
- 'has-many' => ['Model\Pathfinder\SystemModel', 'mapId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\SystemModel', 'mapId']
],
'connections' => [
- 'has-many' => ['Model\Pathfinder\ConnectionModel', 'mapId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\ConnectionModel', 'mapId']
],
'mapCharacters' => [
- 'has-many' => ['Model\Pathfinder\CharacterMapModel', 'mapId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CharacterMapModel', 'mapId']
],
'mapCorporations' => [
- 'has-many' => ['Model\Pathfinder\CorporationMapModel', 'mapId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CorporationMapModel', 'mapId']
],
'mapAlliances' => [
- 'has-many' => ['Model\Pathfinder\AllianceMapModel', 'mapId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\AllianceMapModel', 'mapId']
]
];
@@ -217,14 +217,13 @@ class MapModel extends AbstractMapTrackingModel {
/**
* get data
* -> this includes system and connection data as well
- * @return \stdClass
- * @throws \Exception
+ * @param bool $noCache
+ * @return mixed|object|null
+ * @throws Exception\ConfigException
*/
- public function getData(){
+ public function getData(bool $noCache = false){
// check if there is cached data
- $mapDataAll = $this->getCacheData();
-
- if(is_null($mapDataAll)){
+ if($noCache || is_null($mapDataAll = $this->getCacheData())){
// no cached map data found
$mapData = (object) [];
@@ -340,7 +339,7 @@ class MapModel extends AbstractMapTrackingModel {
* @param string $key
* @param string $val
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_name(string $key, string $val) : bool {
$valid = true;
@@ -356,7 +355,7 @@ class MapModel extends AbstractMapTrackingModel {
* @param string $key
* @param string $val
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_slackWebHookURL(string $key, string $val) : bool {
return $this->validate_WebHookURL($key, $val, 'slack');
@@ -367,7 +366,7 @@ class MapModel extends AbstractMapTrackingModel {
* @param string $key
* @param string $val
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_discordWebHookURLHistory(string $key, string $val) : bool {
return $this->validate_WebHookURL($key, $val, 'discord');
@@ -378,7 +377,7 @@ class MapModel extends AbstractMapTrackingModel {
* @param string $key
* @param string $val
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_discordWebHookURLRally(string $key, string $val) : bool {
return $this->validate_WebHookURL($key, $val, 'discord');
@@ -390,7 +389,7 @@ class MapModel extends AbstractMapTrackingModel {
* @param string $val
* @param string $type
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_WebHookURL(string $key, string $val, string $type) : bool {
$valid = true;
@@ -702,99 +701,134 @@ class MapModel extends AbstractMapTrackingModel {
/**
* set map access for an object (character, corporation or alliance)
* @param $obj
+ * @return bool
* @throws \Exception
*/
- public function setAccess($obj){
-
+ public function setAccess($obj) : bool {
$newAccessGranted = false;
if($obj instanceof CharacterModel){
- // private map
-
// check whether the user has already map access
- $this->has('mapCharacters', ['active = 1 AND characterId = :characterId', ':characterId' => $obj->id]);
- $result = $this->findone(['id = :id', ':id' => $this->id]);
-
- if($result === false){
+ $result = $this->relFindOne('mapCharacters', self::getFilter('characterId', $obj->_id));
+ if(!$result){
// grant access for the character
$characterMap = self::getNew('CharacterMapModel');
$characterMap->characterId = $obj;
$characterMap->mapId = $this;
- $characterMap->save();
-
- $newAccessGranted = true;
+ if($characterMap->save()){
+ $newAccessGranted = true;
+ }
}
}elseif($obj instanceof CorporationModel){
-
// check whether the corporation already has map access
- $this->has('mapCorporations', ['active = 1 AND corporationId = :corporationId', ':corporationId' => $obj->id]);
- $result = $this->findone(['id = :id', ':id' => $this->id]);
-
- if($result === false){
+ $result = $this->relFindOne('mapCorporations', self::getFilter('corporationId', $obj->_id));
+ if(!$result){
// grant access for this corporation
$corporationMap = self::getNew('CorporationMapModel');
$corporationMap->corporationId = $obj;
$corporationMap->mapId = $this;
- $corporationMap->save();
-
- $newAccessGranted = true;
+ if($corporationMap->save()){
+ $newAccessGranted = true;
+ }
}
}elseif($obj instanceof AllianceModel){
-
// check whether the alliance already has map access
- $this->has('mapAlliances', ['active = 1 AND allianceId = :allianceId', ':allianceId' => $obj->id]);
- $result = $this->findone(['id = :id', ':id' => $this->id]);
-
- if($result === false){
+ $result = $this->relFindOne('mapAlliances', self::getFilter('allianceId', $obj->_id));
+ if(!$result){
$allianceMap = self::getNew('AllianceMapModel');
$allianceMap->allianceId = $obj;
$allianceMap->mapId = $this;
- $allianceMap->save();
-
- $newAccessGranted = true;
+ if($allianceMap->save()){
+ $newAccessGranted = true;
+ }
}
}
+ return $newAccessGranted;
+ }
- if($newAccessGranted){
- // mark this map as updated
- $this->setUpdated();
+ /**
+ * @param $stack
+ * @return array
+ */
+ public function compareAccess($stack) : array {
+ $result = [];
+ if($this->valid()){
+ if($this->isPrivate()){
+ $result = $this->mapCharacters ? $this->mapCharacters->compare($stack, 'characterId') : ['new' => $stack];
+ }elseif($this->isCorporation()){
+ $result = $this->mapCorporations ? $this->mapCorporations->compare($stack, 'corporationId') : ['new' => $stack];
+ }elseif($this->isAlliance()){
+ $result = $this->mapAlliances ? $this->mapAlliances->compare($stack, 'allianceId') : ['new' => $stack];
+ }
}
+ return $result;
+ }
+ /**
+ * @param int $id
+ * @return int
+ */
+ public function removeFromAccess(int $id) : int {
+ $count = 0;
+ if($id && $this->valid()){
+ $result = null;
+ if($this->isPrivate()){
+ $result = $this->relFindOne('mapCharacters', self::getFilter('characterId', $id));
+ }elseif($this->isCorporation()){
+ $result = $this->relFindOne('mapCorporations', self::getFilter('corporationId', $id));
+ }elseif($this->isAlliance()){
+ $result = $this->relFindOne('mapAlliances', self::getFilter('allianceId', $id));
+ }
+
+ if($result && $result->erase()){
+ $count++;
+ }
+ }
+ return $count;
+ }
+
+ /**
+ * clear map access for entities that do not match the map "mapType"
+ * @return int
+ */
+ public function clearAccessByType() : int {
+ $count = 0;
+ if($this->valid()){
+ if($this->isPrivate()){
+ $count = $this->clearAccess(['corporation', 'alliance']);
+ }elseif($this->isCorporation()){
+ $count = $this->clearAccess(['character', 'alliance']);
+ }elseif($this->isAlliance()){
+ $count = $this->clearAccess(['character', 'corporation']);
+ }
+ }
+ return $count;
}
/**
* clear access for a given type of objects
* @param array $clearKeys
+ * @return int
*/
- public function clearAccess($clearKeys = ['character', 'corporation', 'alliance']){
+ public function clearAccess($clearKeys = ['character', 'corporation', 'alliance']) : int {
+ $count = 0;
foreach($clearKeys as $key){
+ $field = null;
switch($key){
- case 'character':
- foreach((array)$this->mapCharacters as $characterMapModel){
- /**
- * @var CharacterMapModel $characterMapModel
- */
- $characterMapModel->erase();
- };
- break;
- case 'corporation':
- foreach((array)$this->mapCorporations as $corporationMapModel){
- /**
- * @var CorporationMapModel $corporationMapModel
- */
- $corporationMapModel->erase();
- };
- break;
- case 'alliance':
- foreach((array)$this->mapAlliances as $allianceMapModel){
- /**
- * @var AllianceMapModel $allianceMapModel
- */
- $allianceMapModel->erase();
- };
- break;
+ case 'character': $field = 'mapCharacters'; break;
+ case 'corporation': $field = 'mapCorporations'; break;
+ case 'alliance': $field = 'mapAlliances'; break;
+ }
+
+ if($this->$field){
+ foreach((array)$this->$field as $model){
+ if($model->erase()){
+ $count++;
+ }
+ }
}
}
+ return $count;
}
/**
@@ -975,13 +1009,14 @@ class MapModel extends AbstractMapTrackingModel {
/**
* @param string $action
- * @return logging\LogInterface
- * @throws ConfigException
+ * @return Logging\LogInterface
+ * @throws Exception\ConfigException
+ * @throws \Exception
*/
public function newLog(string $action = '') : Logging\LogInterface{
$logChannelData = $this->getLogChannelData();
$logObjectData = $this->getLogObjectData();
- $log = (new logging\MapLog($action, $logChannelData))->setTempData($logObjectData);
+ $log = (new Logging\MapLog($action, $logChannelData))->setTempData($logObjectData);
// update map history *.log files -----------------------------------------------------------------------------
if($this->isHistoryLogEnabled()){
@@ -1072,7 +1107,7 @@ class MapModel extends AbstractMapTrackingModel {
* check if "Slack WebHook" is enabled for this map type
* @param string $channel
* @return bool
- * @throws ConfigException
+ * @throws Exception\ConfigException
*/
public function isSlackChannelEnabled(string $channel) : bool {
$enabled = false;
@@ -1082,7 +1117,7 @@ class MapModel extends AbstractMapTrackingModel {
switch($channel){
case 'slackChannelHistory': $defaultMapConfigKey = 'send_history_slack_enabled'; break;
case 'slackChannelRally': $defaultMapConfigKey = 'send_rally_slack_enabled'; break;
- default: throw new ConfigException(sprintf(self::ERROR_SLACK_CHANNEL, $channel));
+ default: throw new Exception\ConfigException(sprintf(self::ERROR_SLACK_CHANNEL, $channel));
}
if((bool) Config::getMapsDefaultConfig($this->typeId->name)[$defaultMapConfigKey]){
@@ -1100,7 +1135,7 @@ class MapModel extends AbstractMapTrackingModel {
* check if "Discord WebHook" is enabled for this map type
* @param string $channel
* @return bool
- * @throws ConfigException
+ * @throws Exception\ConfigException
*/
public function isDiscordChannelEnabled(string $channel) : bool {
$enabled = false;
@@ -1110,7 +1145,7 @@ class MapModel extends AbstractMapTrackingModel {
switch($channel){
case 'discordWebHookURLHistory': $defaultMapConfigKey = 'send_history_discord_enabled'; break;
case 'discordWebHookURLRally': $defaultMapConfigKey = 'send_rally_discord_enabled'; break;
- default: throw new ConfigException(sprintf(self::ERROR_DISCORD_CHANNEL, $channel));
+ default: throw new Exception\ConfigException(sprintf(self::ERROR_DISCORD_CHANNEL, $channel));
}
if((bool) Config::getMapsDefaultConfig($this->typeId->name)[$defaultMapConfigKey]){
@@ -1428,17 +1463,6 @@ class MapModel extends AbstractMapTrackingModel {
*/
$mapModel = parent::save($characterModel);
- // check if map type has changed and clear access objects
- if( !$mapModel->dry() ){
- if( $mapModel->isPrivate() ){
- $mapModel->clearAccess(['corporation', 'alliance']);
- }elseif( $mapModel->isCorporation() ){
- $mapModel->clearAccess(['character', 'alliance']);
- }elseif( $mapModel->isAlliance() ){
- $mapModel->clearAccess(['character', 'corporation']);
- }
- }
-
return $mapModel;
}
diff --git a/app/main/model/pathfinder/mapscopemodel.php b/app/Model/Pathfinder/MapScopeModel.php
similarity index 88%
rename from app/main/model/pathfinder/mapscopemodel.php
rename to app/Model/Pathfinder/MapScopeModel.php
index 9ae22291..e3d3d9c3 100644
--- a/app/main/model/pathfinder/mapscopemodel.php
+++ b/app/Model/Pathfinder/MapScopeModel.php
@@ -6,14 +6,20 @@
* Time: 20:01
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class MapScopeModel extends AbstractPathfinderModel{
+ /**
+ * @var string
+ */
protected $table = 'map_scope';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -33,6 +39,9 @@ class MapScopeModel extends AbstractPathfinderModel{
]
];
+ /**
+ * @var array
+ */
protected static $tableData = [
[
'id' => 1,
diff --git a/app/main/model/pathfinder/maptypemodel.php b/app/Model/Pathfinder/MapTypeModel.php
similarity index 93%
rename from app/main/model/pathfinder/maptypemodel.php
rename to app/Model/Pathfinder/MapTypeModel.php
index c25f2d6a..35fee514 100644
--- a/app/main/model/pathfinder/maptypemodel.php
+++ b/app/Model/Pathfinder/MapTypeModel.php
@@ -6,14 +6,20 @@
* Time: 20:01
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class MapTypeModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'map_type';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -43,6 +49,9 @@ class MapTypeModel extends AbstractPathfinderModel {
]
];
+ /**
+ * @var array
+ */
protected static $tableData = [
[
'id' => 1,
diff --git a/app/main/model/pathfinder/rightmodel.php b/app/Model/Pathfinder/RightModel.php
similarity index 80%
rename from app/main/model/pathfinder/rightmodel.php
rename to app/Model/Pathfinder/RightModel.php
index 2c13b877..13cc9c43 100644
--- a/app/main/model/pathfinder/rightmodel.php
+++ b/app/Model/Pathfinder/RightModel.php
@@ -6,7 +6,7 @@
* Time: 14:38
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
@@ -45,7 +45,7 @@ class RightModel extends AbstractPathfinderModel {
'default' => ''
],
'corporationRights' => [
- 'has-many' => ['Model\Pathfinder\CorporationRightModel', 'rightId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CorporationRightModel', 'rightId']
]
];
@@ -76,6 +76,18 @@ class RightModel extends AbstractPathfinderModel {
'name' => 'map_export',
'label' => 'export',
'description' => 'Map export right'
+ ],
+ [
+ 'id' => 5,
+ 'name' => 'map_share',
+ 'label' => 'share',
+ 'description' => 'Map share right'
+ ],
+ [
+ 'id' => 6,
+ 'name' => 'map_create',
+ 'label' => 'create',
+ 'description' => 'Map create right'
]
];
diff --git a/app/main/model/pathfinder/rolemodel.php b/app/Model/Pathfinder/RoleModel.php
similarity index 91%
rename from app/main/model/pathfinder/rolemodel.php
rename to app/Model/Pathfinder/RoleModel.php
index 75763924..e0d1463c 100644
--- a/app/main/model/pathfinder/rolemodel.php
+++ b/app/Model/Pathfinder/RoleModel.php
@@ -6,14 +6,20 @@
* Time: 12:42
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class RoleModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'role';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -41,10 +47,13 @@ class RoleModel extends AbstractPathfinderModel {
'default' => ''
],
'corporationRights' => [
- 'has-many' => ['Model\Pathfinder\CorporationRightModel', 'roleId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CorporationRightModel', 'roleId']
]
];
+ /**
+ * @var array
+ */
protected static $tableData = [
[
'id' => 1,
diff --git a/app/main/model/pathfinder/structuremodel.php b/app/Model/Pathfinder/StructureModel.php
similarity index 95%
rename from app/main/model/pathfinder/structuremodel.php
rename to app/Model/Pathfinder/StructureModel.php
index ef0fcd89..25533f68 100644
--- a/app/main/model/pathfinder/structuremodel.php
+++ b/app/Model/Pathfinder/StructureModel.php
@@ -6,10 +6,10 @@
* Time: 19:41
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use Model\Universe;
+use Exodus4D\Pathfinder\Model\Universe;
class StructureModel extends AbstractPathfinderModel {
@@ -36,7 +36,7 @@ class StructureModel extends AbstractPathfinderModel {
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CorporationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
@@ -53,7 +53,7 @@ class StructureModel extends AbstractPathfinderModel {
'type' => Schema::DT_INT,
'default' => 1,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\StructureStatusModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\StructureStatusModel',
'constraint' => [
[
'table' => 'structure_status',
@@ -72,7 +72,7 @@ class StructureModel extends AbstractPathfinderModel {
'default' => ''
],
'structureCorporations' => [
- 'has-many' => ['Model\Pathfinder\CorporationStructureModel', 'structureId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\CorporationStructureModel', 'structureId']
]
];
diff --git a/app/main/model/pathfinder/structurestatusmodel.php b/app/Model/Pathfinder/StructureStatusModel.php
similarity index 93%
rename from app/main/model/pathfinder/structurestatusmodel.php
rename to app/Model/Pathfinder/StructureStatusModel.php
index 5d7aca0c..cb814b68 100644
--- a/app/main/model/pathfinder/structurestatusmodel.php
+++ b/app/Model/Pathfinder/StructureStatusModel.php
@@ -6,7 +6,7 @@
* Time: 20:13
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
@@ -44,7 +44,7 @@ class StructureStatusModel extends AbstractPathfinderModel {
'default' => ''
],
'structures' => [
- 'has-many' => ['Model\Pathfinder\StructureModel', 'statusId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\StructureModel', 'statusId']
]
];
diff --git a/app/main/model/pathfinder/systemfactionkillmodel.php b/app/Model/Pathfinder/SystemFactionKillModel.php
similarity index 92%
rename from app/main/model/pathfinder/systemfactionkillmodel.php
rename to app/Model/Pathfinder/SystemFactionKillModel.php
index 90c654b0..8bd773fb 100644
--- a/app/main/model/pathfinder/systemfactionkillmodel.php
+++ b/app/Model/Pathfinder/SystemFactionKillModel.php
@@ -6,7 +6,7 @@
* Time: 21:04
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
diff --git a/app/main/model/pathfinder/systemjumpmodel.php b/app/Model/Pathfinder/SystemJumpModel.php
similarity index 92%
rename from app/main/model/pathfinder/systemjumpmodel.php
rename to app/Model/Pathfinder/SystemJumpModel.php
index 03d62b8c..9fd6e2e5 100644
--- a/app/main/model/pathfinder/systemjumpmodel.php
+++ b/app/Model/Pathfinder/SystemJumpModel.php
@@ -6,7 +6,7 @@
* Time: 21:04
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
diff --git a/app/main/model/pathfinder/systemmodel.php b/app/Model/Pathfinder/SystemModel.php
similarity index 96%
rename from app/main/model/pathfinder/systemmodel.php
rename to app/Model/Pathfinder/SystemModel.php
index 29ec2de9..a038b2b8 100644
--- a/app/main/model/pathfinder/systemmodel.php
+++ b/app/Model/Pathfinder/SystemModel.php
@@ -6,12 +6,13 @@
* Time: 23:56
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use lib\logging;
-use lib\PriorityCacheStore;
-use Controller\Ccp\Universe;
+use Exodus4D\Pathfinder\Lib\Logging;
+use Exodus4D\Pathfinder\Lib\PriorityCacheStore;
+use Exodus4D\Pathfinder\Controller\Ccp\Universe;
+use Exodus4D\Pathfinder\Exception;
class SystemModel extends AbstractMapTrackingModel {
@@ -64,7 +65,7 @@ class SystemModel extends AbstractMapTrackingModel {
'mapId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\MapModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\MapModel',
'constraint' => [
[
'table' => 'map',
@@ -86,7 +87,7 @@ class SystemModel extends AbstractMapTrackingModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\SystemTypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\SystemTypeModel',
'constraint' => [
[
'table' => 'system_type',
@@ -99,7 +100,7 @@ class SystemModel extends AbstractMapTrackingModel {
'nullable' => false,
'default' => 1,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\SystemStatusModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\SystemStatusModel',
'constraint' => [
[
'table' => 'system_status',
@@ -141,13 +142,13 @@ class SystemModel extends AbstractMapTrackingModel {
'default' => 0
],
'signatures' => [
- 'has-many' => ['Model\Pathfinder\SystemSignatureModel', 'systemId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\SystemSignatureModel', 'systemId']
],
'connectionsSource' => [
- 'has-many' => ['Model\Pathfinder\ConnectionModel', 'source']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\ConnectionModel', 'source']
],
'connectionsTarget' => [
- 'has-many' => ['Model\Pathfinder\ConnectionModel', 'target']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\ConnectionModel', 'target']
]
];
@@ -297,7 +298,7 @@ class SystemModel extends AbstractMapTrackingModel {
* @param string $key
* @param int $val
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_statusId(string $key, int $val) : bool {
$valid = true;
@@ -313,7 +314,7 @@ class SystemModel extends AbstractMapTrackingModel {
* @param string $key
* @param string $val
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_description(string $key, string $val) : bool {
$valid = true;
@@ -554,8 +555,8 @@ class SystemModel extends AbstractMapTrackingModel {
/**
* @param string $action
- * @return logging\LogInterface
- * @throws \Exception\ConfigException
+ * @return Logging\LogInterface
+ * @throws Exception\ConfigException
*/
public function newLog(string $action = '') : Logging\LogInterface{
return $this->getMap()->newLog($action)->setTempData($this->getLogObjectData());
@@ -715,12 +716,13 @@ class SystemModel extends AbstractMapTrackingModel {
* -> send to an Email
* @param array $rallyData
* @param CharacterModel $characterModel
- * @throws \Exception\ConfigException
+ * @throws Exception\ConfigException
+ * @throws \Exception
*/
public function sendRallyPoke(array $rallyData, CharacterModel $characterModel){
// rally log needs at least one handler to be valid
$isValidLog = false;
- $log = new logging\RallyLog('rallySet', $this->getMap()->getLogChannelData());
+ $log = new Logging\RallyLog('rallySet', $this->getMap()->getLogChannelData());
// Slack poke -----------------------------------------------------------------------------
$slackChannelKey = 'slackChannelRally';
diff --git a/app/main/model/pathfinder/systempodkillmodel.php b/app/Model/Pathfinder/SystemPodKillModel.php
similarity index 92%
rename from app/main/model/pathfinder/systempodkillmodel.php
rename to app/Model/Pathfinder/SystemPodKillModel.php
index 7eb847f7..99b5d51d 100644
--- a/app/main/model/pathfinder/systempodkillmodel.php
+++ b/app/Model/Pathfinder/SystemPodKillModel.php
@@ -6,7 +6,7 @@
* Time: 21:04
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
diff --git a/app/main/model/pathfinder/systemshipkillmodel.php b/app/Model/Pathfinder/SystemShipKillModel.php
similarity index 92%
rename from app/main/model/pathfinder/systemshipkillmodel.php
rename to app/Model/Pathfinder/SystemShipKillModel.php
index 15af811a..9c859d0b 100644
--- a/app/main/model/pathfinder/systemshipkillmodel.php
+++ b/app/Model/Pathfinder/SystemShipKillModel.php
@@ -6,7 +6,7 @@
* Time: 21:04
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
diff --git a/app/main/model/pathfinder/systemsignaturemodel.php b/app/Model/Pathfinder/SystemSignatureModel.php
similarity index 95%
rename from app/main/model/pathfinder/systemsignaturemodel.php
rename to app/Model/Pathfinder/SystemSignatureModel.php
index 06be9f3a..8a95f78a 100644
--- a/app/main/model/pathfinder/systemsignaturemodel.php
+++ b/app/Model/Pathfinder/SystemSignatureModel.php
@@ -6,10 +6,11 @@
* Time: 14:34
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use lib\logging;
+use Exodus4D\Pathfinder\Lib\Logging;
+use Exodus4D\Pathfinder\Exception;
class SystemSignatureModel extends AbstractMapTrackingModel {
@@ -31,7 +32,7 @@ class SystemSignatureModel extends AbstractMapTrackingModel {
'systemId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -56,7 +57,7 @@ class SystemSignatureModel extends AbstractMapTrackingModel {
'connectionId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\ConnectionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\ConnectionModel',
'constraint' => [
[
'table' => 'connection',
@@ -163,7 +164,7 @@ class SystemSignatureModel extends AbstractMapTrackingModel {
* @param string $key
* @param string $val
* @return bool
- * @throws \Exception\ValidationException
+ * @throws Exception\ValidationException
*/
protected function validate_name(string $key, string $val): bool {
$valid = true;
@@ -176,8 +177,8 @@ class SystemSignatureModel extends AbstractMapTrackingModel {
/**
* @param string $action
- * @return logging\LogInterface
- * @throws \Exception\ConfigException
+ * @return Logging\LogInterface
+ * @throws Exception\ConfigException
*/
public function newLog(string $action = ''): Logging\LogInterface{
return $this->getMap()->newLog($action)->setTempData($this->getLogObjectData());
diff --git a/app/main/model/pathfinder/systemstatusmodel.php b/app/Model/Pathfinder/SystemStatusModel.php
similarity index 94%
rename from app/main/model/pathfinder/systemstatusmodel.php
rename to app/Model/Pathfinder/SystemStatusModel.php
index 65a236b4..74e0d71d 100644
--- a/app/main/model/pathfinder/systemstatusmodel.php
+++ b/app/Model/Pathfinder/SystemStatusModel.php
@@ -6,14 +6,20 @@
* Time: 21:53
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class SystemStatusModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'system_status';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -38,6 +44,9 @@ class SystemStatusModel extends AbstractPathfinderModel {
]
];
+ /**
+ * @var array
+ */
protected static $tableData = [
[
'id' => 1,
diff --git a/app/main/model/pathfinder/systemtypemodel.php b/app/Model/Pathfinder/SystemTypeModel.php
similarity index 96%
rename from app/main/model/pathfinder/systemtypemodel.php
rename to app/Model/Pathfinder/SystemTypeModel.php
index b4c18db5..8e026e36 100644
--- a/app/main/model/pathfinder/systemtypemodel.php
+++ b/app/Model/Pathfinder/SystemTypeModel.php
@@ -6,7 +6,7 @@
* Time: 21:59
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
diff --git a/app/main/model/pathfinder/usercharactermodel.php b/app/Model/Pathfinder/UserCharacterModel.php
similarity index 87%
rename from app/main/model/pathfinder/usercharactermodel.php
rename to app/Model/Pathfinder/UserCharacterModel.php
index e96cb7ed..492d7993 100644
--- a/app/main/model/pathfinder/usercharactermodel.php
+++ b/app/Model/Pathfinder/UserCharacterModel.php
@@ -6,14 +6,20 @@
* Time: 21:49
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
class UserCharacterModel extends AbstractPathfinderModel {
+ /**
+ * @var string
+ */
protected $table = 'user_character';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'active' => [
'type' => Schema::DT_BOOL,
@@ -24,7 +30,7 @@ class UserCharacterModel extends AbstractPathfinderModel {
'userId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Pathfinder\UserModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\UserModel',
'constraint' => [
[
'table' => 'user',
@@ -36,7 +42,7 @@ class UserCharacterModel extends AbstractPathfinderModel {
'type' => Schema::DT_INT,
'index' => true,
'unique' => true,
- 'belongs-to-one' => 'Model\Pathfinder\CharacterModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Pathfinder\CharacterModel',
'constraint' => [
[
'table' => 'character',
diff --git a/app/main/model/pathfinder/usermodel.php b/app/Model/Pathfinder/UserModel.php
similarity index 96%
rename from app/main/model/pathfinder/usermodel.php
rename to app/Model/Pathfinder/UserModel.php
index 6a01c6fa..51bce730 100644
--- a/app/main/model/pathfinder/usermodel.php
+++ b/app/Model/Pathfinder/UserModel.php
@@ -6,14 +6,14 @@
* Time: 20:43
*/
-namespace Model\Pathfinder;
+namespace Exodus4D\Pathfinder\Model\Pathfinder;
use DB\SQL\Schema;
-use Controller;
-use Controller\Api\User as User;
-use Exception;
-use lib\Config;
-use lib\logging;
+use Exodus4D\Pathfinder\Controller;
+use Exodus4D\Pathfinder\Controller\Api\User as User;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Logging;
+use Exodus4D\Pathfinder\Exception;
class UserModel extends AbstractPathfinderModel {
@@ -46,7 +46,7 @@ class UserModel extends AbstractPathfinderModel {
'validate' => true
],
'userCharacters' => [
- 'has-many' => ['Model\Pathfinder\UserCharacterModel', 'userId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Pathfinder\UserCharacterModel', 'userId']
]
];
@@ -55,7 +55,7 @@ class UserModel extends AbstractPathfinderModel {
* -> ! caution ! this function returns sensitive data! (e.g. email,..)
* -> user getSimpleData() for faster performance and public user data
* @return \stdClass
- * @throws Exception
+ * @throws \Exception
*/
public function getData() : \stdClass {
@@ -207,7 +207,7 @@ class UserModel extends AbstractPathfinderModel {
* @param int $characterId
* @param int $ttl
* @return CharacterModel|null
- * @throws Exception
+ * @throws \Exception
*/
public function getSessionCharacter(int $characterId = 0, int $ttl = self::DEFAULT_SQL_TTL) : ?CharacterModel {
$data = [];
@@ -285,7 +285,7 @@ class UserModel extends AbstractPathfinderModel {
* -> EITHER - the current active one for the current user
* -> OR - get the first active one
* @return null|CharacterModel
- * @throws Exception
+ * @throws \Exception
*/
public function getActiveCharacter() : ?CharacterModel {
$activeCharacter = null;
diff --git a/app/main/model/universe/alliancemodel.php b/app/Model/Universe/AllianceModel.php
similarity index 86%
rename from app/main/model/universe/alliancemodel.php
rename to app/Model/Universe/AllianceModel.php
index 7a1b3f49..325f4745 100644
--- a/app/main/model/universe/alliancemodel.php
+++ b/app/Model/Universe/AllianceModel.php
@@ -1,7 +1,7 @@
[
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\FactionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\FactionModel',
'constraint' => [
[
'table' => 'faction',
@@ -42,10 +42,10 @@ class AllianceModel extends AbstractUniverseModel {
]
],
'corporations' => [
- 'has-many' => ['Model\Universe\CorporationModel', 'allianceId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\CorporationModel', 'allianceId']
],
'sovereigntySystems' => [
- 'has-many' => ['Model\Universe\SovereigntyMapModel', 'allianceId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SovereigntyMapModel', 'allianceId']
]
];
@@ -85,7 +85,7 @@ class AllianceModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getAllianceData($id);
+ $data = self::getF3()->ccpClient()->send('getAlliance', $id);
if(!empty($data) && !isset($data['error'])){
if($data['factionId']){
/**
diff --git a/app/main/model/universe/categorymodel.php b/app/Model/Universe/CategoryModel.php
similarity index 93%
rename from app/main/model/universe/categorymodel.php
rename to app/Model/Universe/CategoryModel.php
index 3d533143..df0b7f3e 100644
--- a/app/main/model/universe/categorymodel.php
+++ b/app/Model/Universe/CategoryModel.php
@@ -6,14 +6,20 @@
* Time: 23:49
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
class CategoryModel extends AbstractUniverseModel {
+ /**
+ * @var string
+ */
protected $table = 'category';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'name' => [
'type' => Schema::DT_VARCHAR128,
@@ -27,7 +33,7 @@ class CategoryModel extends AbstractUniverseModel {
'index' => true
],
'groups' => [
- 'has-many' => ['Model\Universe\GroupModel', 'categoryId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\GroupModel', 'categoryId']
]
];
@@ -172,14 +178,14 @@ class CategoryModel extends AbstractUniverseModel {
* @return array
*/
public static function getUniverseCategoryData(int $id) : array {
- return self::getF3()->ccpClient()->getUniverseCategoryData($id);
+ return self::getF3()->ccpClient()->send('getUniverseCategory', $id);
}
/**
* @return array
*/
public static function getUniverseCategories() : array {
- return self::getF3()->ccpClient()->getUniverseCategories();
+ return self::getF3()->ccpClient()->send('getUniverseCategories');
}
/**
diff --git a/app/main/model/universe/constellationmodel.php b/app/Model/Universe/ConstellationModel.php
similarity index 84%
rename from app/main/model/universe/constellationmodel.php
rename to app/Model/Universe/ConstellationModel.php
index 1f061ecf..9abd2af5 100644
--- a/app/main/model/universe/constellationmodel.php
+++ b/app/Model/Universe/ConstellationModel.php
@@ -6,7 +6,7 @@
* Time: 16:49
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -29,7 +29,7 @@ class ConstellationModel extends AbstractUniverseModel {
'regionId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\RegionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\RegionModel',
'constraint' => [
[
'table' => 'region',
@@ -54,10 +54,10 @@ class ConstellationModel extends AbstractUniverseModel {
'default' => 0
],
'systems' => [
- 'has-many' => ['Model\Universe\SystemModel', 'constellationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SystemModel', 'constellationId']
],
'systemNeighbours' => [
- 'has-many' => ['Model\Universe\SystemNeighbourModel', 'constellationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SystemNeighbourModel', 'constellationId']
]
];
@@ -80,7 +80,7 @@ class ConstellationModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseConstellationData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseConstellation', $id);
if(!empty($data)){
/**
* @var $region RegionModel
@@ -99,7 +99,7 @@ class ConstellationModel extends AbstractUniverseModel {
*/
public function loadSystemsData(){
if( !$this->dry() ){
- $data = self::getF3()->ccpClient()->getUniverseConstellationData($this->_id);
+ $data = self::getF3()->ccpClient()->send('getUniverseConstellation', $this->_id);
if(!empty($data)){
foreach((array)$data['systems'] as $systemId){
/**
diff --git a/app/main/model/universe/corporationmodel.php b/app/Model/Universe/CorporationModel.php
similarity index 85%
rename from app/main/model/universe/corporationmodel.php
rename to app/Model/Universe/CorporationModel.php
index d672bc13..447f06f9 100644
--- a/app/main/model/universe/corporationmodel.php
+++ b/app/Model/Universe/CorporationModel.php
@@ -1,7 +1,7 @@
[
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\FactionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\FactionModel',
'constraint' => [
[
'table' => 'faction',
@@ -54,7 +54,7 @@ class CorporationModel extends AbstractUniverseModel {
'allianceId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\AllianceModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\AllianceModel',
'constraint' => [
[
'table' => 'alliance',
@@ -63,10 +63,10 @@ class CorporationModel extends AbstractUniverseModel {
]
],
'sovereigntySystems' => [
- 'has-many' => ['Model\Universe\SovereigntyMapModel', 'corporationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SovereigntyMapModel', 'corporationId']
],
'stations' => [
- 'has-many' => ['Model\Universe\StationModel', 'corporationId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StationModel', 'corporationId']
]
];
@@ -105,10 +105,10 @@ class CorporationModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getCorporationData($id);
+ $data = self::getF3()->ccpClient()->send('getCorporation', $id);
if(!empty($data) && !isset($data['error'])){
// check for NPC corporation
- $data['isNPC'] = self::getF3()->ccpClient()->isNpcCorporation($id);
+ $data['isNPC'] = in_array($id, self::getF3()->ccpClient()->send('getNpcCorporations'));
if($data['factionId']){
/**
diff --git a/app/main/model/universe/dogmaattributemodel.php b/app/Model/Universe/DogmaAttributeModel.php
similarity index 91%
rename from app/main/model/universe/dogmaattributemodel.php
rename to app/Model/Universe/DogmaAttributeModel.php
index 7936c2a8..e06c2851 100644
--- a/app/main/model/universe/dogmaattributemodel.php
+++ b/app/Model/Universe/DogmaAttributeModel.php
@@ -6,7 +6,7 @@
* Time: 22:00
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -65,7 +65,7 @@ class DogmaAttributeModel extends AbstractUniverseModel {
'default' => null
],
'attributeTypes' => [
- 'has-many' => ['Model\Universe\TypeAttributeModel', 'attributeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\TypeAttributeModel', 'attributeId']
]
];
@@ -88,7 +88,7 @@ class DogmaAttributeModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getDogmaAttributeData($id);
+ $data = self::getF3()->ccpClient()->send('getDogmaAttribute', $id);
if(!empty($data) && !isset($data['error'])){
$this->copyfrom($data, ['id', 'name', 'displayName', 'description', 'published', 'stackable', 'highIsGood', 'defaultValue', 'iconId', 'unitId']);
$this->save();
diff --git a/app/main/model/universe/factionmodel.php b/app/Model/Universe/FactionModel.php
similarity index 73%
rename from app/main/model/universe/factionmodel.php
rename to app/Model/Universe/FactionModel.php
index bc4623ac..a4b46661 100644
--- a/app/main/model/universe/factionmodel.php
+++ b/app/Model/Universe/FactionModel.php
@@ -6,7 +6,7 @@
* Time: 09:51
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -47,22 +47,22 @@ class FactionModel extends AbstractUniverseModel {
'default' => 0
],
'race' => [ // faction API endpoint dont have "raceId" data, but race API endpoint has
- 'has-one' => ['Model\Universe\RaceModel', 'factionId']
+ 'has-one' => ['Exodus4D\Pathfinder\Model\Universe\RaceModel', 'factionId']
],
'alliances' => [
- 'has-many' => ['Model\Universe\AllianceModel', 'factionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\AllianceModel', 'factionId']
],
'corporations' => [
- 'has-many' => ['Model\Universe\CorporationModel', 'factionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\CorporationModel', 'factionId']
],
'sovereigntySystems' => [
- 'has-many' => ['Model\Universe\SovereigntyMapModel', 'factionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SovereigntyMapModel', 'factionId']
],
'factionWarSystemOwners' => [
- 'has-many' => ['Model\Universe\FactionWarSystemModel', 'ownerFactionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\FactionWarSystemModel', 'ownerFactionId']
],
'factionWarSystemOccupiers' => [
- 'has-many' => ['Model\Universe\FactionWarSystemModel', 'occupierFactionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\FactionWarSystemModel', 'occupierFactionId']
]
];
@@ -84,7 +84,7 @@ class FactionModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseFactionData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseFaction', $id);
if(!empty($data) && !isset($data['error'])){
$this->copyfrom($data, ['id', 'name', 'description', 'sizeFactor', 'stationCount', 'stationSystemCount']);
$this->save();
diff --git a/app/main/model/universe/factionwarsystemmodel.php b/app/Model/Universe/FactionWarSystemModel.php
similarity index 90%
rename from app/main/model/universe/factionwarsystemmodel.php
rename to app/Model/Universe/FactionWarSystemModel.php
index 943cd09b..807010a3 100644
--- a/app/main/model/universe/factionwarsystemmodel.php
+++ b/app/Model/Universe/FactionWarSystemModel.php
@@ -1,7 +1,7 @@
Schema::DT_INT,
'index' => true,
'unique' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -32,7 +32,7 @@ class FactionWarSystemModel extends AbstractUniverseModel {
'ownerFactionId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\FactionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\FactionModel',
'constraint' => [
[
'table' => 'faction',
@@ -43,7 +43,7 @@ class FactionWarSystemModel extends AbstractUniverseModel {
'occupierFactionId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\FactionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\FactionModel',
'constraint' => [
[
'table' => 'faction',
diff --git a/app/main/model/universe/groupmodel.php b/app/Model/Universe/GroupModel.php
similarity index 93%
rename from app/main/model/universe/groupmodel.php
rename to app/Model/Universe/GroupModel.php
index 1bbf5076..69010a01 100644
--- a/app/main/model/universe/groupmodel.php
+++ b/app/Model/Universe/GroupModel.php
@@ -6,7 +6,7 @@
* Time: 23:58
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -40,7 +40,7 @@ class GroupModel extends AbstractUniverseModel {
'categoryId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\CategoryModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\CategoryModel',
'constraint' => [
[
'table' => 'category',
@@ -50,7 +50,7 @@ class GroupModel extends AbstractUniverseModel {
'validate' => 'notDry'
],
'types' => [
- 'has-many' => ['Model\Universe\TypeModel', 'groupId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\TypeModel', 'groupId']
]
];
@@ -178,14 +178,14 @@ class GroupModel extends AbstractUniverseModel {
* @return array
*/
public static function getUniverseGroupData(int $id) : array {
- return self::getF3()->ccpClient()->getUniverseGroupData($id);
+ return self::getF3()->ccpClient()->send('getUniverseGroup', $id);
}
/**
* @return array
*/
public static function getUniverseGroups() : array {
- return self::getF3()->ccpClient()->getUniverseGroups();
+ return self::getF3()->ccpClient()->send('getUniverseGroups');
}
/**
diff --git a/app/main/model/universe/planetmodel.php b/app/Model/Universe/PlanetModel.php
similarity index 87%
rename from app/main/model/universe/planetmodel.php
rename to app/Model/Universe/PlanetModel.php
index 6b7eefb4..3d07ab83 100644
--- a/app/main/model/universe/planetmodel.php
+++ b/app/Model/Universe/PlanetModel.php
@@ -6,14 +6,20 @@
* Time: 01:12
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
class PlanetModel extends AbstractUniverseModel {
+ /**
+ * @var string
+ */
protected $table = 'planet';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'name' => [
'type' => Schema::DT_VARCHAR128,
@@ -23,7 +29,7 @@ class PlanetModel extends AbstractUniverseModel {
'systemId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -35,7 +41,7 @@ class PlanetModel extends AbstractUniverseModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\TypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\TypeModel',
'constraint' => [
[
'table' => 'type',
@@ -81,7 +87,7 @@ class PlanetModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniversePlanetData($id);
+ $data = self::getF3()->ccpClient()->send('getUniversePlanet', $id);
if(!empty($data)){
/**
* @var $system SystemModel
diff --git a/app/main/model/universe/racemodel.php b/app/Model/Universe/RaceModel.php
similarity index 86%
rename from app/main/model/universe/racemodel.php
rename to app/Model/Universe/RaceModel.php
index deea0ed0..45c265ff 100644
--- a/app/main/model/universe/racemodel.php
+++ b/app/Model/Universe/RaceModel.php
@@ -6,7 +6,7 @@
* Time: 03:21
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -32,7 +32,7 @@ class RaceModel extends AbstractUniverseModel {
'factionId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\FactionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\FactionModel',
'constraint' => [
[
'table' => 'faction',
@@ -42,7 +42,7 @@ class RaceModel extends AbstractUniverseModel {
'validate' => 'notDry'
],
'stations' => [
- 'has-many' => ['Model\Universe\StationModel', 'raceId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StationModel', 'raceId']
]
];
@@ -66,7 +66,7 @@ class RaceModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseRaceData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseRace', $id);
if(!empty($data) && !isset($data['error'])){
/**
* @var $faction FactionModel
diff --git a/app/main/model/universe/regionmodel.php b/app/Model/Universe/RegionModel.php
similarity index 81%
rename from app/main/model/universe/regionmodel.php
rename to app/Model/Universe/RegionModel.php
index 77b84fc7..a5b72f67 100644
--- a/app/main/model/universe/regionmodel.php
+++ b/app/Model/Universe/RegionModel.php
@@ -6,7 +6,7 @@
* Time: 15:20
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -31,10 +31,10 @@ class RegionModel extends AbstractUniverseModel {
'type' => Schema::DT_TEXT
],
'constellations' => [
- 'has-many' => ['Model\Universe\ConstellationModel', 'regionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\ConstellationModel', 'regionId']
],
'systemNeighbours' => [
- 'has-many' => ['Model\Universe\SystemNeighbourModel', 'regionId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SystemNeighbourModel', 'regionId']
]
];
@@ -56,7 +56,7 @@ class RegionModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseRegionData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseRegion', $id);
if(!empty($data)){
$this->copyfrom($data, ['id', 'name', 'description']);
$this->save();
@@ -68,7 +68,7 @@ class RegionModel extends AbstractUniverseModel {
*/
public function loadConstellationsData(){
if( !$this->dry() ){
- $data = self::getF3()->ccpClient()->getUniverseRegionData($this->_id);
+ $data = self::getF3()->ccpClient()->send('getUniverseRegion', $this->_id);
if(!empty($data)){
foreach((array)$data['constellations'] as $constellationsId){
/**
diff --git a/app/main/model/universe/sovereigntymapmodel.php b/app/Model/Universe/SovereigntyMapModel.php
similarity index 85%
rename from app/main/model/universe/sovereigntymapmodel.php
rename to app/Model/Universe/SovereigntyMapModel.php
index 59b18b2c..6ac02c29 100644
--- a/app/main/model/universe/sovereigntymapmodel.php
+++ b/app/Model/Universe/SovereigntyMapModel.php
@@ -1,7 +1,7 @@
Schema::DT_INT,
'index' => true,
'unique' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -32,7 +32,7 @@ class SovereigntyMapModel extends AbstractUniverseModel {
'factionId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\FactionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\FactionModel',
'constraint' => [
[
'table' => 'faction',
@@ -43,7 +43,7 @@ class SovereigntyMapModel extends AbstractUniverseModel {
'allianceId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\AllianceModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\AllianceModel',
'constraint' => [
[
'table' => 'alliance',
@@ -54,7 +54,7 @@ class SovereigntyMapModel extends AbstractUniverseModel {
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\CorporationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
diff --git a/app/main/model/universe/starmodel.php b/app/Model/Universe/StarModel.php
similarity index 89%
rename from app/main/model/universe/starmodel.php
rename to app/Model/Universe/StarModel.php
index 94d21876..197273e5 100644
--- a/app/main/model/universe/starmodel.php
+++ b/app/Model/Universe/StarModel.php
@@ -6,7 +6,7 @@
* Time: 23:52
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -29,7 +29,7 @@ class StarModel extends AbstractUniverseModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\TypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\TypeModel',
'constraint' => [
[
'table' => 'type',
@@ -64,7 +64,7 @@ class StarModel extends AbstractUniverseModel {
'default' => null
],
'system' => [
- 'has-one' => ['Model\Universe\SystemModel', 'starId']
+ 'has-one' => ['Exodus4D\Pathfinder\Model\Universe\SystemModel', 'starId']
]
];
@@ -86,7 +86,7 @@ class StarModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseStarData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseStar', $id);
if(!empty($data)){
/**
* @var $type TypeModel
diff --git a/app/main/model/universe/stargatemodel.php b/app/Model/Universe/StargateModel.php
similarity index 90%
rename from app/main/model/universe/stargatemodel.php
rename to app/Model/Universe/StargateModel.php
index cbc32a58..f8915d7b 100644
--- a/app/main/model/universe/stargatemodel.php
+++ b/app/Model/Universe/StargateModel.php
@@ -6,14 +6,20 @@
* Time: 04:30
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
class StargateModel extends AbstractUniverseModel {
+ /**
+ * @var string
+ */
protected $table = 'stargate';
+ /**
+ * @var array
+ */
protected $fieldConf = [
'name' => [
'type' => Schema::DT_VARCHAR128,
@@ -23,7 +29,7 @@ class StargateModel extends AbstractUniverseModel {
'systemId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -35,7 +41,7 @@ class StargateModel extends AbstractUniverseModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\TypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\TypeModel',
'constraint' => [
[
'table' => 'type',
@@ -47,7 +53,7 @@ class StargateModel extends AbstractUniverseModel {
'destinationSystemId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -88,7 +94,7 @@ class StargateModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseStargateData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseStargate', $id);
if(!empty($data)){
diff --git a/app/main/model/universe/stationmodel.php b/app/Model/Universe/StationModel.php
similarity index 90%
rename from app/main/model/universe/stationmodel.php
rename to app/Model/Universe/StationModel.php
index d890ea59..daafb4a3 100644
--- a/app/main/model/universe/stationmodel.php
+++ b/app/Model/Universe/StationModel.php
@@ -6,7 +6,7 @@
* Time: 03:00
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -29,7 +29,7 @@ class StationModel extends AbstractUniverseModel {
'systemId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -41,7 +41,7 @@ class StationModel extends AbstractUniverseModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\TypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\TypeModel',
'constraint' => [
[
'table' => 'type',
@@ -53,7 +53,7 @@ class StationModel extends AbstractUniverseModel {
'corporationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\CorporationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\CorporationModel',
'constraint' => [
[
'table' => 'corporation',
@@ -64,7 +64,7 @@ class StationModel extends AbstractUniverseModel {
'raceId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\RaceModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\RaceModel',
'constraint' => [
[
'table' => 'race',
@@ -123,7 +123,7 @@ class StationModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseStationData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseStation', $id);
if(!empty($data) && !isset($data['error'])){
/**
* @var $system SystemModel
diff --git a/app/main/model/universe/structuremodel.php b/app/Model/Universe/StructureModel.php
similarity index 91%
rename from app/main/model/universe/structuremodel.php
rename to app/Model/Universe/StructureModel.php
index a1fc0ae4..3ea0828a 100644
--- a/app/main/model/universe/structuremodel.php
+++ b/app/Model/Universe/StructureModel.php
@@ -6,7 +6,7 @@
* Time: 15:56
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL;
use DB\SQL\Schema;
@@ -30,7 +30,7 @@ class StructureModel extends AbstractUniverseModel {
'systemId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -42,7 +42,7 @@ class StructureModel extends AbstractUniverseModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\TypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\TypeModel',
'constraint' => [
[
'table' => 'type',
@@ -90,7 +90,7 @@ class StructureModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseStructureData($id, $accessToken);
+ $data = self::getF3()->ccpClient()->send('getUniverseStructure', $id, $accessToken);
if(!empty($data) && !isset($data['error'])){
/**
* @var $type TypeModel
diff --git a/app/main/model/universe/systemmodel.php b/app/Model/Universe/SystemModel.php
similarity index 93%
rename from app/main/model/universe/systemmodel.php
rename to app/Model/Universe/SystemModel.php
index c59ca342..3775e027 100644
--- a/app/main/model/universe/systemmodel.php
+++ b/app/Model/Universe/SystemModel.php
@@ -6,7 +6,7 @@
* Time: 19:29
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -29,7 +29,7 @@ class SystemModel extends AbstractUniverseModel {
'constellationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\ConstellationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\ConstellationModel',
'constraint' => [
[
'table' => 'constellation',
@@ -41,7 +41,7 @@ class SystemModel extends AbstractUniverseModel {
'starId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\StarModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\StarModel',
'constraint' => [
[
'table' => 'star',
@@ -85,28 +85,28 @@ class SystemModel extends AbstractUniverseModel {
'default' => 0
],
'planets' => [
- 'has-many' => ['Model\Universe\PlanetModel', 'systemId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\PlanetModel', 'systemId']
],
'statics' => [
- 'has-many' => ['Model\Universe\SystemStaticModel', 'systemId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SystemStaticModel', 'systemId']
],
'stargates' => [
- 'has-many' => ['Model\Universe\StargateModel', 'systemId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StargateModel', 'systemId']
],
'stations' => [
- 'has-many' => ['Model\Universe\StationModel', 'systemId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StationModel', 'systemId']
],
'structures' => [
- 'has-many' => ['Model\Universe\StructureModel', 'systemId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StructureModel', 'systemId']
],
'neighbour' => [
- 'has-one' => ['Model\Universe\SystemNeighbourModel', 'systemId']
+ 'has-one' => ['Exodus4D\Pathfinder\Model\Universe\SystemNeighbourModel', 'systemId']
],
'sovereignty' => [
- 'has-one' => ['Model\Universe\SovereigntyMapModel', 'systemId']
+ 'has-one' => ['Exodus4D\Pathfinder\Model\Universe\SovereigntyMapModel', 'systemId']
],
'factionWar' => [
- 'has-one' => ['Model\Universe\FactionWarSystemModel', 'systemId']
+ 'has-one' => ['Exodus4D\Pathfinder\Model\Universe\FactionWarSystemModel', 'systemId']
]
];
@@ -491,7 +491,7 @@ class SystemModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseSystemData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseSystem', $id);
if(!empty($data)){
/**
@@ -521,7 +521,7 @@ class SystemModel extends AbstractUniverseModel {
*/
public function loadPlanetsData(){
if($this->valid()){
- $data = self::getF3()->ccpClient()->getUniverseSystemData($this->_id);
+ $data = self::getF3()->ccpClient()->send('getUniverseSystem', $this->_id);
if($data['planets']){
// planets are optional since ESI v4 (e.g. Abyssal systems)
foreach((array)$data['planets'] as $planetData){
@@ -542,7 +542,7 @@ class SystemModel extends AbstractUniverseModel {
*/
public function loadStargatesData(){
if($this->valid()){
- $data = self::getF3()->ccpClient()->getUniverseSystemData($this->_id);
+ $data = self::getF3()->ccpClient()->send('getUniverseSystem', $this->_id);
if($data['stargates']){
foreach((array)$data['stargates'] as $stargateId){
/**
@@ -561,7 +561,7 @@ class SystemModel extends AbstractUniverseModel {
*/
public function loadStationsData(){
if($this->valid()){
- $data = self::getF3()->ccpClient()->getUniverseSystemData($this->_id);
+ $data = self::getF3()->ccpClient()->send('getUniverseSystem', $this->_id);
if($data['stations']){
foreach((array)$data['stations'] as $stationId){
/**
diff --git a/app/main/model/universe/systemneighbourmodel.php b/app/Model/Universe/SystemNeighbourModel.php
similarity index 87%
rename from app/main/model/universe/systemneighbourmodel.php
rename to app/Model/Universe/SystemNeighbourModel.php
index f598565c..0ef5a20c 100644
--- a/app/main/model/universe/systemneighbourmodel.php
+++ b/app/Model/Universe/SystemNeighbourModel.php
@@ -1,7 +1,7 @@
[
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\RegionModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\RegionModel',
'constraint' => [
[
'table' => 'region',
@@ -38,7 +38,7 @@ class SystemNeighbourModel extends AbstractUniverseModel {
'constellationId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\ConstellationModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\ConstellationModel',
'constraint' => [
[
'table' => 'constellation',
@@ -51,7 +51,7 @@ class SystemNeighbourModel extends AbstractUniverseModel {
'type' => Schema::DT_INT,
'index' => true,
'unique' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
diff --git a/app/main/model/universe/systemstaticmodel.php b/app/Model/Universe/SystemStaticModel.php
similarity index 89%
rename from app/main/model/universe/systemstaticmodel.php
rename to app/Model/Universe/SystemStaticModel.php
index a072b123..c62b7b52 100644
--- a/app/main/model/universe/systemstaticmodel.php
+++ b/app/Model/Universe/SystemStaticModel.php
@@ -6,7 +6,7 @@
* Time: 17:50
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -24,7 +24,7 @@ class SystemStaticModel extends AbstractUniverseModel {
'systemId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\SystemModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\SystemModel',
'constraint' => [
[
'table' => 'system',
@@ -36,7 +36,7 @@ class SystemStaticModel extends AbstractUniverseModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\TypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\TypeModel',
'constraint' => [
[
'table' => 'type',
diff --git a/app/main/model/universe/typeattributemodel.php b/app/Model/Universe/TypeAttributeModel.php
similarity index 90%
rename from app/main/model/universe/typeattributemodel.php
rename to app/Model/Universe/TypeAttributeModel.php
index eec9d4bf..41011af6 100644
--- a/app/main/model/universe/typeattributemodel.php
+++ b/app/Model/Universe/TypeAttributeModel.php
@@ -6,7 +6,7 @@
* Time: 22:00
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
@@ -24,7 +24,7 @@ class TypeAttributeModel extends AbstractUniverseModel {
'typeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\TypeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\TypeModel',
'constraint' => [
[
'table' => 'type',
@@ -36,7 +36,7 @@ class TypeAttributeModel extends AbstractUniverseModel {
'attributeId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\DogmaAttributeModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\DogmaAttributeModel',
'constraint' => [
[
'table' => 'dogma_attribute',
diff --git a/app/main/model/universe/typemodel.php b/app/Model/Universe/TypeModel.php
similarity index 92%
rename from app/main/model/universe/typemodel.php
rename to app/Model/Universe/TypeModel.php
index 4402d741..88b78f75 100644
--- a/app/main/model/universe/typemodel.php
+++ b/app/Model/Universe/TypeModel.php
@@ -6,11 +6,11 @@
* Time: 15:56
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
use DB\SQL\Schema;
-use lib\Config;
-use lib\Util;
+use Exodus4D\Pathfinder\Lib\Config;
+use Exodus4D\Pathfinder\Lib\Util;
class TypeModel extends AbstractUniverseModel {
@@ -72,7 +72,7 @@ class TypeModel extends AbstractUniverseModel {
'groupId' => [
'type' => Schema::DT_INT,
'index' => true,
- 'belongs-to-one' => 'Model\Universe\GroupModel',
+ 'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\GroupModel',
'constraint' => [
[
'table' => 'group',
@@ -104,25 +104,25 @@ class TypeModel extends AbstractUniverseModel {
'index' => true
],
'stations' => [
- 'has-many' => ['Model\Universe\StationModel', 'typeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StationModel', 'typeId']
],
'structures' => [
- 'has-many' => ['Model\Universe\StructureModel', 'typeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StructureModel', 'typeId']
],
'planets' => [
- 'has-many' => ['Model\Universe\PlanetModel', 'typeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\PlanetModel', 'typeId']
],
'stars' => [
- 'has-many' => ['Model\Universe\StarModel', 'typeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StarModel', 'typeId']
],
'attributes' => [
- 'has-many' => ['Model\Universe\TypeAttributeModel', 'typeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\TypeAttributeModel', 'typeId']
],
'stargates' => [
- 'has-many' => ['Model\Universe\StargateModel', 'typeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\StargateModel', 'typeId']
],
'statics' => [
- 'has-many' => ['Model\Universe\SystemStaticModel', 'typeId']
+ 'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SystemStaticModel', 'typeId']
]
];
@@ -352,7 +352,7 @@ class TypeModel extends AbstractUniverseModel {
* @param array $additionalOptions
*/
protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
- $data = self::getF3()->ccpClient()->getUniverseTypesData($id);
+ $data = self::getF3()->ccpClient()->send('getUniverseType', $id);
if(!empty($data)){
$this->manipulateDogmaAttributes($data);
diff --git a/app/main/model/universe/abstractuniversemodel.php b/app/Model/Universe/abstractuniversemodel.php
similarity index 98%
rename from app/main/model/universe/abstractuniversemodel.php
rename to app/Model/Universe/abstractuniversemodel.php
index f2b85df8..cc5c3a9a 100644
--- a/app/main/model/universe/abstractuniversemodel.php
+++ b/app/Model/Universe/abstractuniversemodel.php
@@ -6,9 +6,9 @@
* Time: 14:18
*/
-namespace Model\Universe;
+namespace Exodus4D\Pathfinder\Model\Universe;
-use Model\AbstractModel;
+use Exodus4D\Pathfinder\Model\AbstractModel;
abstract class AbstractUniverseModel extends AbstractModel {
diff --git a/app/config.ini b/app/config.ini
index 8eb9ab6c..59b0dee6 100644
--- a/app/config.ini
+++ b/app/config.ini
@@ -52,7 +52,7 @@ SEED = {{ md5(@SERVER.SERVER_NAME) }}
; folder=[DIR]
; - Cache data is stored on disc
; redis=[SERVER]
-; - Cache data is stored in Redis. redis=[host]:[port]:[db] (e.g. redis=localhost:6379:1)
+; - Cache data is stored in Redis. redis=[host]:[port]:[db]:[auth] (e.g. redis=localhost:6379:1:myPass)
CACHE = folder=tmp/cache/
; Cache backend for API data
@@ -67,7 +67,7 @@ CACHE = folder=tmp/cache/
; folder=[DIR]
; - Cache data is stored on disc
; redis=[SERVER]
-; - Cache data is stored in Redis. redis=[host]:[port]:[db] (e.g. redis=localhost:6379:2)
+; - Cache data is stored in Redis. redis=[host]:[port]:[db]:[auth] (e.g. redis=localhost:6379:2:myPass)
API_CACHE = {{@CACHE}}
; Cache backend used by PHPs Session handler.
@@ -85,8 +85,8 @@ API_CACHE = {{@CACHE}}
SESSION_CACHE = mysql
; Callback functions ==============================================================================
-ONERROR = Controller\Controller->showError
-UNLOAD = Controller\Controller->unload
+ONERROR = {{ @NAMESPACE }}\Controller\Controller->showError
+UNLOAD = {{ @NAMESPACE }}\Controller\Controller->unload
; Path configurations =============================================================================
; All path configurations are relative to BASE dir and should NOT be changed
@@ -111,8 +111,8 @@ UI = public/
; Autoload folder
; Where PHP attempts to autoload PHP classes at runtime.
; Syntax: [DIR]
-; Default: app/main/
-AUTOLOAD = app/main/
+; Default: app/
+;AUTOLOAD = app/
; Favicon folder
; Syntax: [DIR]
@@ -137,6 +137,8 @@ CONF.DEFAULT = app/
[configs]
{{@CONF.DEFAULT}}routes.ini = true
{{@CONF.DEFAULT}}pathfinder.ini = true
+{{@CONF.DEFAULT}}plugin.ini = true
{{@CONF.CUSTOM}}pathfinder.ini = true
+{{@CONF.CUSTOM}}plugin.ini = true
{{@CONF.DEFAULT}}requirements.ini = true
{{@CONF.DEFAULT}}cron.ini = true
\ No newline at end of file
diff --git a/app/cron.ini b/app/cron.ini
index de4f53d7..f7c841e1 100644
--- a/app/cron.ini
+++ b/app/cron.ini
@@ -25,48 +25,48 @@ downtime = 0 11 * * *
[CRON.jobs]
; delete EOL connections
-deleteEolConnections = Cron\MapUpdate->deleteEolConnections, @fiveMinutes
+deleteEolConnections = {{ @NAMESPACE }}\Cron\MapUpdate->deleteEolConnections, @fiveMinutes
; delete expired wh connections
-deleteExpiredConnections = Cron\MapUpdate->deleteExpiredConnections, @hourly
+deleteExpiredConnections = {{ @NAMESPACE }}\Cron\MapUpdate->deleteExpiredConnections, @hourly
; delete character log data
-deleteLogData = Cron\CharacterUpdate->deleteLogData, @instant
+deleteLogData = {{ @NAMESPACE }}\Cron\CharacterUpdate->deleteLogData, @instant
; delete expired signatures
-deleteSignatures = Cron\MapUpdate->deleteSignatures, @halfHour
+deleteSignatures = {{ @NAMESPACE }}\Cron\MapUpdate->deleteSignatures, @halfHour
; import system data (jump, kill,..) from CCP API
-importSystemData = Cron\CcpSystemsUpdate->importSystemData, @halfPastHour
+importSystemData = {{ @NAMESPACE }}\Cron\CcpSystemsUpdate->importSystemData, @halfPastHour
; disable outdated maps
-deactivateMapData = Cron\MapUpdate->deactivateMapData, @hourly
+deactivateMapData = {{ @NAMESPACE }}\Cron\MapUpdate->deactivateMapData, @hourly
; clean up character data (kick, ban,..)
-cleanUpCharacterData = Cron\CharacterUpdate->cleanUpCharacterData, @hourly
+cleanUpCharacterData = {{ @NAMESPACE }}\Cron\CharacterUpdate->cleanUpCharacterData, @hourly
; delete disabled maps
-deleteMapData = Cron\MapUpdate->deleteMapData, @downtime
+deleteMapData = {{ @NAMESPACE }}\Cron\MapUpdate->deleteMapData, @downtime
; delete expired character cookie authentication data
-deleteAuthenticationData = Cron\CharacterUpdate->deleteAuthenticationData, @downtime
+deleteAuthenticationData = {{ @NAMESPACE }}\Cron\CharacterUpdate->deleteAuthenticationData, @downtime
; delete expired cache files
-deleteExpiredCacheData = Cron\Cache->deleteExpiredCacheData, @downtime
+deleteExpiredCacheData = {{ @NAMESPACE }}\Cron\Cache->deleteExpiredCacheData, @downtime
; delete old statistics (activity log) data
-deleteStatisticsData = Cron\StatisticsUpdate->deleteStatisticsData, @weekly
+deleteStatisticsData = {{ @NAMESPACE }}\Cron\StatisticsUpdate->deleteStatisticsData, @weekly
; truncate map history log files
-truncateMapHistoryLogFiles = Cron\MapHistory->truncateMapHistoryLogFiles, @halfHour
+truncateMapHistoryLogFiles = {{ @NAMESPACE }}\Cron\MapHistory->truncateMapHistoryLogFiles, @halfHour
; sync "sovereignty" and "faction warfare" data from CCP´s ESI API
-updateSovereigntyData = Cron\Universe->updateSovereigntyData, @halfPastHour
+updateSovereigntyData = {{ @NAMESPACE }}\Cron\Universe->updateSovereigntyData, @halfPastHour
; sync static system data from CCP´s ESI API
; -> Job is WIP!
-;updateUniverseSystems = Cron\Universe->updateUniverseSystems, @instant
+;updateUniverseSystems = {{ @NAMESPACE }}\Cron\Universe->updateUniverseSystems, @instant
; bootstrap job for "eve_universe" DB from CCP´s ESI API
; -> Only for development! This job is used to build the initial export/sql/eve_universe.sql
-;setup = Cron\Universe->setup, @instant
\ No newline at end of file
+;setup = {{ @NAMESPACE }}\Cron\Universe->setup, @instant
\ No newline at end of file
diff --git a/app/environment.ini b/app/environment.ini
index 409cdf58..54075b4c 100644
--- a/app/environment.ini
+++ b/app/environment.ini
@@ -35,7 +35,7 @@ CCP_SSO_DOWNTIME = 11:00
; CCP ESI API
CCP_ESI_URL = https://esi.evetech.net
CCP_ESI_DATASOURCE = singularity
-CCP_ESI_SCOPES = esi-location.read_online.v1,esi-location.read_location.v1,esi-location.read_ship_type.v1,esi-ui.write_waypoint.v1,esi-ui.open_window.v1,esi-universe.read_structures.v1,esi-corporations.read_corporation_membership.v1,esi-clones.read_clones.v1
+CCP_ESI_SCOPES = esi-location.read_online.v1,esi-location.read_location.v1,esi-location.read_ship_type.v1,esi-ui.write_waypoint.v1,esi-ui.open_window.v1,esi-universe.read_structures.v1,esi-corporations.read_corporation_membership.v1,esi-clones.read_clones.v1,esi-characters.read_corporation_roles.v1
CCP_ESI_SCOPES_ADMIN =
; SMTP settings (optional)
@@ -88,7 +88,7 @@ CCP_SSO_DOWNTIME = 11:00
; CCP ESI API
CCP_ESI_URL = https://esi.evetech.net
CCP_ESI_DATASOURCE = tranquility
-CCP_ESI_SCOPES = esi-location.read_online.v1,esi-location.read_location.v1,esi-location.read_ship_type.v1,esi-ui.write_waypoint.v1,esi-ui.open_window.v1,esi-universe.read_structures.v1,esi-corporations.read_corporation_membership.v1,esi-clones.read_clones.v1
+CCP_ESI_SCOPES = esi-location.read_online.v1,esi-location.read_location.v1,esi-location.read_ship_type.v1,esi-ui.write_waypoint.v1,esi-ui.open_window.v1,esi-universe.read_structures.v1,esi-corporations.read_corporation_membership.v1,esi-clones.read_clones.v1,esi-characters.read_corporation_roles.v1
CCP_ESI_SCOPES_ADMIN =
; SMTP settings (optional)
diff --git a/app/lib/CHANGELOG.md b/app/lib/CHANGELOG.md
deleted file mode 100644
index 4960ea2c..00000000
--- a/app/lib/CHANGELOG.md
+++ /dev/null
@@ -1,915 +0,0 @@
-CHANGELOG
-
-3.6.5 (24 December 2018)
-* NEW: Log, added timestamp to each line
-* NEW: Auth, added support for custom compare method, [#116](https://github.com/bcosca/fatfree-core/issues/116)
-* NEW: cache tag support for mongo & jig mapper, ref [#166](https://github.com/bcosca/fatfree-core/issues/116)
-* NEW: Allow PHP functions as template token filters
-* Web: Fix double redirect bug when running cURL with open_basedir disabled
-* Web: Cope with responses from HTTP/2 servers
-* Web->filler: remove very first space, when $std is false
-* Web\OAuth2: Cope with HTTP/2 responses
-* Web\OAuth2: take Content-Type header into account for json decoding, [#250](https://github.com/bcosca/fatfree-core/issues/250) [#251](https://github.com/bcosca/fatfree-core/issues/251)
-* Web\OAuth2: fixed empty results on some endpoints [#250](https://github.com/bcosca/fatfree-core/issues/250)
-* DB\SQL\Mapper: optimize mapper->count memory usage
-* DB\SQL\Mapper: New table alias operator
-* DB\SQL\Mapper: fix count() performance on non-grouped result sets, [bcosca/fatfree#1114](https://github.com/bcosca/fatfree/issues/1114)
-* DB\SQL: Support for CTE in postgreSQL, [bcosca/fatfree#1107](https://github.com/bcosca/fatfree/issues/1107), [bcosca/fatfree#1116](https://github.com/bcosca/fatfree/issues/1116), [bcosca/fatfree#1021](https://github.com/bcosca/fatfree/issues/1021)
-* DB\SQL->log: Remove extraneous whitespace
-* DB\SQL: Added ability to add inline comments per SQL query
-* CLI\WS, Refactoring: Streamline socket server
-* CLI\WS: Add option for dropping query in OAuth2 URI
-* CLI\WS: Add URL-safe base64 encoding
-* CLI\WS: Detect errors in returned JSON values
-* CLI\WS: Added support for Sec-WebSocket-Protocol header
-* Matrix->calendar: Allow unix timestamp as date argument
-* Basket: Access basket item by _id [#260](https://github.com/bcosca/fatfree-core/issues/260)
-* SMTP: Added TLS 1.2 support [bcosca/fatfree#1115](https://github.com/bcosca/fatfree/issues/1115)
-* SMTP->send: Respect $log argument
-* Base->cast: recognize binary and octal numbers in config
-* Base->cast: add awareness of hexadecimal literals
-* Base->abort: Remove unnecessary Content-Encoding header
-* Base->abort: Ensure headers have not been flushed
-* Base->format: Differentiate between long- and full-date (with localized weekday) formats
-* Base->format: Conform with intl extension's number output
-* Enable route handler to override Access-Control headers in response to OPTIONS request, [#257](https://github.com/bcosca/fatfree-core/issues/257)
-* Augment filters with a var_export function
-* Bug fix php7.3: Fix template parse regex to be compatible with strict PCRE2 rules for hyphen placement in a character class
-* Bug fix, Cache->set: update creation time when updating existing cache entries
-* Bug fix: incorrect ICU date/time formatting
-* Bug fix, Jig: lazy write on empty data
-* Bug fix: Method uppercase to avoid route failure [#252](https://github.com/bcosca/fatfree-core/issues/252)
-* Fixed error description when (PSR-11) `CONTAINER` fails to resolve a class [#253](https://github.com/bcosca/fatfree-core/issues/253)
-* Mitigate CSRF predictability/vulnerability
-* Expose Mapper->factory() method
-
-3.6.4 (19 April 2018)
-* NEW: Added Dependency Injection support with CONTAINER variable [#221](https://github.com/bcosca/fatfree-core/issues/221)
-* NEW: configurable LOGGABLE error codes [#1091](https://github.com/bcosca/fatfree/issues/1091#issuecomment-364674701)
-* NEW: JAR.lifetime option, [#178](https://github.com/bcosca/fatfree-core/issues/178)
-* Template: reduced Prefab calls
-* Template: optimized reflection for better derivative support, [bcosca/fatfree#1088](https://github.com/bcosca/fatfree/issues/1088)
-* Template: optimized parsing for template attributes and tokens
-* DB\Mongo: fixed logging with mongodb extention
-* DB\Jig: added lazy-loading [#7e1cd9b9b89](https://github.com/bcosca/fatfree-core/commit/7e1cd9b9b89c4175d0f6b86ced9d9bd49c04ac39)
-* DB\Jig\Mapper: Added group feature, bcosca/fatfree#616
-* DB\SQL\Mapper: fix PostgreSQL RETURNING ID when no pkey is available, [bcosca/fatfree#1069](https://github.com/bcosca/fatfree/issues/1069), [#230](https://github.com/bcosca/fatfree-core/issues/230)
-* DB\SQL\Mapper: disable order clause auto-quoting when it's already been quoted
-* Web->location: add failsafe for geoip_region_name_by_code() [#GB:Bxyn9xn9AgAJ](https://groups.google.com/d/msg/f3-framework/APau4wnwNzE/Bxyn9xn9AgAJ)
-* Web->request: Added proxy support [#e936361b](https://github.com/bcosca/fatfree-core/commit/e936361bc03010c4c7c38a396562e5e96a8a100d)
-* Web->mime: Added JFIF format
-* Markdown: handle line breaks in paragraph blocks, [bcosca/fatfree#1100](https://github.com/bcosca/fatfree/issues/1100)
-* config: reduced cast calls on parsing config sections
-* Patch empty SERVER_NAME [bcosca/fatfree#1084](https://github.com/bcosca/fatfree/issues/1084)
-* Bugfix: unreliable request headers in Web->request() response [bcosca/fatfree#1092](https://github.com/bcosca/fatfree/issues/1092)
-* Fixed, View->render: utilizing multiple UI paths, [bcosca/fatfree#1083](https://github.com/bcosca/fatfree/issues/1083)
-* Fixed URL parsing with PHP 5.4 [#247](https://github.com/bcosca/fatfree-core/issues/247)
-* Fixed PHP 7.2 warnings when session is active prematurely, [#238](https://github.com/bcosca/fatfree-core/issues/238)
-* Fixed setcookie $expire variable type [#240](https://github.com/bcosca/fatfree-core/issues/240)
-* Fixed expiration time when updating an existing cookie
-
-3.6.3 (31 December 2017)
-* PHP7 fix: remove deprecated (unset) cast
-* Web->request: restricted follow_location to 3XX responses only
-* CLI mode: refactored arguments parsing
-* CLI mode: fixed query string encoding
-* SMTP: Refactor parsing of attachments
-* SMTP: clean-up mail headers for multipart messages, [#1065](https://github.com/bcosca/fatfree/issues/1065)
-* config: fixed performance issues on parsing config files
-* config: cast command parameters in config entries to php type & constant, [#1030](https://github.com/bcosca/fatfree/issues/1030)
-* config: reduced registry calls
-* config: skip hive escaping when resolving dynamic config vars, [#1030](https://github.com/bcosca/fatfree/issues/1030)
-* Bug fix: Incorrect cookie lifetime computation, [#1070](https://github.com/bcosca/fatfree/issues/1070), [#1016](https://github.com/bcosca/fatfree/issues/1016)
-* DB\SQL\Mapper: use RETURNING option instead of a sequence query to get lastInsertId in PostgreSQL, [#1069](https://github.com/bcosca/fatfree/issues/1069), [#230](https://github.com/bcosca/fatfree-core/issues/230)
-* DB\SQL\Session: check if _agent is too long for SQL based sessions [#236](https://github.com/bcosca/fatfree-core/issues/236)
-* DB\SQL\Session: fix Session handler table creation issue on SQL Server, [#899](https://github.com/bcosca/fatfree/issues/899)
-* DB\SQL: fix oracle db issue with empty error variable, [#1072](https://github.com/bcosca/fatfree/issues/1072)
-* DB\SQL\Mapper: fix sorting issues on SQL Server, [#1052](https://github.com/bcosca/fatfree/issues/1052) [#225](https://github.com/bcosca/fatfree-core/issues/225)
-* Prevent directory traversal attacks on filesystem based cache [#1073](https://github.com/bcosca/fatfree/issues/1073)
-* Bug fix, Template: PHP constants used in include with attribute, [#983](https://github.com/bcosca/fatfree/issues/983)
-* Bug fix, Template: Numeric value in expression alters PHP_EOL context
-* Template: use existing linefeed instead of PHP_EOL, [#1048](https://github.com/bcosca/fatfree/issues/1048)
-* Template: make newline interpolation handling configurable [#223](https://github.com/bcosca/fatfree-core/issues/223)
-* Template: add beforerender to Preview
-* fix custom FORMATS without modifiers
-* Cache: Refactor Cache->reset for XCache
-* Cache: loosen reset cache key pattern, [#1041](https://github.com/bcosca/fatfree/issues/1041)
-* XCache: suffix reset only works if xcache.admin.enable_auth is disabled
-* Added HTTP 103 as recently approved by the IETF
-* LDAP changes to for AD flexibility [#227](https://github.com/bcosca/fatfree-core/issues/227)
-* Hide debug trace from ajax errors when DEBUG=0 [#1071](https://github.com/bcosca/fatfree/issues/1071)
-* fix View->render using potentially wrong cache entry
-
-3.6.2 (26 June 2017)
-* Return a status code > 0 when dying on error [#220](https://github.com/bcosca/fatfree-core/issues/220)
-* fix SMTP line width [#215](https://github.com/bcosca/fatfree-core/issues/215)
-* Allow using a custom field for ldap user id checking [#217](https://github.com/bcosca/fatfree-core/issues/217)
-* NEW: DB\SQL->exists: generic method to check if SQL table exists
-* Pass handler to route handler and hooks [#1035](https://github.com/bcosca/fatfree/issues/1035)
-* pass carriage return of multiline dictionary keys
-* Better Web->slug customization
-* fix incorrect header issue [#211](https://github.com/bcosca/fatfree-core/issues/211)
-* fix schema issue on databases with case-sensitive collation, fixes [#209](https://github.com/bcosca/fatfree-core/issues/209)
-* Add filter for deriving C-locale equivalent of a number
-* Bug fix: @LANGUAGE remains unchanged after override
-* abort: added Header pre-check
-* Assemble URL after ONREROUTE
-* Add reroute argument to skip script termination
-* Invoke ONREROUTE after headers are sent
-* SQLite switch to backtick as quote
-* Bug fix: Incorrect timing in SQL query logs
-* DB\SQL\Mapper: Cast return value of count to integer
-* Patched $_SERVER['REQUEST_URI'] to ensure it contains a relative URI
-* Tweak debug verbosity
-* fix php carriage return issue in preview->build [#205](https://github.com/bcosca/fatfree-core/pull/205)
-* fixed template string resolution [#205](https://github.com/bcosca/fatfree-core/pull/205)
-* Fixed unexpected default seed on CACHE set [#1028](https://github.com/bcosca/fatfree/issues/1028)
-* DB\SQL\Mapper: Optimized field escaping on options
-* Optimize template conversion to PHP file
-
-3.6.1 (2 April 2017)
-* NEW: Recaptcha plugin [#194](https://github.com/bcosca/fatfree-core/pull/194)
-* NEW: MB variable for detecting multibyte support
-* NEW: DB\SQL: Cache parsed schema for the TTL duration
-* NEW: quick erase flag on Jig/Mongo/SQL mappers [#193](https://github.com/bcosca/fatfree-core/pull/193)
-* NEW: Allow OPTIONS method to return a response body [#171](https://github.com/bcosca/fatfree-core/pull/171)
-* NEW: Add support for Memcached (bcosca/fatfree#997)
-* NEW: Rudimentary preload resource (HTTP2 server) support via template push()
-* NEW: Add support for new MongoDB driver [#177](https://github.com/bcosca/fatfree-core/pull/177)
-* Changed: template filter are all lowercase now
-* Changed: Fix template lookup inconsistency: removed base dir from UI on render
-* Changed: count() method now has an options argument [#192](https://github.com/bcosca/fatfree-core/pull/192)
-* Changed: SMTP, Spit out error message if any
-* \DB\SQL\Mapper: refactored row count strategy
-* DB\SQL\Mapper: Allow non-scalar values to be assigned as mapper property
-* DB\SQL::PARAM_FLOAT: remove cast to float (#106 and bcosca/fatfree#984) (#191)
-* DB\SQL\mapper->erase: allow empty string
-* DB\SQL\mapper->insert: fields reset after successful INSERT
-* Add option to debounce Cursor->paginate subset [#195](https://github.com/bcosca/fatfree-core/pull/195)
-* View: Don't delete sandboxed variables (#198)
-* Preview: Optimize compilation of template expressions
-* Preview: Use shorthand tag for direct rendering
-* Preview->resolve(): new tweak to allow template persistence as option
-* Web: Expose diacritics translation table
-* SMTP: Enable logging of message body only when $log argument is 'verbose'
-* SMTP: Convert headers to camelcase for consistency
-* make cache seed more flexible, #164
-* Improve trace details for DEBUG>2
-* Enable config() to read from an array of input files
-* Improved alias and reroute regex
-* Make camelCase and snakeCase Unicode-aware
-* format: Provision for optional whitespaces
-* Break APCu-BC dependence
-* Old PHP 5.3 cleanup
-* Debug log must include HTTP query
-* Recognize X-Forwarded-Port header (bcosca/fatfree#1002)
-* Avoid use of deprecated mcrypt module
-* Return only the client's IP when using the `X-Forwarded-For` header to deduce an IP address
-* Remove orphan mutex locks on termination (#157)
-* Use 80 as default port number to avoid issues when `$_SERVER['SERVER_PORT']` is not existing
-* fread replaced with readfile() for simple send() usecase
-* Bug fix: request URI with multiple leading slashes, #203
-* Bug fix: Query generates wrong adhoc field value
-* Bug fix: SMTP stream context issue #200
-* Bug fix: child pseudo class selector in minify, bcosca/fatfree#1008
-* Bug fix: "Undefined index: CLI" error (#197)
-* Bug fix: cast Cache-Control expire time to int, bcosca/fatfree#1004
-* Bug fix: Avoid issuance of multiple Content-Type headers for nested templates
-* Bug fix: wildcard token issue with digits (bcosca/fatfree#996)
-* Bug fix: afterupdate ignored when row does not change
-* Bug fix: session handler read() method for PHP7 (need strict string) #184 #185
-* Bug fix: reroute mocking in CLI mode (#183)
-* Bug fix: Reroute authoritative relative references (#181)
-* Bug fix: locales order and charset hyphen
-* Bug fix: base stripped twice in router (#176)
-
-3.6.0 (19 November 2016)
-* NEW: [cli] request type
-* NEW: console-friendly CLI mode
-* NEW: lexicon caching
-* NEW: Silent operator skips startup error check (#125)
-* NEW: DB\SQL->trans()
-* NEW: custom config section parser, i.e. [conf > Foo::bar]
-* NEW: support for cache tags in SQL
-* NEW: custom FORMATS
-* NEW: Mongo mapper fields whitelist
-* NEW: WebSocket server
-* NEW: Base->extend method (#158)
-* NEW: Implement framework variable caching via config, i.e. FOO = "bar" | 3600
-* NEW: Lightweight OAuth2 client
-* NEW: SEED variable, configurable app-specific hashing prefix (#149, bcosca/fatfree#951, bcosca/fatfree#884, bcosca/fatfree#629)
-* NEW: CLI variable
-* NEW: Web->send, specify custom filename (#124)
-* NEW: Web->send, added flushing flag (#131)
-* NEW: Indexed route wildcards, now exposed in PARAMS['*']
-* Changed: PHP 5.4 is now the minimum version requirement
-* Changed: Prevent database wrappers from being cloned
-* Changed: Router works on PATH instead of URI (#126) NB: PARAMS.0 no longer contains the query string
-* Changed: Removed ALIASES autobuilding (#118)
-* Changed: Route wildcards match empty strings (#119)
-* Changed: Disable default debug highlighting, HIGHLIGHT is false now
-* General PHP 5.4 optimizations
-* Optimized config parsing
-* Optimized Base->recursive
-* Optimized header extraction
-* Optimized cache/expire headers
-* Optimized session_start behaviour (bcosca/fatfree#673)
-* Optimized reroute regex
-* Tweaked cookie removal
-* Better route precedence order
-* Performance tweak: reduced cache calls
-* Refactored lexicon (LOCALES) build-up, much faster now
-* Added turkish locale bug workaround
-* Geo->tzinfo Update to UTC
-* Added Xcache reset (bcosca/fatfree#928)
-* Redis cache: allow db name in dsn
-* SMTP: Improve server emulation responses
-* SMTP: Optimize transmission envelope
-* SMTP: Implement mock transmission
-* SMTP: Various bug fixes and feature improvements
-* SMTP: quit on failed authentication
-* Geo->weather: force metric units
-* Base->until: Implement CLI interoperability
-* Base->format: looser plural syntax
-* Base->format: Force decimal as default number format
-* Base->merge: Added $keep flag to save result to the hive key
-* Base->reroute: Allow array as URL argument for aliasing
-* Base->alias: Allow query string (or array) to be appended to alias
-* Permit reroute to named routes with URL query segment
-* Sync COOKIE global on set()
-* Permit non-hive variables to use JS dot notation
-* RFC2616: Use absolute URIs for Location header
-* Matrix->calendar: Check if calendar extension is loaded
-* Markdown: require start of line/whitespace for text processing (#136)
-* DB\[SQL|Jig|Mongo]->log(FALSE) disables logging
-* DB\SQL->exec: Added timestamp toggle to db log
-* DB\SQL->schema: Remove unnecessary line terminators
-* DB\SQL\Mapper: allow array filter with empty string
-* DB\SQL\Mapper: optimized handling for key-less tables
-* DB\SQL\Mapper: added float support (#106)
-* DB\SQL\Session: increased default column sizes (#148, bcosca/fatfree#931, bcosca/fatfree#950)
-* Web: Catch cURL errors
-* Optimize Web->receive (bcosca/fatfree#930)
-* Web->minify: fix arbitrary file download vulnerability
-* Web->request: fix cache control max-age detection (bcosca/fatfree#908)
-* Web->request: Add request headers & error message to return value (bcosca/fatfree#737)
-* Web->request: Refactored response to HTTP request
-* Web->send flush while sending big files
-* Image->rgb: allow hex strings
-* Image->captcha: Check if GD module supports TrueType
-* Image->load: Return FALSE on load failure
-* Image->resize: keep aspect ratio when only width or height was given
-* Updated OpenID lib (bcosca/fatfree#965)
-* Audit->card: add new mastercard "2" BIN range (bcosca/fatfree#954)
-* Deprecated: Bcrypt class
-* Preview->render: optimized detection to remove short open PHP tags and allow xml tags (#133)
-* Display file and line number in exception handler (bcosca/fatfree#967)
-* Added error reporting level to Base->error and ERROR.level (bcosca/fatfree#957)
-* Added optional custom cache instance to Session (#141)
-* CLI-aware mock()
-* XFRAME and PACKAGE can be switched off now (#128)
-* Bug fix: wrong time calculation on memcache reset (#170)
-* Bug fix: encode CLI parameters
-* Bug fix: Close connection on abort explicitly (#162)
-* Bug fix: Image->identicon, Avoid double-size sprite rotation (and possible segfault)
-* Bug fix: Image->render and Image->dump, removed unnecessary 2nd argument (#146)
-* Bug fix: Magic->offsetset, access property as array element (#147)
-* Bug fix: multi-line custom template tag parsing (bcosca/fatfree#935)
-* Bug fix: cache headers on errors (bcosca/fatfree#885)
-* Bug fix: Web, deprecated CURLOPT_SSL_VERIFYHOST in curl
-* Bug fix: Web, Invalid user error constant (bcosca/fatfree#962)
-* Bug fix: Web->request, redirections for domain-less location (#135)
-* Bug fix: DB\SQL\Mapper, reset changed flag after update (#142, #152)
-* Bug fix: DB\SQL\Mapper, fix changed flag when using assignment operator #143 #150 #151
-* Bug fix: DB\SQL\Mapper, revival of the HAVING clause
-* Bug fix: DB\SQL\Mapper, pgsql with non-integer primary keys (bcosca/fatfree#916)
-* Bug fix: DB\SQL\Session, quote table name (bcosca/fatfree#977)
-* Bug fix: snakeCase returns word starting with underscore (bcosca/fatfree#927)
-* Bug fix: mock does not populate PATH variable
-* Bug fix: Geo->weather API key (#129)
-* Bug fix: Incorrect compilation of array element with zero index
-* Bug fix: Compilation of array construct is incorrect
-* Bug fix: Trailing slash redirection on UTF-8 paths (#121)
-
-3.5.1 (31 December 2015)
-* NEW: ttl attribute in '.$this->encode($text?:$req).'
'.$eol. - ($this->hive['DEBUG']?(''.$trace.''.$eol):''). - ''.$eol. - ''); - if ($this->hive['HALT']) - die(1); - } - - /** - * Mock HTTP request - * @return mixed - * @param $pattern string - * @param $args array - * @param $headers array - * @param $body string - **/ - function mock($pattern, - array $args=NULL,array $headers=NULL,$body=NULL) { - if (!$args) - $args=[]; - $types=['sync','ajax','cli']; - preg_match('/([\|\w]+)\h+(?:@(\w+)(?:(\(.+?)\))*|([^\h]+))'. - '(?:\h+\[('.implode('|',$types).')\])?/',$pattern,$parts); - $verb=strtoupper($parts[1]); - if ($parts[2]) { - if (empty($this->hive['ALIASES'][$parts[2]])) - user_error(sprintf(self::E_Named,$parts[2]),E_USER_ERROR); - $parts[4]=$this->hive['ALIASES'][$parts[2]]; - $parts[4]=$this->build($parts[4], - isset($parts[3])?$this->parse($parts[3]):[]); - } - if (empty($parts[4])) - user_error(sprintf(self::E_Pattern,$pattern),E_USER_ERROR); - $url=parse_url($parts[4]); - parse_str(@$url['query'],$GLOBALS['_GET']); - if (preg_match('/GET|HEAD/',$verb)) - $GLOBALS['_GET']=array_merge($GLOBALS['_GET'],$args); - $GLOBALS['_POST']=$verb=='POST'?$args:[]; - $GLOBALS['_REQUEST']=array_merge($GLOBALS['_GET'],$GLOBALS['_POST']); - foreach ($headers?:[] as $key=>$val) - $_SERVER['HTTP_'.strtr(strtoupper($key),'-','_')]=$val; - $this->hive['VERB']=$verb; - $this->hive['PATH']=$url['path']; - $this->hive['URI']=$this->hive['BASE'].$url['path']; - if ($GLOBALS['_GET']) - $this->hive['URI'].='?'.http_build_query($GLOBALS['_GET']); - $this->hive['BODY']=''; - if (!preg_match('/GET|HEAD/',$verb)) - $this->hive['BODY']=$body?:http_build_query($args); - $this->hive['AJAX']=isset($parts[5]) && - preg_match('/ajax/i',$parts[5]); - $this->hive['CLI']=isset($parts[5]) && - preg_match('/cli/i',$parts[5]); - return $this->run(); - } - - /** - * Assemble url from alias name - * @return string - * @param $name string - * @param $params array|string - * @param $query string|array - **/ - function alias($name,$params=[],$query=NULL) { - if (!is_array($params)) - $params=$this->parse($params); - if (empty($this->hive['ALIASES'][$name])) - user_error(sprintf(self::E_Named,$name),E_USER_ERROR); - $url=$this->build($this->hive['ALIASES'][$name],$params); - if (is_array($query)) - $query=http_build_query($query); - return $url.($query?('?'.$query):''); - } - - /** - * Bind handler to route pattern - * @return NULL - * @param $pattern string|array - * @param $handler callback - * @param $ttl int - * @param $kbps int - **/ - function route($pattern,$handler,$ttl=0,$kbps=0) { - $types=['sync','ajax','cli']; - $alias=null; - if (is_array($pattern)) { - foreach ($pattern as $item) - $this->route($item,$handler,$ttl,$kbps); - return; - } - preg_match('/([\|\w]+)\h+(?:(?:@?(.+?)\h*:\h*)?(@(\w+)|[^\h]+))'. - '(?:\h+\[('.implode('|',$types).')\])?/u',$pattern,$parts); - if (isset($parts[2]) && $parts[2]) - $this->hive['ALIASES'][$alias=$parts[2]]=$parts[3]; - elseif (!empty($parts[4])) { - if (empty($this->hive['ALIASES'][$parts[4]])) - user_error(sprintf(self::E_Named,$parts[4]),E_USER_ERROR); - $parts[3]=$this->hive['ALIASES'][$alias=$parts[4]]; - } - if (empty($parts[3])) - user_error(sprintf(self::E_Pattern,$pattern),E_USER_ERROR); - $type=empty($parts[5])?0:constant('self::REQ_'.strtoupper($parts[5])); - foreach ($this->split($parts[1]) as $verb) { - if (!preg_match('/'.self::VERBS.'/',$verb)) - $this->error(501,$verb.' '.$this->hive['URI']); - $this->hive['ROUTES'][$parts[3]][$type][strtoupper($verb)]= - [$handler,$ttl,$kbps,$alias]; - } - } - - /** - * Reroute to specified URI - * @return NULL - * @param $url array|string - * @param $permanent bool - * @param $die bool - **/ - function reroute($url=NULL,$permanent=FALSE,$die=TRUE) { - if (!$url) - $url=$this->hive['REALM']; - if (is_array($url)) - $url=call_user_func_array([$this,'alias'],$url); - elseif (preg_match('/^(?:@?([^\/()?]+)(?:(\(.+?)\))*(\?.+)*)/', - $url,$parts) && - isset($this->hive['ALIASES'][$parts[1]])) - $url=$this->hive['ALIASES'][$parts[1]]; - $url=$this->build($url,isset($parts[2])?$this->parse($parts[2]):[]). - (isset($parts[3])?$parts[3]:''); - if (($handler=$this->hive['ONREROUTE']) && - $this->call($handler,[$url,$permanent])!==FALSE) - return; - if ($url[0]=='/' && (empty($url[1]) || $url[1]!='/')) { - $port=$this->hive['PORT']; - $port=in_array($port,[80,443])?'':(':'.$port); - $url=$this->hive['SCHEME'].'://'. - $this->hive['HOST'].$port.$this->hive['BASE'].$url; - } - if ($this->hive['CLI']) - $this->mock('GET '.$url.' [cli]'); - else { - header('Location: '.$url); - $this->status($permanent?301:302); - if ($die) - die; - } - } - - /** - * Provide ReST interface by mapping HTTP verb to class method - * @return NULL - * @param $url string - * @param $class string|object - * @param $ttl int - * @param $kbps int - **/ - function map($url,$class,$ttl=0,$kbps=0) { - if (is_array($url)) { - foreach ($url as $item) - $this->map($item,$class,$ttl,$kbps); - return; - } - foreach (explode('|',self::VERBS) as $method) - $this->route($method.' '.$url,is_string($class)? - $class.'->'.$this->hive['PREMAP'].strtolower($method): - [$class,$this->hive['PREMAP'].strtolower($method)], - $ttl,$kbps); - } - - /** - * Redirect a route to another URL - * @return NULL - * @param $pattern string|array - * @param $url string - * @param $permanent bool - */ - function redirect($pattern,$url,$permanent=TRUE) { - if (is_array($pattern)) { - foreach ($pattern as $item) - $this->redirect($item,$url,$permanent); - return; - } - $this->route($pattern,function($fw) use($url,$permanent) { - $fw->reroute($url,$permanent); - }); - } - - /** - * Return TRUE if IPv4 address exists in DNSBL - * @return bool - * @param $ip string - **/ - function blacklisted($ip) { - if ($this->hive['DNSBL'] && - !in_array($ip, - is_array($this->hive['EXEMPT'])? - $this->hive['EXEMPT']: - $this->split($this->hive['EXEMPT']))) { - // Reverse IPv4 dotted quad - $rev=implode('.',array_reverse(explode('.',$ip))); - foreach (is_array($this->hive['DNSBL'])? - $this->hive['DNSBL']: - $this->split($this->hive['DNSBL']) as $server) - // DNSBL lookup - if (checkdnsrr($rev.'.'.$server,'A')) - return TRUE; - } - return FALSE; - } - - /** - * Applies the specified URL mask and returns parameterized matches - * @return $args array - * @param $pattern string - * @param $url string|NULL - **/ - function mask($pattern,$url=NULL) { - if (!$url) - $url=$this->rel($this->hive['URI']); - $case=$this->hive['CASELESS']?'i':''; - $wild=preg_quote($pattern,'/'); - $i=0; - while (is_int($pos=strpos($wild,'\*'))) { - $wild=substr_replace($wild,'(?P<_'.$i.'>[^\?]*)',$pos,2); - $i++; - } - preg_match('/^'. - preg_replace( - '/((\\\{)?@(\w+\b)(?(2)\\\}))/', - '(?P<\3>[^\/\?]+)', - $wild).'\/?$/'.$case.'um',$url,$args); - foreach (array_keys($args) as $key) { - if (preg_match('/^_\d+$/',$key)) { - if (empty($args['*'])) - $args['*']=$args[$key]; - else { - if (is_string($args['*'])) - $args['*']=[$args['*']]; - array_push($args['*'],$args[$key]); - } - unset($args[$key]); - } - elseif (is_numeric($key) && $key) - unset($args[$key]); - } - return $args; - } - - /** - * Match routes against incoming URI - * @return mixed - **/ - function run() { - if ($this->blacklisted($this->hive['IP'])) - // Spammer detected - $this->error(403); - if (!$this->hive['ROUTES']) - // No routes defined - user_error(self::E_Routes,E_USER_ERROR); - // Match specific routes first - $paths=[]; - foreach ($keys=array_keys($this->hive['ROUTES']) as $key) { - $path=preg_replace('/@\w+/','*@',$key); - if (substr($path,-1)!='*') - $path.='+'; - $paths[]=$path; - } - $vals=array_values($this->hive['ROUTES']); - array_multisort($paths,SORT_DESC,$keys,$vals); - $this->hive['ROUTES']=array_combine($keys,$vals); - // Convert to BASE-relative URL - $req=urldecode($this->hive['PATH']); - $preflight=FALSE; - if ($cors=(isset($this->hive['HEADERS']['Origin']) && - $this->hive['CORS']['origin'])) { - $cors=$this->hive['CORS']; - header('Access-Control-Allow-Origin: '.$cors['origin']); - header('Access-Control-Allow-Credentials: '. - $this->export($cors['credentials'])); - $preflight= - isset($this->hive['HEADERS']['Access-Control-Request-Method']); - } - $allowed=[]; - foreach ($this->hive['ROUTES'] as $pattern=>$routes) { - if (!$args=$this->mask($pattern,$req)) - continue; - ksort($args); - $route=NULL; - $ptr=$this->hive['CLI']?self::REQ_CLI:$this->hive['AJAX']+1; - if (isset($routes[$ptr][$this->hive['VERB']]) || - isset($routes[$ptr=0])) - $route=$routes[$ptr]; - if (!$route) - continue; - if (isset($route[$this->hive['VERB']]) && !$preflight) { - if ($this->hive['VERB']=='GET' && - preg_match('/.+\/$/',$this->hive['PATH'])) - $this->reroute(substr($this->hive['PATH'],0,-1). - ($this->hive['QUERY']?('?'.$this->hive['QUERY']):'')); - list($handler,$ttl,$kbps,$alias)=$route[$this->hive['VERB']]; - // Capture values of route pattern tokens - $this->hive['PARAMS']=$args; - // Save matching route - $this->hive['ALIAS']=$alias; - $this->hive['PATTERN']=$pattern; - if ($cors && $cors['expose']) - header('Access-Control-Expose-Headers: '. - (is_array($cors['expose'])? - implode(',',$cors['expose']):$cors['expose'])); - if (is_string($handler)) { - // Replace route pattern tokens in handler if any - $handler=preg_replace_callback('/({)?@(\w+\b)(?(1)})/', - function($id) use($args) { - $pid=count($id)>2?2:1; - return isset($args[$id[$pid]])? - $args[$id[$pid]]: - $id[0]; - }, - $handler - ); - if (preg_match('/(.+)\h*(?:->|::)/',$handler,$match) && - !class_exists($match[1])) - $this->error(404); - } - // Process request - $result=NULL; - $body=''; - $now=microtime(TRUE); - if (preg_match('/GET|HEAD/',$this->hive['VERB']) && $ttl) { - // Only GET and HEAD requests are cacheable - $headers=$this->hive['HEADERS']; - $cache=Cache::instance(); - $cached=$cache->exists( - $hash=$this->hash($this->hive['VERB'].' '. - $this->hive['URI']).'.url',$data); - if ($cached) { - if (isset($headers['If-Modified-Since']) && - strtotime($headers['If-Modified-Since'])+ - $ttl>$now) { - $this->status(304); - die; - } - // Retrieve from cache backend - list($headers,$body,$result)=$data; - if (!$this->hive['CLI']) - array_walk($headers,'header'); - $this->expire($cached[0]+$ttl-$now); - } - else - // Expire HTTP client-cached page - $this->expire($ttl); - } - else - $this->expire(0); - if (!strlen($body)) { - if (!$this->hive['RAW'] && !$this->hive['BODY']) - $this->hive['BODY']=file_get_contents('php://input'); - ob_start(); - // Call route handler - $result=$this->call($handler,[$this,$args,$handler], - 'beforeroute,afterroute'); - $body=ob_get_clean(); - if (isset($cache) && !error_get_last()) { - // Save to cache backend - $cache->set($hash,[ - // Remove cookies - preg_grep('/Set-Cookie\:/',headers_list(), - PREG_GREP_INVERT),$body,$result],$ttl); - } - } - $this->hive['RESPONSE']=$body; - if (!$this->hive['QUIET']) { - if ($kbps) { - $ctr=0; - foreach (str_split($body,1024) as $part) { - // Throttle output - $ctr++; - if ($ctr/$kbps>($elapsed=microtime(TRUE)-$now) && - !connection_aborted()) - usleep(1e6*($ctr/$kbps-$elapsed)); - echo $part; - } - } - else - echo $body; - } - if ($result || $this->hive['VERB']!='OPTIONS') - return $result; - } - $allowed=array_merge($allowed,array_keys($route)); - } - if (!$allowed) - // URL doesn't match any route - $this->error(404); - elseif (!$this->hive['CLI']) { - if (!preg_grep('/Allow:/',$headers_send=headers_list())) - // Unhandled HTTP method - header('Allow: '.implode(',',array_unique($allowed))); - if ($cors) { - if (!preg_grep('/Access-Control-Allow-Methods:/',$headers_send)) - header('Access-Control-Allow-Methods: OPTIONS,'. - implode(',',$allowed)); - if ($cors['headers'] && - !preg_grep('/Access-Control-Allow-Headers:/',$headers_send)) - header('Access-Control-Allow-Headers: '. - (is_array($cors['headers'])? - implode(',',$cors['headers']): - $cors['headers'])); - if ($cors['ttl']>0) - header('Access-Control-Max-Age: '.$cors['ttl']); - } - if ($this->hive['VERB']!='OPTIONS') - $this->error(405); - } - return FALSE; - } - - /** - * Loop until callback returns TRUE (for long polling) - * @return mixed - * @param $func callback - * @param $args array - * @param $timeout int - **/ - function until($func,$args=NULL,$timeout=60) { - if (!$args) - $args=[]; - $time=time(); - $max=ini_get('max_execution_time'); - $limit=max(0,($max?min($timeout,$max):$timeout)-1); - $out=''; - // Turn output buffering on - ob_start(); - // Not for the weak of heart - while ( - // No error occurred - !$this->hive['ERROR'] && - // Got time left? - time()-$time+1<$limit && - // Still alive? - !connection_aborted() && - // Restart session - !headers_sent() && - (session_status()==PHP_SESSION_ACTIVE || session_start()) && - // CAUTION: Callback will kill host if it never becomes truthy! - !$out=$this->call($func,$args)) { - if (!$this->hive['CLI']) - session_commit(); - // Hush down - sleep(1); - } - ob_flush(); - flush(); - return $out; - } - - /** - * Disconnect HTTP client; - * Set FcgidOutputBufferSize to zero if server uses mod_fcgid; - * Disable mod_deflate when rendering text/html output - **/ - function abort() { - if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE) - session_start(); - $out=''; - while (ob_get_level()) - $out=ob_get_clean().$out; - if (!headers_sent()) { - header('Content-Length: '.strlen($out)); - header('Connection: close'); - } - session_commit(); - echo $out; - flush(); - if (function_exists('fastcgi_finish_request')) - fastcgi_finish_request(); - } - - /** - * Grab the real route handler behind the string expression - * @return string|array - * @param $func string - * @param $args array - **/ - function grab($func,$args=NULL) { - if (preg_match('/(.+)\h*(->|::)\h*(.+)/s',$func,$parts)) { - // Convert string to executable PHP callback - if (!class_exists($parts[1])) - user_error(sprintf(self::E_Class,$parts[1]),E_USER_ERROR); - if ($parts[2]=='->') { - if (is_subclass_of($parts[1],'Prefab')) - $parts[1]=call_user_func($parts[1].'::instance'); - elseif ($container=$this->get('CONTAINER')) { - if (is_object($container) && is_callable([$container,'has']) - && $container->has($parts[1])) // PSR11 - $parts[1]=call_user_func([$container,'get'],$parts[1]); - elseif (is_callable($container)) - $parts[1]=call_user_func($container,$parts[1],$args); - elseif (is_string($container) && - is_subclass_of($container,'Prefab')) - $parts[1]=call_user_func($container.'::instance')-> - get($parts[1]); - else - user_error(sprintf(self::E_Class, - $this->stringify($parts[1])), - E_USER_ERROR); - } - else { - $ref=new ReflectionClass($parts[1]); - $parts[1]=method_exists($parts[1],'__construct') && $args? - $ref->newinstanceargs($args): - $ref->newinstance(); - } - } - $func=[$parts[1],$parts[3]]; - } - return $func; - } - - /** - * Execute callback/hooks (supports 'class->method' format) - * @return mixed|FALSE - * @param $func callback - * @param $args mixed - * @param $hooks string - **/ - function call($func,$args=NULL,$hooks='') { - if (!is_array($args)) - $args=[$args]; - // Grab the real handler behind the string representation - if (is_string($func)) - $func=$this->grab($func,$args); - // Execute function; abort if callback/hook returns FALSE - if (!is_callable($func)) - // No route handler - if ($hooks=='beforeroute,afterroute') { - $allowed=[]; - if (is_array($func)) - $allowed=array_intersect( - array_map('strtoupper',get_class_methods($func[0])), - explode('|',self::VERBS) - ); - header('Allow: '.implode(',',$allowed)); - $this->error(405); - } - else - user_error(sprintf(self::E_Method, - is_string($func)?$func:$this->stringify($func)), - E_USER_ERROR); - $obj=FALSE; - if (is_array($func)) { - $hooks=$this->split($hooks); - $obj=TRUE; - } - // Execute pre-route hook if any - if ($obj && $hooks && in_array($hook='beforeroute',$hooks) && - method_exists($func[0],$hook) && - call_user_func_array([$func[0],$hook],$args)===FALSE) - return FALSE; - // Execute callback - $out=call_user_func_array($func,$args?:[]); - if ($out===FALSE) - return FALSE; - // Execute post-route hook if any - if ($obj && $hooks && in_array($hook='afterroute',$hooks) && - method_exists($func[0],$hook) && - call_user_func_array([$func[0],$hook],$args)===FALSE) - return FALSE; - return $out; - } - - /** - * Execute specified callbacks in succession; Apply same arguments - * to all callbacks - * @return array - * @param $funcs array|string - * @param $args mixed - **/ - function chain($funcs,$args=NULL) { - $out=[]; - foreach (is_array($funcs)?$funcs:$this->split($funcs) as $func) - $out[]=$this->call($func,$args); - return $out; - } - - /** - * Execute specified callbacks in succession; Relay result of - * previous callback as argument to the next callback - * @return array - * @param $funcs array|string - * @param $args mixed - **/ - function relay($funcs,$args=NULL) { - foreach (is_array($funcs)?$funcs:$this->split($funcs) as $func) - $args=[$this->call($func,$args)]; - return array_shift($args); - } - - /** - * Configure framework according to .ini-style file settings; - * If optional 2nd arg is provided, template strings are interpreted - * @return object - * @param $source string|array - * @param $allow bool - **/ - function config($source,$allow=FALSE) { - if (is_string($source)) - $source=$this->split($source); - if ($allow) - $preview=Preview::instance(); - foreach ($source as $file) { - preg_match_all( - '/(?<=^|\n)(?:'. - '\[(?
'.$out.''):$text;
- }
-
- /**
- * Dump expression with syntax highlighting
- * @return NULL
- * @param $expr mixed
- **/
- function dump($expr) {
- echo $this->highlight($this->stringify($expr));
- }
-
- /**
- * Return path (and query parameters) relative to the base directory
- * @return string
- * @param $url string
- **/
- function rel($url) {
- return preg_replace('/^(?:https?:\/\/)?'.
- preg_quote($this->hive['BASE'],'/').'(\/.*|$)/','\1',$url);
- }
-
- /**
- * Namespace-aware class autoloader
- * @return mixed
- * @param $class string
- **/
- protected function autoload($class) {
- $class=$this->fixslashes(ltrim($class,'\\'));
- $func=NULL;
- if (is_array($path=$this->hive['AUTOLOAD']) &&
- isset($path[1]) && is_callable($path[1]))
- list($path,$func)=$path;
- foreach ($this->split($this->hive['PLUGINS'].';'.$path) as $auto)
- if ($func && is_file($file=$func($auto.$class).'.php') ||
- is_file($file=$auto.$class.'.php') ||
- is_file($file=$auto.strtolower($class).'.php') ||
- is_file($file=strtolower($auto.$class).'.php'))
- return require($file);
- }
-
- /**
- * Execute framework/application shutdown sequence
- * @param $cwd string
- **/
- function unload($cwd) {
- chdir($cwd);
- if (!($error=error_get_last()) &&
- session_status()==PHP_SESSION_ACTIVE)
- session_commit();
- foreach ($this->locks as $lock)
- @unlink($lock);
- $handler=$this->hive['UNLOAD'];
- if ((!$handler || $this->call($handler,$this)===FALSE) &&
- $error && in_array($error['type'],
- [E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR]))
- // Fatal error detected
- $this->error(500,
- sprintf(self::E_Fatal,$error['message']),[$error]);
- }
-
- /**
- * Convenience method for checking hive key
- * @return mixed
- * @param $key string
- **/
- function offsetexists($key) {
- return $this->exists($key);
- }
-
- /**
- * Convenience method for assigning hive value
- * @return mixed
- * @param $key string
- * @param $val scalar
- **/
- function offsetset($key,$val) {
- return $this->set($key,$val);
- }
-
- /**
- * Convenience method for retrieving hive value
- * @return mixed
- * @param $key string
- **/
- function &offsetget($key) {
- $val=&$this->ref($key);
- return $val;
- }
-
- /**
- * Convenience method for removing hive key
- * @return NULL
- * @param $key string
- **/
- function offsetunset($key) {
- $this->clear($key);
- }
-
- /**
- * Alias for offsetexists()
- * @return mixed
- * @param $key string
- **/
- function __isset($key) {
- return $this->offsetexists($key);
- }
-
- /**
- * Alias for offsetset()
- * @return mixed
- * @param $key string
- * @param $val mixed
- **/
- function __set($key,$val) {
- return $this->offsetset($key,$val);
- }
-
- /**
- * Alias for offsetget()
- * @return mixed
- * @param $key string
- **/
- function &__get($key) {
- $val=&$this->offsetget($key);
- return $val;
- }
-
- /**
- * Alias for offsetunset()
- * @return mixed
- * @param $key string
- **/
- function __unset($key) {
- $this->offsetunset($key);
- }
-
- /**
- * Call function identified by hive key
- * @return mixed
- * @param $key string
- * @param $args array
- **/
- function __call($key,array $args) {
- if ($this->exists($key,$val))
- return call_user_func_array($val,$args);
- user_error(sprintf(self::E_Method,$key),E_USER_ERROR);
- }
-
- //! Prohibit cloning
- private function __clone() {
- }
-
- //! Bootstrap
- function __construct() {
- // Managed directives
- ini_set('default_charset',$charset='UTF-8');
- if (extension_loaded('mbstring'))
- mb_internal_encoding($charset);
- ini_set('display_errors',0);
- // Deprecated directives
- @ini_set('magic_quotes_gpc',0);
- @ini_set('register_globals',0);
- // Intercept errors/exceptions; PHP5.3-compatible
- $check=error_reporting((E_ALL|E_STRICT)&~(E_NOTICE|E_USER_NOTICE));
- set_exception_handler(
- function($obj) {
- $this->hive['EXCEPTION']=$obj;
- $this->error(500,
- $obj->getmessage().' '.
- '['.$obj->getFile().':'.$obj->getLine().']',
- $obj->gettrace());
- }
- );
- set_error_handler(
- function($level,$text,$file,$line) {
- if ($level & error_reporting())
- $this->error(500,$text,NULL,$level);
- }
- );
- if (!isset($_SERVER['SERVER_NAME']) || $_SERVER['SERVER_NAME']==='')
- $_SERVER['SERVER_NAME']=gethostname();
- $headers=[];
- if ($cli=PHP_SAPI=='cli') {
- // Emulate HTTP request
- $_SERVER['REQUEST_METHOD']='GET';
- if (!isset($_SERVER['argv'][1])) {
- $_SERVER['argc']++;
- $_SERVER['argv'][1]='/';
- }
- $req=$query='';
- if (substr($_SERVER['argv'][1],0,1)=='/') {
- $req=$_SERVER['argv'][1];
- $query=parse_url($req,PHP_URL_QUERY);
- } else {
- foreach($_SERVER['argv'] as $i=>$arg) {
- if (!$i) continue;
- if (preg_match('/^\-(\-)?(\w+)(?:\=(.*))?$/',$arg,$m)) {
- foreach($m[1]?[$m[2]]:str_split($m[2]) as $k)
- $query.=($query?'&':'').urlencode($k).'=';
- if (isset($m[3]))
- $query.=urlencode($m[3]);
- } else
- $req.='/'.$arg;
- }
- if (!$req)
- $req='/';
- if ($query)
- $req.='?'.$query;
- }
- $_SERVER['REQUEST_URI']=$req;
- parse_str($query,$GLOBALS['_GET']);
- }
- elseif (function_exists('getallheaders')) {
- foreach (getallheaders() as $key=>$val) {
- $tmp=strtoupper(strtr($key,'-','_'));
- // TODO: use ucwords delimiters for php 5.4.32+ & 5.5.16+
- $key=strtr(ucwords(strtolower(strtr($key,'-',' '))),' ','-');
- $headers[$key]=$val;
- if (isset($_SERVER['HTTP_'.$tmp]))
- $headers[$key]=&$_SERVER['HTTP_'.$tmp];
- }
- }
- else {
- if (isset($_SERVER['CONTENT_LENGTH']))
- $headers['Content-Length']=&$_SERVER['CONTENT_LENGTH'];
- if (isset($_SERVER['CONTENT_TYPE']))
- $headers['Content-Type']=&$_SERVER['CONTENT_TYPE'];
- foreach (array_keys($_SERVER) as $key)
- if (substr($key,0,5)=='HTTP_')
- $headers[strtr(ucwords(strtolower(strtr(
- substr($key,5),'_',' '))),' ','-')]=&$_SERVER[$key];
- }
- if (isset($headers['X-HTTP-Method-Override']))
- $_SERVER['REQUEST_METHOD']=$headers['X-HTTP-Method-Override'];
- elseif ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['_method']))
- $_SERVER['REQUEST_METHOD']=strtoupper($_POST['_method']);
- $scheme=isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ||
- isset($headers['X-Forwarded-Proto']) &&
- $headers['X-Forwarded-Proto']=='https'?'https':'http';
- // Create hive early on to expose header methods
- $this->hive=['HEADERS'=>&$headers];
- if (function_exists('apache_setenv')) {
- // Work around Apache pre-2.4 VirtualDocumentRoot bug
- $_SERVER['DOCUMENT_ROOT']=str_replace($_SERVER['SCRIPT_NAME'],'',
- $_SERVER['SCRIPT_FILENAME']);
- apache_setenv("DOCUMENT_ROOT",$_SERVER['DOCUMENT_ROOT']);
- }
- $_SERVER['DOCUMENT_ROOT']=realpath($_SERVER['DOCUMENT_ROOT']);
- $base='';
- if (!$cli)
- $base=rtrim($this->fixslashes(
- dirname($_SERVER['SCRIPT_NAME'])),'/');
- $uri=parse_url((preg_match('/^\w+:\/\//',$_SERVER['REQUEST_URI'])?'':
- $scheme.'://'.$_SERVER['SERVER_NAME']).$_SERVER['REQUEST_URI']);
- $_SERVER['REQUEST_URI']=$uri['path'].
- (isset($uri['query'])?'?'.$uri['query']:'').
- (isset($uri['fragment'])?'#'.$uri['fragment']:'');
- $path=preg_replace('/^'.preg_quote($base,'/').'/','',$uri['path']);
- $jar=[
- 'expire'=>0,
- 'lifetime'=>0,
- 'path'=>$base?:'/',
- 'domain'=>is_int(strpos($_SERVER['SERVER_NAME'],'.')) &&
- !filter_var($_SERVER['SERVER_NAME'],FILTER_VALIDATE_IP)?
- $_SERVER['SERVER_NAME']:'',
- 'secure'=>($scheme=='https'),
- 'httponly'=>TRUE
- ];
- $port=80;
- if (isset($headers['X-Forwarded-Port']))
- $port=$headers['X-Forwarded-Port'];
- elseif (isset($_SERVER['SERVER_PORT']))
- $port=$_SERVER['SERVER_PORT'];
- // Default configuration
- $this->hive+=[
- 'AGENT'=>$this->agent(),
- 'AJAX'=>$this->ajax(),
- 'ALIAS'=>NULL,
- 'ALIASES'=>[],
- 'AUTOLOAD'=>'./',
- 'BASE'=>$base,
- 'BITMASK'=>ENT_COMPAT,
- 'BODY'=>NULL,
- 'CACHE'=>FALSE,
- 'CASELESS'=>TRUE,
- 'CLI'=>$cli,
- 'CORS'=>[
- 'headers'=>'',
- 'origin'=>FALSE,
- 'credentials'=>FALSE,
- 'expose'=>FALSE,
- 'ttl'=>0
- ],
- 'DEBUG'=>0,
- 'DIACRITICS'=>[],
- 'DNSBL'=>'',
- 'EMOJI'=>[],
- 'ENCODING'=>$charset,
- 'ERROR'=>NULL,
- 'ESCAPE'=>TRUE,
- 'EXCEPTION'=>NULL,
- 'EXEMPT'=>NULL,
- 'FALLBACK'=>$this->fallback,
- 'FORMATS'=>[],
- 'FRAGMENT'=>isset($uri['fragment'])?$uri['fragment']:'',
- 'HALT'=>TRUE,
- 'HIGHLIGHT'=>FALSE,
- 'HOST'=>$_SERVER['SERVER_NAME'],
- 'IP'=>$this->ip(),
- 'JAR'=>$jar,
- 'LANGUAGE'=>isset($headers['Accept-Language'])?
- $this->language($headers['Accept-Language']):
- $this->fallback,
- 'LOCALES'=>'./',
- 'LOGGABLE'=>'*',
- 'LOGS'=>'./',
- 'MB'=>extension_loaded('mbstring'),
- 'ONERROR'=>NULL,
- 'ONREROUTE'=>NULL,
- 'PACKAGE'=>self::PACKAGE,
- 'PARAMS'=>[],
- 'PATH'=>$path,
- 'PATTERN'=>NULL,
- 'PLUGINS'=>$this->fixslashes(__DIR__).'/',
- 'PORT'=>$port,
- 'PREFIX'=>NULL,
- 'PREMAP'=>'',
- 'QUERY'=>isset($uri['query'])?$uri['query']:'',
- 'QUIET'=>FALSE,
- 'RAW'=>FALSE,
- 'REALM'=>$scheme.'://'.$_SERVER['SERVER_NAME'].
- ($port && !in_array($port,[80,443])?(':'.$port):'').
- $_SERVER['REQUEST_URI'],
- 'RESPONSE'=>'',
- 'ROOT'=>$_SERVER['DOCUMENT_ROOT'],
- 'ROUTES'=>[],
- 'SCHEME'=>$scheme,
- 'SEED'=>$this->hash($_SERVER['SERVER_NAME'].$base),
- 'SERIALIZER'=>extension_loaded($ext='igbinary')?$ext:'php',
- 'TEMP'=>'tmp/',
- 'TIME'=>&$_SERVER['REQUEST_TIME_FLOAT'],
- 'TZ'=>@date_default_timezone_get(),
- 'UI'=>'./',
- 'UNLOAD'=>NULL,
- 'UPLOADS'=>'./',
- 'URI'=>&$_SERVER['REQUEST_URI'],
- 'VERB'=>&$_SERVER['REQUEST_METHOD'],
- 'VERSION'=>self::VERSION,
- 'XFRAME'=>'SAMEORIGIN'
- ];
- if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE) {
- unset($jar['expire']);
- session_cache_limiter('');
- call_user_func_array('session_set_cookie_params',$jar);
- }
- if (PHP_SAPI=='cli-server' &&
- preg_match('/^'.preg_quote($base,'/').'$/',$this->hive['URI']))
- $this->reroute('/');
- if (ini_get('auto_globals_jit'))
- // Override setting
- $GLOBALS+=['_ENV'=>$_ENV,'_REQUEST'=>$_REQUEST];
- // Sync PHP globals with corresponding hive keys
- $this->init=$this->hive;
- foreach (explode('|',self::GLOBALS) as $global) {
- $sync=$this->sync($global);
- $this->init+=[
- $global=>preg_match('/SERVER|ENV/',$global)?$sync:[]
- ];
- }
- if ($check && $error=error_get_last())
- // Error detected
- $this->error(500,
- sprintf(self::E_Fatal,$error['message']),[$error]);
- date_default_timezone_set($this->hive['TZ']);
- // Register framework autoloader
- spl_autoload_register([$this,'autoload']);
- // Register shutdown handler
- register_shutdown_function([$this,'unload'],getcwd());
- }
-
-}
-
-//! Cache engine
-class Cache extends Prefab {
-
- protected
- //! Cache DSN
- $dsn,
- //! Prefix for cache entries
- $prefix,
- //! MemCache or Redis object
- $ref;
-
- /**
- * Return timestamp and TTL of cache entry or FALSE if not found
- * @return array|FALSE
- * @param $key string
- * @param $val mixed
- **/
- function exists($key,&$val=NULL) {
- $fw=Base::instance();
- if (!$this->dsn)
- return FALSE;
- $ndx=$this->prefix.'.'.$key;
- $parts=explode('=',$this->dsn,2);
- switch ($parts[0]) {
- case 'apc':
- case 'apcu':
- $raw=call_user_func($parts[0].'_fetch',$ndx);
- break;
- case 'redis':
- $raw=$this->ref->get($ndx);
- break;
- case 'memcache':
- $raw=memcache_get($this->ref,$ndx);
- break;
- case 'memcached':
- $raw=$this->ref->get($ndx);
- break;
- case 'wincache':
- $raw=wincache_ucache_get($ndx);
- break;
- case 'xcache':
- $raw=xcache_get($ndx);
- break;
- case 'folder':
- $raw=$fw->read($parts[1].$ndx);
- break;
- }
- if (!empty($raw)) {
- list($val,$time,$ttl)=(array)$fw->unserialize($raw);
- if ($ttl===0 || $time+$ttl>microtime(TRUE))
- return [$time,$ttl];
- $val=null;
- $this->clear($key);
- }
- return FALSE;
- }
-
- /**
- * Store value in cache
- * @return mixed|FALSE
- * @param $key string
- * @param $val mixed
- * @param $ttl int
- **/
- function set($key,$val,$ttl=0) {
- $fw=Base::instance();
- if (!$this->dsn)
- return TRUE;
- $ndx=$this->prefix.'.'.$key;
- if ($cached=$this->exists($key))
- $ttl=$cached[1];
- $data=$fw->serialize([$val,microtime(TRUE),$ttl]);
- $parts=explode('=',$this->dsn,2);
- switch ($parts[0]) {
- case 'apc':
- case 'apcu':
- return call_user_func($parts[0].'_store',$ndx,$data,$ttl);
- case 'redis':
- return $this->ref->set($ndx,$data,$ttl?['ex'=>$ttl]:[]);
- case 'memcache':
- return memcache_set($this->ref,$ndx,$data,0,$ttl);
- case 'memcached':
- return $this->ref->set($ndx,$data,$ttl);
- case 'wincache':
- return wincache_ucache_set($ndx,$data,$ttl);
- case 'xcache':
- return xcache_set($ndx,$data,$ttl);
- case 'folder':
- return $fw->write($parts[1].
- str_replace(['/','\\'],'',$ndx),$data);
- }
- return FALSE;
- }
-
- /**
- * Retrieve value of cache entry
- * @return mixed|FALSE
- * @param $key string
- **/
- function get($key) {
- return $this->dsn && $this->exists($key,$data)?$data:FALSE;
- }
-
- /**
- * Delete cache entry
- * @return bool
- * @param $key string
- **/
- function clear($key) {
- if (!$this->dsn)
- return;
- $ndx=$this->prefix.'.'.$key;
- $parts=explode('=',$this->dsn,2);
- switch ($parts[0]) {
- case 'apc':
- case 'apcu':
- return call_user_func($parts[0].'_delete',$ndx);
- case 'redis':
- return $this->ref->del($ndx);
- case 'memcache':
- return memcache_delete($this->ref,$ndx);
- case 'memcached':
- return $this->ref->delete($ndx);
- case 'wincache':
- return wincache_ucache_delete($ndx);
- case 'xcache':
- return xcache_unset($ndx);
- case 'folder':
- return @unlink($parts[1].$ndx);
- }
- return FALSE;
- }
-
- /**
- * Clear contents of cache backend
- * @return bool
- * @param $suffix string
- **/
- function reset($suffix=NULL) {
- if (!$this->dsn)
- return TRUE;
- $regex='/'.preg_quote($this->prefix.'.','/').'.*'.
- preg_quote($suffix,'/').'/';
- $parts=explode('=',$this->dsn,2);
- switch ($parts[0]) {
- case 'apc':
- case 'apcu':
- $info=call_user_func($parts[0].'_cache_info',
- $parts[0]=='apcu'?FALSE:'user');
- if (!empty($info['cache_list'])) {
- $key=array_key_exists('info',
- $info['cache_list'][0])?'info':'key';
- foreach ($info['cache_list'] as $item)
- if (preg_match($regex,$item[$key]))
- call_user_func($parts[0].'_delete',$item[$key]);
- }
- return TRUE;
- case 'redis':
- $keys=$this->ref->keys($this->prefix.'.*'.$suffix);
- foreach($keys as $key)
- $this->ref->del($key);
- return TRUE;
- case 'memcache':
- foreach (memcache_get_extended_stats(
- $this->ref,'slabs') as $slabs)
- foreach (array_filter(array_keys($slabs),'is_numeric')
- as $id)
- foreach (memcache_get_extended_stats(
- $this->ref,'cachedump',$id) as $data)
- if (is_array($data))
- foreach (array_keys($data) as $key)
- if (preg_match($regex,$key))
- memcache_delete($this->ref,$key);
- return TRUE;
- case 'memcached':
- foreach ($this->ref->getallkeys()?:[] as $key)
- if (preg_match($regex,$key))
- $this->ref->delete($key);
- return TRUE;
- case 'wincache':
- $info=wincache_ucache_info();
- foreach ($info['ucache_entries'] as $item)
- if (preg_match($regex,$item['key_name']))
- wincache_ucache_delete($item['key_name']);
- return TRUE;
- case 'xcache':
- if ($suffix && !ini_get('xcache.admin.enable_auth')) {
- $cnt=xcache_count(XC_TYPE_VAR);
- for ($i=0;$i<$cnt;$i++) {
- $list=xcache_list(XC_TYPE_VAR,$i);
- foreach ($list['cache_list'] as $item)
- if (preg_match($regex,$item['name']))
- xcache_unset($item['name']);
- }
- } else
- xcache_unset_by_prefix($this->prefix.'.');
- return TRUE;
- case 'folder':
- if ($glob=@glob($parts[1].'*'))
- foreach ($glob as $file)
- if (preg_match($regex,basename($file)))
- @unlink($file);
- return TRUE;
- }
- return FALSE;
- }
-
- /**
- * Load/auto-detect cache backend
- * @return string
- * @param $dsn bool|string
- * @param $seed bool|string
- **/
- function load($dsn,$seed=NULL) {
- $fw=Base::instance();
- if ($dsn=trim($dsn)) {
- if (preg_match('/^redis=(.+)/',$dsn,$parts) &&
- extension_loaded('redis')) {
- list($host,$port,$db)=explode(':',$parts[1])+[1=>6379,2=>NULL];
- $this->ref=new Redis;
- if(!$this->ref->connect($host,$port,2))
- $this->ref=NULL;
- if(isset($db))
- $this->ref->select($db);
- }
- elseif (preg_match('/^memcache=(.+)/',$dsn,$parts) &&
- extension_loaded('memcache'))
- foreach ($fw->split($parts[1]) as $server) {
- list($host,$port)=explode(':',$server)+[1=>11211];
- if (empty($this->ref))
- $this->ref=@memcache_connect($host,$port)?:NULL;
- else
- memcache_add_server($this->ref,$host,$port);
- }
- elseif (preg_match('/^memcached=(.+)/',$dsn,$parts) &&
- extension_loaded('memcached'))
- foreach ($fw->split($parts[1]) as $server) {
- list($host,$port)=explode(':',$server)+[1=>11211];
- if (empty($this->ref))
- $this->ref=new Memcached();
- $this->ref->addServer($host,$port);
- }
- if (empty($this->ref) && !preg_match('/^folder\h*=/',$dsn))
- $dsn=($grep=preg_grep('/^(apc|wincache|xcache)/',
- array_map('strtolower',get_loaded_extensions())))?
- // Auto-detect
- current($grep):
- // Use filesystem as fallback
- ('folder='.$fw->TEMP.'cache/');
- if (preg_match('/^folder\h*=\h*(.+)/',$dsn,$parts) &&
- !is_dir($parts[1]))
- mkdir($parts[1],Base::MODE,TRUE);
- }
- $this->prefix=$seed?:$fw->SEED;
- return $this->dsn=$dsn;
- }
-
- /**
- * Class constructor
- * @param $dsn bool|string
- **/
- function __construct($dsn=FALSE) {
- if ($dsn)
- $this->load($dsn);
- }
-
-}
-
-//! View handler
-class View extends Prefab {
-
- private
- //! Temporary hive
- $temp;
-
- protected
- //! Template file
- $file,
- //! Post-rendering handler
- $trigger,
- //! Nesting level
- $level=0;
-
- /** @var \Base Framework instance */
- protected $fw;
-
- function __construct() {
- $this->fw=\Base::instance();
- }
-
- /**
- * Encode characters to equivalent HTML entities
- * @return string
- * @param $arg mixed
- **/
- function esc($arg) {
- return $this->fw->recursive($arg,
- function($val) {
- return is_string($val)?$this->fw->encode($val):$val;
- }
- );
- }
-
- /**
- * Decode HTML entities to equivalent characters
- * @return string
- * @param $arg mixed
- **/
- function raw($arg) {
- return $this->fw->recursive($arg,
- function($val) {
- return is_string($val)?$this->fw->decode($val):$val;
- }
- );
- }
-
- /**
- * Create sandbox for template execution
- * @return string
- * @param $hive array
- * @param $mime string
- **/
- protected function sandbox(array $hive=NULL,$mime=NULL) {
- $fw=$this->fw;
- $implicit=FALSE;
- if (is_null($hive)) {
- $implicit=TRUE;
- $hive=$fw->hive();
- }
- if ($this->level<1 || $implicit) {
- if (!$fw->CLI && $mime && !headers_sent() &&
- !preg_grep ('/^Content-Type:/',headers_list()))
- header('Content-Type: '.$mime.'; '.
- 'charset='.$fw->ENCODING);
- if ($fw->ESCAPE)
- $hive=$this->esc($hive);
- if (isset($hive['ALIASES']))
- $hive['ALIASES']=$fw->build($hive['ALIASES']);
- }
- $this->temp=$hive;
- unset($fw,$hive,$implicit,$mime);
- extract($this->temp);
- $this->temp=NULL;
- $this->level++;
- ob_start();
- require($this->file);
- $this->level--;
- return ob_get_clean();
- }
-
- /**
- * Render template
- * @return string
- * @param $file string
- * @param $mime string
- * @param $hive array
- * @param $ttl int
- **/
- function render($file,$mime='text/html',array $hive=NULL,$ttl=0) {
- $fw=$this->fw;
- $cache=Cache::instance();
- foreach ($fw->split($fw->UI) as $dir) {
- if ($cache->exists($hash=$fw->hash($dir.$file),$data))
- return $data;
- if (is_file($this->file=$fw->fixslashes($dir.$file))) {
- if (isset($_COOKIE[session_name()]) &&
- !headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
- session_start();
- $fw->sync('SESSION');
- $data=$this->sandbox($hive,$mime);
- if (isset($this->trigger['afterrender']))
- foreach($this->trigger['afterrender'] as $func)
- $data=$fw->call($func,[$data, $dir.$file]);
- if ($ttl)
- $cache->set($hash,$data,$ttl);
- return $data;
- }
- }
- user_error(sprintf(Base::E_Open,$file),E_USER_ERROR);
- }
-
- /**
- * post rendering handler
- * @param $func callback
- */
- function afterrender($func) {
- $this->trigger['afterrender'][]=$func;
- }
-
-}
-
-//! Lightweight template engine
-class Preview extends View {
-
- protected
- //! token filter
- $filter=[
- 'c'=>'$this->c',
- 'esc'=>'$this->esc',
- 'raw'=>'$this->raw',
- 'export'=>'Base::instance()->export',
- 'alias'=>'Base::instance()->alias',
- 'format'=>'Base::instance()->format'
- ];
-
- protected
- //! newline interpolation
- $interpolation=true;
-
- /**
- * Enable/disable markup parsing interpolation
- * mainly used for adding appropriate newlines
- * @param $bool bool
- */
- function interpolation($bool) {
- $this->interpolation=$bool;
- }
-
- /**
- * Return C-locale equivalent of number
- * @return string
- * @param $val int|float
- **/
- function c($val) {
- $locale=setlocale(LC_NUMERIC,0);
- setlocale(LC_NUMERIC,'C');
- $out=(string)(float)$val;
- $locale=setlocale(LC_NUMERIC,$locale);
- return $out;
- }
-
- /**
- * Convert token to variable
- * @return string
- * @param $str string
- **/
- function token($str) {
- $fw=$this->fw;
- $str=trim(preg_replace('/\{\{(.+?)\}\}/s',trim('\1'),
- $fw->compile($str)));
- if (preg_match('/^(.+)(?split(trim($parts[2],"\xC2\xA0")) as $func)
- $str=((empty($this->filter[$cmd=$func]) &&
- function_exists($cmd)) ||
- is_string($cmd=$this->filter($func)))?
- $cmd.'('.$str.')':
- 'Base::instance()->'.
- 'call($this->filter(\''.$func.'\'),['.$str.'])';
- }
- return $str;
- }
-
- /**
- * Register or get (one specific or all) token filters
- * @param string $key
- * @param string|closure $func
- * @return array|closure|string
- */
- function filter($key=NULL,$func=NULL) {
- if (!$key)
- return array_keys($this->filter);
- $key=strtolower($key);
- if (!$func)
- return $this->filter[$key];
- $this->filter[$key]=$func;
- }
-
- /**
- * Assemble markup
- * @return string
- * @param $node string
- **/
- protected function build($node) {
- return preg_replace_callback(
- '/\{~(.+?)~\}|\{\*(.+?)\*\}|\{\-(.+?)\-\}|'.
- '\{\{(.+?)\}\}((\r?\n)*)/s',
- function($expr) {
- if ($expr[1])
- $str='token($expr[1]).' ?>';
- elseif ($expr[2])
- return '';
- elseif ($expr[3])
- $str=$expr[3];
- else {
- $str='= ('.trim($this->token($expr[4])).')'.
- ($this->interpolation?
- (!empty($expr[6])?'."'.$expr[6].'"':''):'').' ?>';
- if (isset($expr[5]))
- $str.=$expr[5];
- }
- return $str;
- },
- $node
- );
- }
-
- /**
- * Render template string
- * @return string
- * @param $node string|array
- * @param $hive array
- * @param $ttl int
- * @param $persist bool
- * @param $escape bool
- **/
- function resolve($node,array $hive=NULL,$ttl=0,$persist=FALSE,$escape=NULL) {
- $fw=$this->fw;
- $cache=Cache::instance();
- if ($escape!==NULL) {
- $esc=$fw->ESCAPE;
- $fw->ESCAPE=$escape;
- }
- if ($ttl || $persist)
- $hash=$fw->hash($fw->serialize($node));
- if ($ttl && $cache->exists($hash,$data))
- return $data;
- if ($persist) {
- if (!is_dir($tmp=$fw->TEMP))
- mkdir($tmp,Base::MODE,TRUE);
- if (!is_file($this->file=($tmp.
- $fw->SEED.'.'.$hash.'.php')))
- $fw->write($this->file,$this->build($node));
- if (isset($_COOKIE[session_name()]) &&
- !headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
- session_start();
- $fw->sync('SESSION');
- $data=$this->sandbox($hive);
- }
- else {
- if (!$hive)
- $hive=$fw->hive();
- if ($fw->ESCAPE)
- $hive=$this->esc($hive);
- extract($hive);
- unset($hive);
- ob_start();
- eval(' ?>'.$this->build($node).'set($hash,$data,$ttl);
- if ($escape!==NULL)
- $fw->ESCAPE=$esc;
- return $data;
- }
-
- /**
- * Parse template string
- * @return string
- * @param $text string
- **/
- function parse($text) {
- // Remove PHP code and comments
- return preg_replace(
- '/\h*<\?(?!xml)(?:php|\s*=)?.+?\?>\h*|'.
- '\{\*.+?\*\}/is','', $text);
- }
-
- /**
- * Render template
- * @return string
- * @param $file string
- * @param $mime string
- * @param $hive array
- * @param $ttl int
- **/
- function render($file,$mime='text/html',array $hive=NULL,$ttl=0) {
- $fw=$this->fw;
- $cache=Cache::instance();
- if (!is_dir($tmp=$fw->TEMP))
- mkdir($tmp,Base::MODE,TRUE);
- foreach ($fw->split($fw->UI) as $dir) {
- if ($cache->exists($hash=$fw->hash($dir.$file),$data))
- return $data;
- if (is_file($view=$fw->fixslashes($dir.$file))) {
- if (!is_file($this->file=($tmp.
- $fw->SEED.'.'.$fw->hash($view).'.php')) ||
- filemtime($this->file)'.$this->build($str).''."\n\n"):''; - } - - /** - * Process whitespace-prefixed code block - * @return string - * @param $str string - **/ - protected function _pre($str) { - $str=preg_replace('/(?<=^|\n)(?: {4}|\t)(.+?(?:\n+|$))/','\1', - $this->esc($str)); - return strlen($str)? - ('
'.
- $this->esc($this->snip($str)).
- ''."\n\n"):
- '';
- }
-
- /**
- * Process fenced code block
- * @return string
- * @param $hint string
- * @param $str string
- **/
- protected function _fence($hint,$str) {
- $str=$this->snip($str);
- $fw=Base::instance();
- if ($fw->HIGHLIGHT) {
- switch (strtolower($hint)) {
- case 'php':
- $str=$fw->highlight($str);
- break;
- case 'apache':
- preg_match_all('/(?<=^|\n)(\h*)'.
- '(?:(<\/?)(\w+)((?:\h+[^>]+)*)(>)|'.
- '(?:(\w+)(\h.+?)))(\h*(?:\n+|$))/',
- $str,$matches,PREG_SET_ORDER);
- $out='';
- foreach ($matches as $match)
- $out.=$match[1].
- ($match[3]?
- (''.
- $this->esc($match[2]).$match[3].
- ''.
- ($match[4]?
- (''.
- $this->esc($match[4]).
- ''):
- '').
- ''.
- $this->esc($match[5]).
- ''):
- (''.
- $match[6].
- ''.
- ''.
- $this->esc($match[7]).
- '')).
- $match[8];
- $str=''.$out.'';
- break;
- case 'html':
- preg_match_all(
- '/(?:(?:<(\/?)(\w+)'.
- '((?:\h+(?:\w+\h*=\h*)?".+?"|[^>]+)*|'.
- '\h+.+?)(\h*\/?)>)|(.+?))/s',
- $str,$matches,PREG_SET_ORDER
- );
- $out='';
- foreach ($matches as $match) {
- if ($match[2]) {
- $out.='<'.
- $match[1].$match[2].'';
- if ($match[3]) {
- preg_match_all(
- '/(?:\h+(?:(?:(\w+)\h*=\h*)?'.
- '(".+?")|(.+)))/',
- $match[3],$parts,PREG_SET_ORDER
- );
- foreach ($parts as $part)
- $out.=' '.
- (empty($part[3])?
- ((empty($part[1])?
- '':
- (''.
- $part[1].'=')).
- ''.
- $part[2].''):
- (''.
- $part[3].''));
- }
- $out.=''.
- $match[4].'>';
- }
- else
- $out.=$this->esc($match[5]);
- }
- $str=''.$out.'';
- break;
- case 'ini':
- preg_match_all(
- '/(?<=^|\n)(?:'.
- '(;[^\n]*)|(?:<\?php.+?\?>?)|'.
- '(?:\[(.+?)\])|'.
- '(.+?)\h*=\h*'.
- '((?:\\\\\h*\r?\n|.+?)*)'.
- ')((?:\r?\n)+|$)/',
- $str,$matches,PREG_SET_ORDER
- );
- $out='';
- foreach ($matches as $match) {
- if ($match[1])
- $out.=''.$match[1].
- '';
- elseif ($match[2])
- $out.='['.$match[2].']'.
- '';
- elseif ($match[3])
- $out.=''.$match[3].
- '='.
- ($match[4]?
- (''.
- $match[4].''):'');
- else
- $out.=$match[0];
- if (isset($match[5]))
- $out.=$match[5];
- }
- $str=''.$out.'';
- break;
- default:
- $str=''.$this->esc($str).'';
- break;
- }
- }
- else
- $str=''.$this->esc($str).'';
- return ''.$str.''."\n\n"; - } - - /** - * Process horizontal rule - * @return string - **/ - protected function _hr() { - return '
'.$this->scan($str).'
'."\n\n"; - } - return ''; - } - - /** - * Process strong/em/strikethrough spans - * @return string - * @param $str string - **/ - protected function _text($str) { - $tmp=''; - while ($str!=$tmp) - $str=preg_replace_callback( - '/(?<=\s|^)(?'.$expr[2].'