From 33afc334055a6cac5466a2b97d03de89dc87d999 Mon Sep 17 00:00:00 2001 From: Bartek Fabiszewski Date: Thu, 20 Feb 2020 17:08:47 +0100 Subject: [PATCH] Refactor config class --- .tests/lib/BaseDatabaseTestCase.php | 4 + .tests/tests/ConfigTest.php | 121 +++++++++---- .tests/tests/ImportTest.php | 8 +- .tests/tests/InternalAPITest.php | 20 +-- .tests/tests/LangTest.php | 19 +- client/index.php | 224 ++++++++++++------------ helpers/auth.php | 4 +- helpers/config.php | 258 ++++++++++++++++------------ helpers/db.php | 52 +++++- helpers/lang.php | 9 +- helpers/user.php | 30 ++-- index.php | 23 +-- login.php | 7 +- scripts/import_cli.php | 17 +- scripts/setup.php | 87 +++++++--- utils/changepass.php | 75 ++++---- utils/export.php | 9 +- utils/getinit.php | 27 +-- utils/getpositions.php | 6 +- utils/gettracks.php | 4 +- utils/getusers.php | 4 +- utils/handleposition.php | 73 ++++---- utils/handletrack.php | 71 ++++---- utils/handleuser.php | 99 +++++------ utils/import.php | 3 +- 25 files changed, 731 insertions(+), 523 deletions(-) diff --git a/.tests/lib/BaseDatabaseTestCase.php b/.tests/lib/BaseDatabaseTestCase.php index 1c38d02..b97c519 100644 --- a/.tests/lib/BaseDatabaseTestCase.php +++ b/.tests/lib/BaseDatabaseTestCase.php @@ -1,6 +1,7 @@ mockConfig = new uConfig(false); } public static function setUpBeforeClass() { diff --git a/.tests/tests/ConfigTest.php b/.tests/tests/ConfigTest.php index 07779f5..499a01f 100644 --- a/.tests/tests/ConfigTest.php +++ b/.tests/tests/ConfigTest.php @@ -6,6 +6,8 @@ require_once(__DIR__ . "/../lib/UloggerDatabaseTestCase.php"); class ConfigTest extends UloggerDatabaseTestCase { + private $config; + private $mapApi; private $latitude; private $longitude; @@ -26,6 +28,7 @@ class ConfigTest extends UloggerDatabaseTestCase { public function setUp() { parent::setUp(); + $this->config = uConfig::getInstance(); $this->initConfigValues(); } @@ -60,25 +63,75 @@ class ConfigTest extends UloggerDatabaseTestCase { } public function testSetFromDatabase() { - uConfig::setFromDatabase(); - $this->assertEquals($this->mapApi, uConfig::$mapApi); - $this->assertEquals($this->latitude, uConfig::$initLatitude); - $this->assertEquals($this->longitude, uConfig::$initLongitude); - $this->assertEquals($this->googleKey, uConfig::$googleKey); - $this->assertEquals($this->requireAuth, uConfig::$requireAuthentication); - $this->assertEquals($this->publicTracks, uConfig::$publicTracks); - $this->assertEquals($this->passLenMin, uConfig::$passLenMin); - $this->assertEquals($this->passStrength, uConfig::$passStrength); - $this->assertEquals($this->interval, uConfig::$interval); - $this->assertEquals($this->lang, uConfig::$lang); - $this->assertEquals($this->units, uConfig::$units); - $this->assertEquals($this->strokeWeight, uConfig::$strokeWeight); - $this->assertEquals($this->strokeColor, uConfig::$strokeColor); - $this->assertEquals($this->strokeOpacity, uConfig::$strokeOpacity); + $this->assertEquals($this->mapApi, $this->config->mapApi); + $this->assertEquals($this->latitude, $this->config->initLatitude); + $this->assertEquals($this->longitude, $this->config->initLongitude); + $this->assertEquals($this->googleKey, $this->config->googleKey); + $this->assertEquals($this->requireAuth, $this->config->requireAuthentication); + $this->assertEquals($this->publicTracks, $this->config->publicTracks); + $this->assertEquals($this->passLenMin, $this->config->passLenMin); + $this->assertEquals($this->passStrength, $this->config->passStrength); + $this->assertEquals($this->interval, $this->config->interval); + $this->assertEquals($this->lang, $this->config->lang); + $this->assertEquals($this->units, $this->config->units); + $this->assertEquals($this->strokeWeight, $this->config->strokeWeight); + $this->assertEquals($this->strokeColor, $this->config->strokeColor); + $this->assertEquals($this->strokeOpacity, $this->config->strokeOpacity); - $this->assertEquals($this->testLayer, uConfig::$olLayers[0]->name); - $this->assertEquals($this->testUrl, uConfig::$olLayers[0]->url); - $this->assertEquals($this->testPriority, uConfig::$olLayers[0]->priority); + $this->assertEquals($this->testLayer, $this->config->olLayers[0]->name); + $this->assertEquals($this->testUrl, $this->config->olLayers[0]->url); + $this->assertEquals($this->testPriority, $this->config->olLayers[0]->priority); + } + + public function testSave() { + $this->config->mapApi = 'newApi'; + $this->config->initLatitude = 33.11; + $this->config->initLongitude = 22.11; + $this->config->googleKey = 'newKey'; + $this->config->requireAuthentication = false; + $this->config->publicTracks = false; + $this->config->passLenMin = 31; + $this->config->passStrength = 31; + $this->config->interval = 661; + $this->config->lang = 'newLang'; + $this->config->units = 'newUnits'; + $this->config->strokeWeight = 551; + $this->config->strokeColor = '#bfbfbf'; + $this->config->strokeOpacity = 0.11; + $this->config->olLayers = []; + $this->config->olLayers[0] = new uLayer(11, 'newLayer', 'newUrl', 51); + + $this->config->save(); + + $this->assertEquals(1, $this->getConnection()->getRowCount('config'), "Wrong row count"); + $expected = [ + "map_api" => $this->config->mapApi, + "latitude" => $this->config->initLatitude, + "longitude" => $this->config->initLongitude, + "google_key" => $this->config->googleKey, + "require_auth" => $this->config->requireAuthentication, + "public_tracks" => $this->config->publicTracks, + "pass_lenmin" => $this->config->passLenMin, + "pass_strength" => $this->config->passStrength, + "interval_seconds" => $this->config->interval, + "lang" => $this->config->lang, + "units" => $this->config->units, + "stroke_weight" => $this->config->strokeWeight, + "stroke_color" => hexdec(str_replace('#', '', $this->config->strokeColor)), + "stroke_opacity" => (int) ($this->config->strokeOpacity * 100) + ]; + $actual = $this->getConnection()->createQueryTable("config", "SELECT * FROM config"); + $this->assertTableContains($expected, $actual, "Wrong actual table data: " . implode(', ', $actual->getRow(0))); + + $this->assertEquals(1, $this->getConnection()->getRowCount('ol_layers'), "Wrong row count"); + $expected = [ + "id" => $this->config->olLayers[0]->id, + "name" => $this->config->olLayers[0]->name, + "url" => $this->config->olLayers[0]->url, + "priority" => $this->config->olLayers[0]->priority + ]; + $actual = $this->getConnection()->createQueryTable("ol_layers", "SELECT * FROM ol_layers"); + $this->assertTableContains($expected, $actual, "Wrong actual table data: " . implode(', ', $actual->getRow(0))); } private function initConfigValues() { @@ -102,35 +155,35 @@ class ConfigTest extends UloggerDatabaseTestCase { } public function testPassRegex() { - uConfig::$passLenMin = 0; - uConfig::$passStrength = 0; + $this->config->passLenMin = 0; + $this->config->passStrength = 0; $password0 = "password"; $password1 = "PASSword"; $password2 = "PASSword1234"; $password3 = "PASSword1234-;"; - $regex = uConfig::passRegex(); + $regex = $this->config->passRegex(); $this->assertRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); $this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\""); - uConfig::$passStrength = 1; - $regex = uConfig::passRegex(); + $this->config->passStrength = 1; + $regex = $this->config->passRegex(); $this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); $this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\""); - uConfig::$passStrength = 2; - $regex = uConfig::passRegex(); + $this->config->passStrength = 2; + $regex = $this->config->passRegex(); $this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertNotRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); $this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\""); - uConfig::$passStrength = 3; - $regex = uConfig::passRegex(); + $this->config->passStrength = 3; + $regex = $this->config->passRegex(); $this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertNotRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertNotRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); @@ -138,19 +191,19 @@ class ConfigTest extends UloggerDatabaseTestCase { $password_len5 = "12345"; $password_len10 = "1234567890"; - uConfig::$passLenMin = 5; - uConfig::$passStrength = 0; - $regex = uConfig::passRegex(); + $this->config->passLenMin = 5; + $this->config->passStrength = 0; + $regex = $this->config->passRegex(); $this->assertRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\""); $this->assertRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\""); - uConfig::$passLenMin = 7; - $regex = uConfig::passRegex(); + $this->config->passLenMin = 7; + $regex = $this->config->passRegex(); $this->assertNotRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\""); $this->assertRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\""); - uConfig::$passLenMin = 12; - $regex = uConfig::passRegex(); + $this->config->passLenMin = 12; + $regex = $this->config->passRegex(); $this->assertNotRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\""); $this->assertNotRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\""); } diff --git a/.tests/tests/ImportTest.php b/.tests/tests/ImportTest.php index 1b3dba8..904366a 100644 --- a/.tests/tests/ImportTest.php +++ b/.tests/tests/ImportTest.php @@ -626,7 +626,7 @@ class ImportTest extends UloggerAPITestCase { } public function testImportNoLongitude() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); @@ -673,7 +673,7 @@ class ImportTest extends UloggerAPITestCase { } public function testImportNoLatitude() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); @@ -720,7 +720,7 @@ class ImportTest extends UloggerAPITestCase { } public function testImportNoGPX() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); @@ -761,7 +761,7 @@ class ImportTest extends UloggerAPITestCase { } public function testImportCorrupt() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); diff --git a/.tests/tests/InternalAPITest.php b/.tests/tests/InternalAPITest.php index 6f49c8a..7d5f13c 100644 --- a/.tests/tests/InternalAPITest.php +++ b/.tests/tests/InternalAPITest.php @@ -666,7 +666,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleTrackDeleteOtherUser() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertTrue($this->authenticate($this->testUser, $this->testPass), "Authentication failed"); @@ -728,7 +728,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleTrackUpdateEmptyName() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $userId = $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); @@ -752,7 +752,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleTrackUpdateNonexistantTrack() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $newName = "New name"; $this->assertTrue($this->authenticate(), "Authentication failed"); $userId = $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); @@ -776,7 +776,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleTrackMissingAction() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $options = [ @@ -794,7 +794,7 @@ class InternalAPITest extends UloggerAPITestCase { /* handleuser.php */ public function testHandleUserMissingAction() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $options = [ @@ -809,7 +809,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleUserNonAdmin() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertTrue($this->authenticate($this->testUser, $this->testPass), "Authentication failed"); @@ -829,7 +829,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleUserSelf() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertEquals(1, $this->getConnection()->getRowCount("users"), "Wrong row count"); @@ -847,7 +847,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleUserEmptyLogin() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertEquals(1, $this->getConnection()->getRowCount("users"), "Wrong row count"); @@ -865,7 +865,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleUserNoAuth() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); @@ -908,7 +908,7 @@ class InternalAPITest extends UloggerAPITestCase { } public function testHandleUserAddSameLogin() { - $lang = (new uLang("en"))->getStrings(); + $lang = (new uLang($this->mockConfig))->getStrings(); $this->assertTrue($this->authenticate(), "Authentication failed"); $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); diff --git a/.tests/tests/LangTest.php b/.tests/tests/LangTest.php index 4078306..ba2fdee 100644 --- a/.tests/tests/LangTest.php +++ b/.tests/tests/LangTest.php @@ -1,11 +1,20 @@ mockConfig = new uConfig(false); + } + public function testGetLanguages() { $languages = uLang::getLanguages(); $this->assertNotEmpty($languages); @@ -16,16 +25,18 @@ class LangTest extends TestCase { } public function testGetStrings() { - $lang = new uLang("en"); + $lang = new uLang($this->mockConfig); $this->assertEquals("User", $lang->getStrings()["user"]); - $lang = new uLang("pl"); + $this->mockConfig->lang = "pl"; + $lang = new uLang($this->mockConfig); $this->assertEquals("Użytkownik", $lang->getStrings()["user"]); } public function testGetSetupStrings() { - $lang = new uLang("en"); + $lang = new uLang($this->mockConfig); $this->assertEquals("Congratulations!", $lang->getSetupStrings()["congratulations"]); - $lang = new uLang("pl"); + $this->mockConfig->lang = "pl"; + $lang = new uLang($this->mockConfig); $this->assertEquals("Gratulacje!", $lang->getSetupStrings()["congratulations"]); } } diff --git a/client/index.php b/client/index.php index 3de795d..0ce3dc8 100644 --- a/client/index.php +++ b/client/index.php @@ -17,125 +17,125 @@ * along with this program; if not, see . */ - /** - * Exit with error status and message - * - * @param string $message Message - */ - function exitWithError($message) { - $response = []; - $response['error'] = true; - $response['message'] = $message; - header('Content-Type: application/json'); - echo json_encode($response); - exit(); - } +/** + * Exit with error status and message + * + * @param string $message Message + */ +function exitWithError($message) { + $response = []; + $response['error'] = true; + $response['message'] = $message; + header('Content-Type: application/json'); + echo json_encode($response); + exit(); +} - /** - * Exit with success status - * - * @param array $params Optional params - * @return void - */ - function exitWithSuccess($params = []) { - $response = []; - $response['error'] = false; - header('Content-Type: application/json'); - echo json_encode(array_merge($response, $params)); - exit(); - } +/** + * Exit with success status + * + * @param array $params Optional params + * @return void + */ +function exitWithSuccess($params = []) { + $response = []; + $response['error'] = false; + header('Content-Type: application/json'); + echo json_encode(array_merge($response, $params)); + exit(); +} - require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(dirname(__DIR__) . "/helpers/auth.php"); - $action = uUtils::postString('action'); +$action = uUtils::postString('action'); - $auth = new uAuth(); - if (!$auth->isAuthenticated() && $action != "auth") { - $auth->sendUnauthorizedHeader(); - exitWithError("Unauthorized"); - } +$auth = new uAuth(); +if ($action !== "auth" && !$auth->isAuthenticated()) { + $auth->sendUnauthorizedHeader(); + exitWithError("Unauthorized"); +} switch ($action) { - // action: authorize - case "auth": - $login = uUtils::postString('user'); - $pass = uUtils::postPass('pass'); - if ($auth->checkLogin($login, $pass)) { - exitWithSuccess(); - } else { - $auth->sendUnauthorizedHeader(); - exitWithError("Unauthorized"); - } - break; - - // action: adduser (currently unused) - case "adduser": - if (!$auth->user->isAdmin) { - exitWithError("Not allowed"); - } - $login = uUtils::postString('login'); - $pass = uUtils::postPass('password'); - if (empty($login) || empty($pass)) { - exitWithError("Empty login or password"); - } - $newId = uUser::add($login, $pass); - if ($newId === false) { - exitWithError("Server error"); - } - exitWithSuccess(['userid'=> $newId]); - break; - - // action: addtrack - case "addtrack": - $trackName = uUtils::postString('track'); - if (empty($trackName)) { - exitWithError("Missing required parameter"); - } - require_once(ROOT_DIR . "/helpers/track.php"); - $trackId = uTrack::add($auth->user->id, $trackName); - if ($trackId === false) { - exitWithError("Server error"); - } - // return track id - exitWithSuccess(['trackid' => $trackId]); - break; - - // action: addposition - case "addpos": - $lat = uUtils::postFloat('lat'); - $lon = uUtils::postFloat('lon'); - $timestamp = uUtils::postInt('time'); - $altitude = uUtils::postFloat('altitude'); - $speed = uUtils::postFloat('speed'); - $bearing = uUtils::postFloat('bearing'); - $accuracy = uUtils::postInt('accuracy'); - $provider = uUtils::postString('provider'); - $comment = uUtils::postString('comment'); - $imageMeta = uUtils::requestFile('image'); - $trackId = uUtils::postInt('trackid'); - - if (!is_float($lat) || !is_float($lon) || !is_int($timestamp) || !is_int($trackId)) { - exitWithError("Missing required parameter"); - } - - $image = null; - if (!empty($imageMeta)) { - $image = uUpload::add($imageMeta, $trackId); - } - - require_once(ROOT_DIR . "/helpers/position.php"); - $positionId = uPosition::add($auth->user->id, $trackId, - $timestamp, $lat, $lon, $altitude, $speed, $bearing, $accuracy, $provider, $comment, $image); - - if ($positionId === false) { - exitWithError("Server error"); - } + // action: authorize + case "auth": + $login = uUtils::postString('user'); + $pass = uUtils::postPass('pass'); + if ($auth->checkLogin($login, $pass)) { exitWithSuccess(); - break; + } else { + $auth->sendUnauthorizedHeader(); + exitWithError("Unauthorized"); + } + break; - default: - exitWithError("Unknown command"); - break; - } + // action: adduser (currently unused) + case "adduser": + if (!$auth->user->isAdmin) { + exitWithError("Not allowed"); + } + $login = uUtils::postString('login'); + $pass = uUtils::postPass('password'); + if (empty($login) || empty($pass)) { + exitWithError("Empty login or password"); + } + $newId = uUser::add($login, $pass); + if ($newId === false) { + exitWithError("Server error"); + } + exitWithSuccess(['userid' => $newId]); + break; + + // action: addtrack + case "addtrack": + $trackName = uUtils::postString('track'); + if (empty($trackName)) { + exitWithError("Missing required parameter"); + } + require_once(ROOT_DIR . "/helpers/track.php"); + $trackId = uTrack::add($auth->user->id, $trackName); + if ($trackId === false) { + exitWithError("Server error"); + } + // return track id + exitWithSuccess(['trackid' => $trackId]); + break; + + // action: addposition + case "addpos": + $lat = uUtils::postFloat('lat'); + $lon = uUtils::postFloat('lon'); + $timestamp = uUtils::postInt('time'); + $altitude = uUtils::postFloat('altitude'); + $speed = uUtils::postFloat('speed'); + $bearing = uUtils::postFloat('bearing'); + $accuracy = uUtils::postInt('accuracy'); + $provider = uUtils::postString('provider'); + $comment = uUtils::postString('comment'); + $imageMeta = uUtils::requestFile('image'); + $trackId = uUtils::postInt('trackid'); + + if (!is_float($lat) || !is_float($lon) || !is_int($timestamp) || !is_int($trackId)) { + exitWithError("Missing required parameter"); + } + + $image = null; + if (!empty($imageMeta)) { + $image = uUpload::add($imageMeta, $trackId); + } + + require_once(ROOT_DIR . "/helpers/position.php"); + $positionId = uPosition::add($auth->user->id, $trackId, + $timestamp, $lat, $lon, $altitude, $speed, $bearing, $accuracy, $provider, $comment, $image); + + if ($positionId === false) { + exitWithError("Server error"); + } + exitWithSuccess(); + break; + + default: + exitWithError("Unknown command"); + break; +} ?> \ No newline at end of file diff --git a/helpers/auth.php b/helpers/auth.php index afe9f78..a4f2e4f 100644 --- a/helpers/auth.php +++ b/helpers/auth.php @@ -30,12 +30,12 @@ /** @var bool Is user authenticated */ private $isAuthenticated = false; /** @var null|uUser */ - public $user = null; + public $user; public function __construct() { $this->sessionStart(); - $user = (new uUser())->getFromSession(); + $user = uUser::getFromSession(); if ($user->isValid) { $this->setAuthenticated($user); } diff --git a/helpers/config.php b/helpers/config.php index 8c12abd..8700972 100644 --- a/helpers/config.php +++ b/helpers/config.php @@ -20,75 +20,60 @@ require_once(ROOT_DIR . "/helpers/db.php"); require_once(ROOT_DIR . "/helpers/layer.php"); -/** - * Initialize on file include - */ -uConfig::init(); /** * Handles config values */ class uConfig { + /** + * Singleton instance + * + * @var uConfig Object instance + */ + private static $instance; /** * @var string Version number */ - public static $version = "1.0-beta"; + public $version = "1.0-beta"; /** * @var string Default map drawing framework */ - public static $mapApi = "openlayers"; + public $mapApi = "openlayers"; /** * @var string|null Google maps key */ - public static $googleKey; + public $googleKey; /** * @var uLayer[] Openlayers extra map layers */ - public static $olLayers = []; + public $olLayers = []; /** * @var float Default latitude for initial map */ - public static $initLatitude = 52.23; + public $initLatitude = 52.23; /** * @var float Default longitude for initial map */ - public static $initLongitude = 21.01; - - /** - * @var string Database DSN - */ - public static $dbdsn = ""; - /** - * @var string Database user - */ - public static $dbuser = ""; - /** - * @var string Database pass - */ - public static $dbpass = ""; - /** - * @var string Optional table names prefix, eg. "ulogger_" - */ - public static $dbprefix = ""; + public $initLongitude = 21.01; /** * @var bool Require login/password authentication */ - public static $requireAuthentication = true; + public $requireAuthentication = true; /** * @var bool All users tracks are visible to authenticated user */ - public static $publicTracks = false; + public $publicTracks = false; /** * @var int Miniumum required length of user password */ - public static $passLenMin = 10; + public $passLenMin = 10; /** * @var int Required strength of user password @@ -97,49 +82,65 @@ class uConfig { * 2 = require mixed case and numbers * 3 = require mixed case, numbers and non-alphanumeric characters */ - public static $passStrength = 2; + public $passStrength = 2; /** * @var int Default interval in seconds for live auto reload */ - public static $interval = 10; + public $interval = 10; /** * @var string Default language code */ - public static $lang = "en"; + public $lang = "en"; /** * @var string Default units */ - public static $units = "metric"; + public $units = "metric"; /** * @var int Stroke weight */ - public static $strokeWeight = 2; + public $strokeWeight = 2; /** * @var string Stroke color */ - public static $strokeColor = '#ff0000'; + public $strokeColor = '#ff0000'; /** - * @var int Stroke opacity + * @var float Stroke opacity */ - public static $strokeOpacity = 1; - - private static $fileLoaded = false; - private static $initialized = false; - - /** - * Static initializer - */ - public static function init() { - if (!self::$initialized) { - self::setFromFile(); - self::setFromDatabase(); - self::setFromCookies(); - self::$initialized = true; + public $strokeOpacity = 1.0; + + public function __construct($useDatabase = true) { + if ($useDatabase) { + $this->setFromDatabase(); } + $this->setFromCookies(); + } + + /** + * Returns singleton instance + * + * @return uConfig Singleton instance + */ + public static function getInstance() { + if (!self::$instance) { + self::$instance = new self(); + } + return self::$instance; + } + + /** + * Returns singleton instance + * + * @return uConfig Singleton instance + */ + public static function getOfflineInstance() { + if (!self::$instance) { + self::$instance = new self(false); + } + return self::$instance; } /** @@ -154,7 +155,7 @@ class uConfig { /** * Read config values from database */ - public static function setFromDatabase() { + public function setFromDatabase() { try { $query = "SELECT map_api, latitude, longitude, google_key, require_auth, public_tracks, pass_lenmin, pass_strength, interval_seconds, lang, units, @@ -163,30 +164,91 @@ class uConfig { $result = self::db()->query($query); $row = $result->fetch(); if ($row) { - if (!empty($row['map_api'])) { self::$mapApi = $row['map_api']; } - if (is_numeric($row['latitude'])) { self::$initLatitude = $row['latitude']; } - if (is_numeric($row['longitude'])) { self::$initLongitude = $row['longitude']; } - if (!empty($row['google_key'])) { self::$googleKey = $row['google_key']; } - if (is_numeric($row['require_auth']) || is_bool($row['require_auth'])) { self::$requireAuthentication = (bool) $row['require_auth']; } - if (is_numeric($row['public_tracks']) || is_bool($row['public_tracks'])) { self::$publicTracks = (bool) $row['public_tracks']; } - if (is_numeric($row['pass_lenmin'])) { self::$passLenMin = $row['pass_lenmin']; } - if (is_numeric($row['pass_strength'])) { self::$passStrength = $row['pass_strength']; } - if (is_numeric($row['interval_seconds'])) { self::$interval = $row['interval_seconds']; } - if (!empty($row['lang'])) { self::$lang = $row['lang']; } - if (!empty($row['units'])) { self::$units = $row['units']; } - if (is_numeric($row['stroke_weight'])) { self::$strokeWeight = $row['stroke_weight']; } - if (is_numeric($row['stroke_color'])) { self::$strokeColor = self::getColorAsHex($row['stroke_color']); } - if (is_numeric($row['stroke_opacity'])) { self::$strokeOpacity = $row['stroke_opacity'] / 100; } + if (!empty($row['map_api'])) { $this->mapApi = $row['map_api']; } + if (is_numeric($row['latitude'])) { $this->initLatitude = (float) $row['latitude']; } + if (is_numeric($row['longitude'])) { $this->initLongitude = (float) $row['longitude']; } + if (!empty($row['google_key'])) { $this->googleKey = $row['google_key']; } + if (is_numeric($row['require_auth']) || is_bool($row['require_auth'])) { $this->requireAuthentication = (bool) $row['require_auth']; } + if (is_numeric($row['public_tracks']) || is_bool($row['public_tracks'])) { $this->publicTracks = (bool) $row['public_tracks']; } + if (is_numeric($row['pass_lenmin'])) { $this->passLenMin = (int) $row['pass_lenmin']; } + if (is_numeric($row['pass_strength'])) { $this->passStrength = (int) $row['pass_strength']; } + if (is_numeric($row['interval_seconds'])) { $this->interval = (int) $row['interval_seconds']; } + if (!empty($row['lang'])) { $this->lang = $row['lang']; } + if (!empty($row['units'])) { $this->units = $row['units']; } + if (is_numeric($row['stroke_weight'])) { $this->strokeWeight = (int) $row['stroke_weight']; } + if (is_numeric($row['stroke_color'])) { $this->strokeColor = self::getColorAsHex($row['stroke_color']); } + if (is_numeric($row['stroke_opacity'])) { $this->strokeOpacity = $row['stroke_opacity'] / 100; } } - self::setLayersFromDatabase(); - if (!self::$requireAuthentication) { + $this->setLayersFromDatabase(); + if (!$this->requireAuthentication) { // tracks must be public if we don't require authentication - self::$publicTracks = true; + $this->publicTracks = true; } } catch (PDOException $e) { // TODO: handle exception syslog(LOG_ERR, $e->getMessage()); - return; + } + } + + /** + * Save config values to database + * @return bool True on success, false otherwise + */ + public function save() { + $ret = false; + try { + $query = "UPDATE " . self::db()->table('config') . " + SET map_api = ?, latitude = ?, longitude = ?, google_key = ?, require_auth = ?, public_tracks = ?, + pass_lenmin = ?, pass_strength = ?, interval_seconds = ?, lang = ?, units = ?, + stroke_weight = ?, stroke_color = ?, stroke_opacity = ?"; + $stmt = self::db()->prepare($query); + $params = [ + $this->mapApi, + $this->initLatitude, + $this->initLongitude, + $this->googleKey, + (int) $this->requireAuthentication, + (int) $this->publicTracks, + $this->passLenMin, + $this->passStrength, + $this->interval, + $this->lang, + $this->units, + $this->strokeWeight, + self::getColorAsInt($this->strokeColor), + (int) ($this->strokeOpacity * 100) + ]; + $stmt->execute($params); + $this->saveLayers(); + $ret = true; + } catch (PDOException $e) { + // TODO: handle exception + syslog(LOG_ERR, $e->getMessage()); + } + return $ret; + } + + /** + * Truncate ol_layers table + * @throws PDOException + */ + private function deleteLayers() { + $query = "DELETE FROM " . self::db()->table('ol_layers'); + self::db()->exec($query); + } + + /** + * Save layers to database + * @throws PDOException + */ + private function saveLayers() { + $this->deleteLayers(); + if (!empty($this->olLayers)) { + $query = "INSERT INTO " . self::db()->table('ol_layers') . " (id, name, url, priority) VALUES (?, ?, ?, ?)"; + $stmt = self::db()->prepare($query); + foreach ($this->olLayers as $layer) { + $stmt->execute([ $layer->id, $layer->name, $layer->url, $layer->priority]); + } } } @@ -194,50 +256,34 @@ class uConfig { * Read config values from database * @throws PDOException */ - private static function setLayersFromDatabase() { - self::$olLayers = []; + private function setLayersFromDatabase() { + $this->olLayers = []; $query = "SELECT id, name, url, priority FROM " . self::db()->table('ol_layers'); $result = self::db()->query($query); while ($row = $result->fetch()) { - self::$olLayers[] = new uLayer($row['id'], $row['name'], $row['url'], $row['priority']); + $this->olLayers[] = new uLayer($row['id'], $row['name'], $row['url'], $row['priority']); } } - /** - * Read config values from "/config.php" file - * @noinspection IssetArgumentExistenceInspection - * @noinspection DuplicatedCode - * @noinspection PhpIncludeInspection - */ - private static function setFromFile() { - $configFile = ROOT_DIR . "/config.php"; - if (self::$fileLoaded || !file_exists($configFile)) { return; } - self::$fileLoaded = true; - include_once($configFile); - - if (isset($dbdsn)) { self::$dbdsn = $dbdsn; } - if (isset($dbuser)) { self::$dbuser = $dbuser; } - if (isset($dbpass)) { self::$dbpass = $dbpass; } - if (isset($dbprefix)) { self::$dbprefix = $dbprefix; } - } - /** * Read config values stored in cookies */ - private static function setFromCookies() { - if (isset($_COOKIE["ulogger_api"])) { self::$mapApi = $_COOKIE["ulogger_api"]; } - if (isset($_COOKIE["ulogger_lang"])) { self::$lang = $_COOKIE["ulogger_lang"]; } - if (isset($_COOKIE["ulogger_units"])) { self::$units = $_COOKIE["ulogger_units"]; } - if (isset($_COOKIE["ulogger_interval"])) { self::$interval = $_COOKIE["ulogger_interval"]; } + private function setFromCookies() { + if (isset($_COOKIE["ulogger_api"])) { $this->mapApi = $_COOKIE["ulogger_api"]; } + if (isset($_COOKIE["ulogger_lang"])) { $this->lang = $_COOKIE["ulogger_lang"]; } + if (isset($_COOKIE["ulogger_units"])) { $this->units = $_COOKIE["ulogger_units"]; } + if (isset($_COOKIE["ulogger_interval"])) { $this->interval = $_COOKIE["ulogger_interval"]; } } + /** - * Is config loaded from file? + * Check if given password matches user's one * - * @return bool True if loaded, false otherwise + * @param String $password Password + * @return bool True if matches, false otherwise */ - public static function isFileLoaded() { - return self::$fileLoaded; + public function validPassStrength($password) { + return preg_match($this->passRegex(), $password); } /** @@ -245,22 +291,22 @@ class uConfig { * Valid for both php and javascript * @return string */ - public static function passRegex() { + public function passRegex() { $regex = ""; - if (self::$passStrength > 0) { + if ($this->passStrength > 0) { // lower and upper case $regex .= "(?=.*[a-z])(?=.*[A-Z])"; } - if (self::$passStrength > 1) { + if ($this->passStrength > 1) { // digits $regex .= "(?=.*[0-9])"; } - if (self::$passStrength > 2) { + if ($this->passStrength > 2) { // not latin, not digits $regex .= "(?=.*[^a-zA-Z0-9])"; } - if (self::$passLenMin > 0) { - $regex .= "(?=.{" . self::$passLenMin . ",})"; + if ($this->passLenMin > 0) { + $regex .= "(?=.{" . $this->passLenMin . ",})"; } if (empty($regex)) { $regex = ".*"; diff --git a/helpers/db.php b/helpers/db.php index 71bc962..fc8015e 100644 --- a/helpers/db.php +++ b/helpers/db.php @@ -17,8 +17,6 @@ * along with this program; if not, see . */ - require_once(ROOT_DIR . "/helpers/config.php"); - /** * PDO wrapper */ @@ -44,6 +42,23 @@ */ protected static $driver; + /** + * @var string Database DSN + */ + private static $dbdsn = ""; + /** + * @var string Database user + */ + private static $dbuser = ""; + /** + * @var string Database pass + */ + private static $dbpass = ""; + /** + * @var string Optional table names prefix, eg. "ulogger_" + */ + private static $dbprefix = ""; + /** * PDO constuctor * @@ -73,7 +88,7 @@ */ private function initTables() { self::$tables = []; - $prefix = preg_replace('/[^a-z0-9_]/i', '', uConfig::$dbprefix); + $prefix = preg_replace('/[^a-z0-9_]/i', '', self::$dbprefix); self::$tables['positions'] = $prefix . "positions"; self::$tables['tracks'] = $prefix . "tracks"; self::$tables['users'] = $prefix . "users"; @@ -88,12 +103,39 @@ */ public static function getInstance() { if (!self::$instance) { - self::$instance = new self(uConfig::$dbdsn, uConfig::$dbuser, uConfig::$dbpass); + self::getConfig(); + self::$instance = new self(self::$dbdsn, self::$dbuser, self::$dbpass); } return self::$instance; } - /** + /** + * Read database setup from config file + * @noinspection IssetArgumentExistenceInspection + * @noinspection PhpIncludeInspection + */ + private static function getConfig() { + $configFile = dirname(__DIR__) . "/config.php"; + if (!file_exists($configFile)) { + header("HTTP/1.1 503 Service Unavailable"); + die("Missing config.php file!"); + } + include($configFile); + if (isset($dbdsn)) { + self::$dbdsn = $dbdsn; + } + if (isset($dbuser)) { + self::$dbuser = $dbuser; + } + if (isset($dbpass)) { + self::$dbpass = $dbpass; + } + if (isset($dbprefix)) { + self::$dbprefix = $dbprefix; + } + } + + /** * Get full table name including prefix * * @param string $name Name diff --git a/helpers/lang.php b/helpers/lang.php index f9a276b..0f97c0c 100644 --- a/helpers/lang.php +++ b/helpers/lang.php @@ -61,9 +61,10 @@ /** * Constructor * - * @param string $language Language code (IANA) + * @param uConfig $config Config */ - public function __construct($language = "en") { + public function __construct($config) { + $language = $config->lang; $lang = []; $langSetup = []; // always load en base @@ -76,9 +77,9 @@ } // choose password messages based on config - $passRules = "passrules_" . uConfig::$passStrength; + $passRules = "passrules_" . $config->passStrength; $lang['passrules'] = isset($lang[$passRules]) ? $lang[$passRules] : ""; - $lang['passlenmin'] = sprintf($lang["passlenmin"], uConfig::$passLenMin); + $lang['passlenmin'] = sprintf($lang["passlenmin"], $config->passLenMin); $this->strings = $lang; $this->setupStrings = $langSetup; } diff --git a/helpers/user.php b/helpers/user.php index 30c160d..9a3e3bb 100644 --- a/helpers/user.php +++ b/helpers/user.php @@ -16,7 +16,6 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ - require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/db.php"); require_once(ROOT_DIR . "/helpers/track.php"); require_once(ROOT_DIR . "/helpers/position.php"); @@ -75,7 +74,7 @@ */ public static function add($login, $pass, $isAdmin = false) { $userid = false; - if (!empty($login) && !empty($pass) && self::validPassStrength($pass)) { + if (!empty($login) && !empty($pass)) { $hash = password_hash($pass, PASSWORD_DEFAULT); $table = self::db()->table('users'); try { @@ -152,7 +151,7 @@ */ public function setPass($pass) { $ret = false; - if (!empty($this->login) && !empty($pass) && self::validPassStrength($pass)) { + if (!empty($this->login) && !empty($pass)) { $hash = password_hash($pass, PASSWORD_DEFAULT); try { $query = "UPDATE " . self::db()->table('users') . " SET password = ? WHERE login = ?"; @@ -178,16 +177,6 @@ return password_verify($password, $this->hash); } - /** - * Check if given password matches user's one - * - * @param String $password Password - * @return bool True if matches, false otherwise - */ - private static function validPassStrength($password) { - return preg_match(uConfig::passRegex(), $password); - } - /** * Store uUser object in session */ @@ -199,16 +188,17 @@ * Fill uUser object properties from session data * @return uUser */ - public function getFromSession() { + public static function getFromSession() { + $user = new uUser(); if (isset($_SESSION['user'])) { $sessionUser = $_SESSION['user']; - $this->id = $sessionUser->id; - $this->login = $sessionUser->login; - $this->hash = $sessionUser->hash; - $this->isAdmin = $sessionUser->isAdmin; - $this->isValid = $sessionUser->isValid; + $user->id = $sessionUser->id; + $user->login = $sessionUser->login; + $user->hash = $sessionUser->hash; + $user->isAdmin = $sessionUser->isAdmin; + $user->isValid = $sessionUser->isValid; } - return $this; + return $user; } /** diff --git a/index.php b/index.php index f05dd67..55c3ebd 100644 --- a/index.php +++ b/index.php @@ -28,7 +28,8 @@ $pass = uUtils::postPass('pass'); $action = uUtils::postString('action'); - $lang = (new uLang(uConfig::$lang))->getStrings(); + $config = uConfig::getInstance(); + $lang = (new uLang($config))->getStrings(); $langsArr = uLang::getLanguages(); $auth = new uAuth(); @@ -39,13 +40,13 @@ if ($action === 'auth' && !$auth->isAuthenticated()) { $auth->exitWithRedirect('login.php?auth_error=1'); } - if (uConfig::$requireAuthentication && !$auth->isAuthenticated()) { + if ($config->requireAuthentication && !$auth->isAuthenticated()) { $auth->exitWithRedirect('login.php'); } ?> - + <?= $lang['title'] ?> @@ -78,7 +79,7 @@
- ( s)
+ (interval ?> s)

@@ -91,8 +92,8 @@
@@ -100,7 +101,7 @@ @@ -108,9 +109,9 @@
@@ -142,7 +143,7 @@ - +
diff --git a/login.php b/login.php index 6cd16eb..92072e5 100644 --- a/login.php +++ b/login.php @@ -23,11 +23,12 @@ $auth_error = uUtils::getBool('auth_error', false); - $lang = (new uLang(uConfig::$lang))->getStrings(); + $config = uConfig::getInstance(); + $lang = (new uLang($config))->getStrings(); ?> - + <?= $lang["title"] ?> @@ -49,7 +50,7 @@
"> - + requireAuthentication): ?>
diff --git a/scripts/import_cli.php b/scripts/import_cli.php index 215a790..1c63ba1 100644 --- a/scripts/import_cli.php +++ b/scripts/import_cli.php @@ -33,7 +33,7 @@ if (file_exists(ROOT_DIR . '/vendor/autoload.php')) { } // check we are running in CLI mode -if (PHP_SAPI != 'cli') { +if (PHP_SAPI !== 'cli') { exit('Call me on CLI only!' . PHP_EOL); } @@ -90,7 +90,9 @@ if (!$getopt->getOption('import-existing-track')) { $gpxFiles = $getopt->getOperand('gpx'); foreach ($gpxFiles as $i => $gpxFile) { // skip last track? - if ($getopt->getOption('skip-last-track') && $i === count($gpxFiles) - 1) continue; + if ($getopt->getOption('skip-last-track') && $i === count($gpxFiles) - 1) { + continue; + } $gpxName = basename($gpxFile); @@ -105,7 +107,8 @@ foreach ($gpxFiles as $i => $gpxFile) { print('importing ' . $gpxFile.'...' . PHP_EOL); - $lang = (new uLang(uConfig::$lang))->getStrings(); + $config = uConfig::getInstance(); + $lang = (new uLang($config))->getStrings(); $gpx = false; libxml_use_internal_errors(true); @@ -125,8 +128,8 @@ foreach ($gpxFiles as $i => $gpxFile) { } uUtils::exitWithError($message); } - else if ($gpx->getName() != "gpx") { - uUtils::exitWithError($lang["iparsefailure"]); + else if ($gpx->getName() !== "gpx") { + uUtils::exitWithError($lang["iparsefailure"]); } else if (empty($gpx->trk)) { uUtils::exitWithError($lang["idatafailure"]); @@ -165,8 +168,8 @@ foreach ($gpxFiles as $i => $gpxFile) { if (count($ext->provider)) { $provider = (string) $ext->provider; } } $ret = $track->addPosition($userId, - $time, (double) $point["lat"], (double) $point["lon"], $altitude, - $speed, $bearing, $accuracy, $provider, NULL, NULL); + $time, (double) $point["lat"], (double) $point["lon"], $altitude, + $speed, $bearing, $accuracy, $provider, NULL, NULL); if ($ret === false) { $track->delete(); uUtils::exitWithError($lang["servererror"]); diff --git a/scripts/setup.php b/scripts/setup.php index 7773a80..578b3ca 100644 --- a/scripts/setup.php +++ b/scripts/setup.php @@ -30,6 +30,21 @@ if (version_compare(PHP_VERSION, "5.5.0", "<")) { } define("ROOT_DIR", dirname(__DIR__)); +$dbConfig = ROOT_DIR . "/config.php"; +$dbConfigLoaded = false; +$configDSN = ""; +$configUser = ""; +$configPass = ""; +$configPrefix = ""; +if (file_exists($dbConfig)) { + /** @noinspection PhpIncludeInspection */ + include($dbConfig); + $dbConfigLoaded = true; + if (isset($dbdsn)) { $configDSN = $dbdsn; } + if (isset($dbuser)) { $configUser = $dbuser; } + if (isset($dbpass)) { $configPass = $dbpass; } + if (isset($dbprefix)) { $configPrefix = $dbprefix; } +} require_once(ROOT_DIR . "/helpers/db.php"); require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/lang.php"); @@ -37,11 +52,14 @@ require_once(ROOT_DIR . "/helpers/user.php"); require_once(ROOT_DIR . "/helpers/utils.php"); $command = uUtils::postString("command"); +$language = uUtils::getString("lang", "en"); -$lang = (new uLang(uConfig::$lang))->getStrings(); -$langSetup = (new uLang(uConfig::$lang))->getSetupStrings(); +$config = uConfig::getOfflineInstance(); +$config->lang = $language; +$lang = (new uLang($config))->getStrings(); +$langSetup = (new uLang($config))->getSetupStrings(); -$prefix = preg_replace("/[^a-z0-9_]/i", "", uConfig::$dbprefix); +$prefix = preg_replace("/[^a-z0-9_]/i", "", $configPrefix); $tPositions = $prefix . "positions"; $tTracks = $prefix . "tracks"; $tUsers = $prefix . "users"; @@ -79,7 +97,7 @@ switch ($command) { if (!$error) { $messages[] = "{$langSetup["dbtablessuccess"]}"; $messages[] = $langSetup["setupuser"]; - $form = "
"; + $form = ""; $form .= ""; $form .= ""; $form .= ""; @@ -90,6 +108,7 @@ switch ($command) { break; case "adduser": + $config->save(); $login = uUtils::postString("login"); $pass = uUtils::postPass("pass"); @@ -104,43 +123,54 @@ switch ($command) { break; default: + $langsArr = uLang::getLanguages(); + $langsOpts = ""; + foreach ($langsArr as $langCode => $langName) { + $langsOpts .= ""; + } + $messages[] = "
+ + +
"; $messages[] = "\"µLogger\"" . $langSetup["welcome"]; if (!isset($enabled) || $enabled === false) { $messages[] = sprintf($langSetup["disabledwarn"], "\$enabled", "true"); $messages[] = sprintf($langSetup["lineshouldread"], "
\$enabled = false;
", "
\$enabled = true;"); $messages[] = $langSetup["dorestart"]; - $messages[] = "
"; + $messages[] = "
"; break; } - if (!uConfig::isFileLoaded()) { + if (!$dbConfigLoaded) { $messages[] = $langSetup["createconfig"]; $messages[] = $langSetup["dorestart"]; - $messages[] = "
"; + $messages[] = "
"; break; } if (ini_get("session.auto_start") === "1") { $messages[] = sprintf($langSetup["optionwarn"], "session.auto_start", "0 (off)"); $messages[] = $langSetup["dorestart"]; - $messages[] = "
"; + $messages[] = "
"; break; } if (!extension_loaded("pdo")) { $messages[] = sprintf($langSetup["extensionwarn"], "PDO"); $messages[] = $langSetup["dorestart"]; - $messages[] = "
"; + $messages[] = "
"; break; } - if (empty(uConfig::$dbdsn)) { + if (empty($configDSN)) { $messages[] = sprintf($langSetup["nodbsettings"], "\$dbdsn"); $messages[] = $langSetup["dorestart"]; - $messages[] = "
"; + $messages[] = "
"; break; } try { $pdo = getPdo(); } catch (PDOException $e) { - $isSqlite = stripos(uConfig::$dbdsn, "sqlite") === 0; - if (!$isSqlite && empty(uConfig::$dbuser)) { + $isSqlite = stripos($configDSN, "sqlite") === 0; + if (!$isSqlite && empty($configUser)) { $messages[] = sprintf($langSetup["nodbsettings"], "\$dbuser, \$dbpass"); } else { $messages[] = $langSetup["dbconnectfailed"]; @@ -148,15 +178,15 @@ switch ($command) { $messages[] = sprintf($langSetup["serversaid"], "" . htmlentities($e->getMessage()) . ""); } $messages[] = $langSetup["dorestart"]; - $messages[] = "
"; + $messages[] = "
"; break; } $pdo = null; - $dbName = uDb::getDbName(uConfig::$dbdsn); + $dbName = uDb::getDbName($configDSN); $dbName = empty($dbName) ? '""' : "" . htmlentities($dbName) . ""; $messages[] = sprintf($langSetup["scriptdesc"], "'$tPositions', '$tTracks', '$tUsers'", $dbName); $messages[] = $langSetup["scriptdesc2"]; - $messages[] = "
"; + $messages[] = "
"; break; } @@ -417,14 +447,15 @@ function getQueries($dbDriver) { * @throws PDOException */ function getPdo() { - $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]; - return new PDO(uConfig::$dbdsn, uConfig::$dbuser, uConfig::$dbpass, $options); + global $configDSN, $configUser, $configPass; + $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; + return new PDO($configDSN, $configUser, $configPass, $options); } ?> - + <?= $lang["title"] ?> @@ -455,6 +486,14 @@ function getPdo() { -webkit-border-radius: 5px; } + #language { + text-align: right; + } + + #language label { + font-size: small; + } + .warn { color: #ffc747; } @@ -466,7 +505,6 @@ function getPdo() { diff --git a/utils/changepass.php b/utils/changepass.php index b7c29f4..4452cad 100644 --- a/utils/changepass.php +++ b/utils/changepass.php @@ -17,44 +17,49 @@ * along with this program; if not, see . */ - require_once(dirname(__DIR__) . "/helpers/auth.php"); - require_once(ROOT_DIR . "/helpers/utils.php"); +require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(ROOT_DIR . "/helpers/config.php"); +require_once(ROOT_DIR . "/helpers/utils.php"); - $auth = new uAuth(); - if (!$auth->isAuthenticated()) { - $auth->sendUnauthorizedHeader(); - uUtils::exitWithError("Unauthorized"); - } +$auth = new uAuth(); +$config = uConfig::getInstance(); +if (!$auth->isAuthenticated()) { + $auth->sendUnauthorizedHeader(); + uUtils::exitWithError("Unauthorized"); +} - $login = uUtils::postString('login'); - $oldpass = uUtils::postPass('oldpass'); - $pass = uUtils::postPass('pass'); - // FIXME: strings need to be localized - if (empty($pass)) { - uUtils::exitWithError("Empty password"); +$login = uUtils::postString('login'); +$oldpass = uUtils::postPass('oldpass'); +$pass = uUtils::postPass('pass'); +// FIXME: strings need to be localized +if (empty($pass)) { + uUtils::exitWithError("Empty password"); +} +if (!$config->validPassStrength($pass)) { + uUtils::exitWithError("Invalid password strength"); +} +if (empty($login)) { + uUtils::exitWithError("Empty login"); +} +if ($auth->user->login === $login) { + // current user + $passUser = $auth->user; + if (!$passUser->validPassword($oldpass)) { + uUtils::exitWithError("Wrong old password"); } - if (empty($login)) { - uUtils::exitWithError("Empty login"); +} else if ($auth->isAdmin()) { + // different user, only admin + $passUser = new uUser($login); + if (!$passUser->isValid) { + uUtils::exitWithError("User unknown"); } - if ($auth->user->login === $login) { - // current user - $passUser = $auth->user; - if (!$passUser->validPassword($oldpass)) { - uUtils::exitWithError("Wrong old password"); - } - } else if ($auth->isAdmin()) { - // different user, only admin - $passUser = new uUser($login); - if (!$passUser->isValid) { - uUtils::exitWithError("User unknown"); - } - } else { - uUtils::exitWithError("Unauthorized"); - } - if ($passUser->setPass($pass) === false) { - uUtils::exitWithError("Server error"); - } - $auth->updateSession(); - uUtils::exitWithSuccess(); +} else { + uUtils::exitWithError("Unauthorized"); +} +if ($passUser->setPass($pass) === false) { + uUtils::exitWithError("Server error"); +} +$auth->updateSession(); +uUtils::exitWithSuccess(); ?> \ No newline at end of file diff --git a/utils/export.php b/utils/export.php index 9e78fb8..3c6a3b8 100644 --- a/utils/export.php +++ b/utils/export.php @@ -23,7 +23,8 @@ require_once(ROOT_DIR . "/helpers/lang.php"); require_once(ROOT_DIR . "/helpers/config.php"); $auth = new uAuth(); -$lang = (new uLang(uConfig::$lang))->getStrings(); +$config = uConfig::getInstance(); +$lang = (new uLang($config))->getStrings(); /** * Add kml marker style element @@ -62,13 +63,13 @@ $type = uUtils::getString('type', 'kml'); $userId = uUtils::getInt('userid'); $trackId = uUtils::getInt('trackid'); -if (!uConfig::$publicTracks && +if (!$config->publicTracks && (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $userId))) { // unauthorized exit(); } -if (uConfig::$units === "imperial") { +if ($config->units === "imperial") { $factor_kmh = 0.62; //to mph $unit_kmh = "mph"; $factor_m = 3.28; // to feet @@ -185,7 +186,7 @@ if ($trackId && $userId) { $xml->writeAttributeNs("xsi", "schemaLocation", NULL, "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd https://github.com/bfabiszewski/ulogger-android/1 https://raw.githubusercontent.com/bfabiszewski/ulogger-server/master/scripts/gpx_extensions1.xsd"); $xml->writeAttributeNs("xmlns", "xsi", NULL, "http://www.w3.org/2001/XMLSchema-instance"); $xml->writeAttributeNs("xmlns", "ulogger", NULL, "https://github.com/bfabiszewski/ulogger-android/1"); - $xml->writeAttribute("creator", "μlogger-server " . uConfig::$version); + $xml->writeAttribute("creator", "μlogger-server " . $config->version); $xml->writeAttribute("version", "1.1"); $xml->startElement("metadata"); $xml->writeElement("name", $positionsArr[0]->trackName); diff --git a/utils/getinit.php b/utils/getinit.php index 7f81cbe..edc1e2d 100644 --- a/utils/getinit.php +++ b/utils/getinit.php @@ -22,7 +22,8 @@ require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/lang.php"); $auth = new uAuth(); -$langStrings = (new uLang(uConfig::$lang))->getStrings(); +$config = uConfig::getInstance(); +$langStrings = (new uLang($config))->getStrings(); $result = []; $resultAuth = [ @@ -35,20 +36,20 @@ if ($auth->isAuthenticated()) { } $resultConfig = [ - "interval" => uConfig::$interval, - "units" => uConfig::$units, - "lang" => uConfig::$lang, - "mapApi" => uConfig::$mapApi, - "gkey" => uConfig::$googleKey, - "initLatitude" => uConfig::$initLatitude, - "initLongitude" => uConfig::$initLongitude, - "passRegex" => uConfig::passRegex(), - "strokeWeight" => uConfig::$strokeWeight, - "strokeColor" => uConfig::$strokeColor, - "strokeOpacity" => uConfig::$strokeOpacity, + "interval" => $config->interval, + "units" => $config->units, + "lang" => $config->lang, + "mapApi" => $config->mapApi, + "gkey" => $config->googleKey, + "initLatitude" => $config->initLatitude, + "initLongitude" => $config->initLongitude, + "passRegex" => $config->passRegex(), + "strokeWeight" => $config->strokeWeight, + "strokeColor" => $config->strokeColor, + "strokeOpacity" => $config->strokeOpacity, "olLayers" => [] ]; -foreach (uConfig::$olLayers as $key => $val) { +foreach ($config->olLayers as $key => $val) { $resultConfig["olLayers"][$key] = $val; } diff --git a/utils/getpositions.php b/utils/getpositions.php index e9d256a..cb80a18 100644 --- a/utils/getpositions.php +++ b/utils/getpositions.php @@ -18,10 +18,12 @@ */ require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/position.php"); require_once(ROOT_DIR . "/helpers/utils.php"); $auth = new uAuth(); +$config = uConfig::getInstance(); $userId = uUtils::getInt('userid'); $trackId = uUtils::getInt('trackid'); @@ -30,7 +32,7 @@ $last = uUtils::getBool('last'); $positionsArr = []; if ($userId) { - if (uConfig::$publicTracks || + if ($config->publicTracks || ($auth->isAuthenticated() && ($auth->isAdmin() || $auth->user->id === $userId))) { if ($trackId) { // get all track data @@ -44,7 +46,7 @@ if ($userId) { } } } else if ($last) { - if (uConfig::$publicTracks || ($auth->isAuthenticated() && ($auth->isAdmin()))) { + if ($config->publicTracks || ($auth->isAuthenticated() && ($auth->isAdmin()))) { $positionsArr = uPosition::getLastAllUsers(); } } diff --git a/utils/gettracks.php b/utils/gettracks.php index a197ade..4a7e8e2 100644 --- a/utils/gettracks.php +++ b/utils/gettracks.php @@ -18,15 +18,17 @@ */ require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/track.php"); $auth = new uAuth(); +$config = uConfig::getInstance(); $userId = uUtils::getInt('userid'); $tracksArr = []; if ($userId) { - if (uConfig::$publicTracks || + if ($config->publicTracks || ($auth->isAuthenticated() && ($auth->isAdmin() || $auth->user->id === $userId))) { $tracksArr = uTrack::getAll($userId); } diff --git a/utils/getusers.php b/utils/getusers.php index 25bcc96..2dc671f 100644 --- a/utils/getusers.php +++ b/utils/getusers.php @@ -19,12 +19,14 @@ */ require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/track.php"); $auth = new uAuth(); +$config = uConfig::getInstance(); $usersArr = []; -if (uConfig::$publicTracks || $auth->isAdmin()) { +if ($config->publicTracks || $auth->isAdmin()) { $usersArr = uUser::getAll(); } else if ($auth->isAuthenticated()) { $usersArr = [ $auth->user ]; diff --git a/utils/handleposition.php b/utils/handleposition.php index 19bbdae..69dd43e 100644 --- a/utils/handleposition.php +++ b/utils/handleposition.php @@ -17,49 +17,50 @@ * along with this program; if not, see . */ - require_once(dirname(__DIR__) . "/helpers/auth.php"); - require_once(ROOT_DIR . "/helpers/lang.php"); - require_once(ROOT_DIR . "/helpers/track.php"); - require_once(ROOT_DIR . "/helpers/utils.php"); - require_once(ROOT_DIR . "/helpers/config.php"); +require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(ROOT_DIR . "/helpers/lang.php"); +require_once(ROOT_DIR . "/helpers/track.php"); +require_once(ROOT_DIR . "/helpers/utils.php"); +require_once(ROOT_DIR . "/helpers/config.php"); - $auth = new uAuth(); +$auth = new uAuth(); - $action = uUtils::postString('action'); - $positionId = uUtils::postInt('posid'); - $comment = uUtils::postString('comment'); +$action = uUtils::postString('action'); +$positionId = uUtils::postInt('posid'); +$comment = uUtils::postString('comment'); - $lang = (new uLang(uConfig::$lang))->getStrings(); +$config = uConfig::getInstance(); +$lang = (new uLang($config))->getStrings(); - if (empty($action) || empty($positionId)) { - uUtils::exitWithError($lang["servererror"]); - } - $position = new uPosition($positionId); - if (!$position->isValid || - (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $position->userId))) { - uUtils::exitWithError($lang["servererror"]); - } +if (empty($action) || empty($positionId)) { + uUtils::exitWithError($lang["servererror"]); +} +$position = new uPosition($positionId); +if (!$position->isValid || + (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $position->userId))) { + uUtils::exitWithError($lang["servererror"]); +} - switch ($action) { +switch ($action) { - case 'update': - $position->comment = $comment; - if ($position->update() === false) { - uUtils::exitWithError($lang["servererror"]); - } - break; - - case 'delete': - if ($position->delete() === false) { - uUtils::exitWithError($lang["servererror"]); - } - break; - - default: + case 'update': + $position->comment = $comment; + if ($position->update() === false) { uUtils::exitWithError($lang["servererror"]); - break; - } + } + break; - uUtils::exitWithSuccess(); + case 'delete': + if ($position->delete() === false) { + uUtils::exitWithError($lang["servererror"]); + } + break; + + default: + uUtils::exitWithError($lang["servererror"]); + break; +} + +uUtils::exitWithSuccess(); ?> \ No newline at end of file diff --git a/utils/handletrack.php b/utils/handletrack.php index 908529b..b92c764 100644 --- a/utils/handletrack.php +++ b/utils/handletrack.php @@ -17,48 +17,49 @@ * along with this program; if not, see . */ - require_once(dirname(__DIR__) . "/helpers/auth.php"); - require_once(ROOT_DIR . "/helpers/lang.php"); - require_once(ROOT_DIR . "/helpers/track.php"); - require_once(ROOT_DIR . "/helpers/utils.php"); - require_once(ROOT_DIR . "/helpers/config.php"); +require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(ROOT_DIR . "/helpers/lang.php"); +require_once(ROOT_DIR . "/helpers/track.php"); +require_once(ROOT_DIR . "/helpers/utils.php"); +require_once(ROOT_DIR . "/helpers/config.php"); - $auth = new uAuth(); +$auth = new uAuth(); - $action = uUtils::postString('action'); - $trackId = uUtils::postInt('trackid'); - $trackName = uUtils::postString('trackname'); +$action = uUtils::postString('action'); +$trackId = uUtils::postInt('trackid'); +$trackName = uUtils::postString('trackname'); - $lang = (new uLang(uConfig::$lang))->getStrings(); +$config = uConfig::getInstance(); +$lang = (new uLang($config))->getStrings(); - if (empty($action) || empty($trackId)) { - uUtils::exitWithError($lang["servererror"]); - } - $track = new uTrack($trackId); - if (!$track->isValid || - (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $track->userId))) { - uUtils::exitWithError($lang["servererror"]); - } +if (empty($action) || empty($trackId)) { + uUtils::exitWithError($lang["servererror"]); +} +$track = new uTrack($trackId); +if (!$track->isValid || + (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $track->userId))) { + uUtils::exitWithError($lang["servererror"]); +} - switch ($action) { +switch ($action) { - case 'update': - if (empty($trackName) || $track->update($trackName) === false) { - uUtils::exitWithError($lang["servererror"]); - } - break; - - case 'delete': - if ($track->delete() === false) { - uUtils::exitWithError($lang["servererror"]); - } - break; - - default: + case 'update': + if (empty($trackName) || $track->update($trackName) === false) { uUtils::exitWithError($lang["servererror"]); - break; - } + } + break; - uUtils::exitWithSuccess(); + case 'delete': + if ($track->delete() === false) { + uUtils::exitWithError($lang["servererror"]); + } + break; + + default: + uUtils::exitWithError($lang["servererror"]); + break; +} + +uUtils::exitWithSuccess(); ?> \ No newline at end of file diff --git a/utils/handleuser.php b/utils/handleuser.php index 4cd8720..b6fd871 100644 --- a/utils/handleuser.php +++ b/utils/handleuser.php @@ -17,63 +17,64 @@ * along with this program; if not, see . */ - require_once(dirname(__DIR__) . "/helpers/auth.php"); - require_once(ROOT_DIR . "/helpers/lang.php"); - require_once(ROOT_DIR . "/helpers/config.php"); - require_once(ROOT_DIR . "/helpers/utils.php"); +require_once(dirname(__DIR__) . "/helpers/auth.php"); +require_once(ROOT_DIR . "/helpers/lang.php"); +require_once(ROOT_DIR . "/helpers/config.php"); +require_once(ROOT_DIR . "/helpers/utils.php"); - $auth = new uAuth(); +$auth = new uAuth(); +$config = uConfig::getInstance(); - $action = uUtils::postString('action'); - $login = uUtils::postString('login'); - $pass = uUtils::postPass('pass'); - $admin = uUtils::postBool('admin', false); +$action = uUtils::postString('action'); +$login = uUtils::postString('login'); +$pass = uUtils::postPass('pass'); +$admin = uUtils::postBool('admin', false); - $lang = (new uLang(uConfig::$lang))->getStrings(); +$lang = (new uLang($config))->getStrings(); - if (!$auth->isAuthenticated() || !$auth->isAdmin() || $auth->user->login === $login || empty($action) || empty($login)) { - uUtils::exitWithError($lang["servererror"]); - } +if ($auth->user->login === $login || empty($action) || empty($login) || !$auth->isAuthenticated() || !$auth->isAdmin()) { + uUtils::exitWithError($lang["servererror"]); +} - if ($admin && !$auth->isAdmin()) { - uUtils::exitWithError($lang["notauthorized"]); - } +if ($admin && !$auth->isAdmin()) { + uUtils::exitWithError($lang["notauthorized"]); +} - $aUser = new uUser($login); - $data = NULL; +$aUser = new uUser($login); +$data = NULL; - switch ($action) { - case 'add': - if ($aUser->isValid) { - uUtils::exitWithError($lang["userexists"]); - } - if (empty($pass) || ($userId = uUser::add($login, $pass, $admin)) === false) { - uUtils::exitWithError($lang["servererror"]); - } else { - $data = [ 'id' => $userId ]; - } - break; - - case 'update': - if ($aUser->setAdmin($admin) === false) { - uUtils::exitWithError($lang["servererror"]); - } - if (!empty($pass) && $aUser->setPass($pass) === false) { - uUtils::exitWithError($lang["servererror"]); - } - break; - - case 'delete': - if ($aUser->delete() === false) { - uUtils::exitWithError($lang["servererror"]); - } - break; - - default: +switch ($action) { + case 'add': + if ($aUser->isValid) { + uUtils::exitWithError($lang["userexists"]); + } + if (empty($pass) || !$config->validPassStrength($pass) || ($userId = uUser::add($login, $pass, $admin)) === false) { uUtils::exitWithError($lang["servererror"]); - break; - } + } else { + $data = [ 'id' => $userId ]; + } + break; - uUtils::exitWithSuccess($data); + case 'update': + if ($aUser->setAdmin($admin) === false) { + uUtils::exitWithError($lang["servererror"]); + } + if (!empty($pass) && (!$config->validPassStrength($pass) || $aUser->setPass($pass) === false)) { + uUtils::exitWithError($lang["servererror"]); + } + break; + + case 'delete': + if ($aUser->delete() === false) { + uUtils::exitWithError($lang["servererror"]); + } + break; + + default: + uUtils::exitWithError($lang["servererror"]); + break; +} + +uUtils::exitWithSuccess($data); ?> \ No newline at end of file diff --git a/utils/import.php b/utils/import.php index 737f999..8dffe8c 100644 --- a/utils/import.php +++ b/utils/import.php @@ -26,7 +26,8 @@ require_once(ROOT_DIR . "/helpers/lang.php"); $auth = new uAuth(); -$lang = (new uLang(uConfig::$lang))->getStrings(); +$config = uConfig::getInstance(); +$lang = (new uLang($config))->getStrings(); $uploadErrors = []; $uploadErrors[UPLOAD_ERR_INI_SIZE] = "The uploaded file exceeds the upload_max_filesize directive in php.ini";