Refactor config class

This commit is contained in:
Bartek Fabiszewski 2020-02-20 17:08:47 +01:00
parent 652655a90f
commit 33afc33405
25 changed files with 731 additions and 523 deletions

View File

@ -1,6 +1,7 @@
<?php <?php
if (!defined("ROOT_DIR")) { define("ROOT_DIR", __DIR__ . "/../.."); } if (!defined("ROOT_DIR")) { define("ROOT_DIR", __DIR__ . "/../.."); }
require_once(__DIR__ . "/../../helpers/config.php");
abstract class BaseDatabaseTestCase extends PHPUnit_Extensions_Database_TestCase { abstract class BaseDatabaseTestCase extends PHPUnit_Extensions_Database_TestCase {
@ -14,6 +15,8 @@ abstract class BaseDatabaseTestCase extends PHPUnit_Extensions_Database_TestCase
private $conn; private $conn;
static private $driver = "mysql"; static private $driver = "mysql";
protected $mockConfig;
protected $testUser = "testUser"; protected $testUser = "testUser";
protected $testUser2 = "testUser2"; protected $testUser2 = "testUser2";
protected $testAdminUser = "admin"; protected $testAdminUser = "admin";
@ -44,6 +47,7 @@ abstract class BaseDatabaseTestCase extends PHPUnit_Extensions_Database_TestCase
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->mockConfig = new uConfig(false);
} }
public static function setUpBeforeClass() { public static function setUpBeforeClass() {

View File

@ -6,6 +6,8 @@ require_once(__DIR__ . "/../lib/UloggerDatabaseTestCase.php");
class ConfigTest extends UloggerDatabaseTestCase { class ConfigTest extends UloggerDatabaseTestCase {
private $config;
private $mapApi; private $mapApi;
private $latitude; private $latitude;
private $longitude; private $longitude;
@ -26,6 +28,7 @@ class ConfigTest extends UloggerDatabaseTestCase {
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->config = uConfig::getInstance();
$this->initConfigValues(); $this->initConfigValues();
} }
@ -60,25 +63,75 @@ class ConfigTest extends UloggerDatabaseTestCase {
} }
public function testSetFromDatabase() { public function testSetFromDatabase() {
uConfig::setFromDatabase(); $this->assertEquals($this->mapApi, $this->config->mapApi);
$this->assertEquals($this->mapApi, uConfig::$mapApi); $this->assertEquals($this->latitude, $this->config->initLatitude);
$this->assertEquals($this->latitude, uConfig::$initLatitude); $this->assertEquals($this->longitude, $this->config->initLongitude);
$this->assertEquals($this->longitude, uConfig::$initLongitude); $this->assertEquals($this->googleKey, $this->config->googleKey);
$this->assertEquals($this->googleKey, uConfig::$googleKey); $this->assertEquals($this->requireAuth, $this->config->requireAuthentication);
$this->assertEquals($this->requireAuth, uConfig::$requireAuthentication); $this->assertEquals($this->publicTracks, $this->config->publicTracks);
$this->assertEquals($this->publicTracks, uConfig::$publicTracks); $this->assertEquals($this->passLenMin, $this->config->passLenMin);
$this->assertEquals($this->passLenMin, uConfig::$passLenMin); $this->assertEquals($this->passStrength, $this->config->passStrength);
$this->assertEquals($this->passStrength, uConfig::$passStrength); $this->assertEquals($this->interval, $this->config->interval);
$this->assertEquals($this->interval, uConfig::$interval); $this->assertEquals($this->lang, $this->config->lang);
$this->assertEquals($this->lang, uConfig::$lang); $this->assertEquals($this->units, $this->config->units);
$this->assertEquals($this->units, uConfig::$units); $this->assertEquals($this->strokeWeight, $this->config->strokeWeight);
$this->assertEquals($this->strokeWeight, uConfig::$strokeWeight); $this->assertEquals($this->strokeColor, $this->config->strokeColor);
$this->assertEquals($this->strokeColor, uConfig::$strokeColor); $this->assertEquals($this->strokeOpacity, $this->config->strokeOpacity);
$this->assertEquals($this->strokeOpacity, uConfig::$strokeOpacity);
$this->assertEquals($this->testLayer, uConfig::$olLayers[0]->name); $this->assertEquals($this->testLayer, $this->config->olLayers[0]->name);
$this->assertEquals($this->testUrl, uConfig::$olLayers[0]->url); $this->assertEquals($this->testUrl, $this->config->olLayers[0]->url);
$this->assertEquals($this->testPriority, uConfig::$olLayers[0]->priority); $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() { private function initConfigValues() {
@ -102,35 +155,35 @@ class ConfigTest extends UloggerDatabaseTestCase {
} }
public function testPassRegex() { public function testPassRegex() {
uConfig::$passLenMin = 0; $this->config->passLenMin = 0;
uConfig::$passStrength = 0; $this->config->passStrength = 0;
$password0 = "password"; $password0 = "password";
$password1 = "PASSword"; $password1 = "PASSword";
$password2 = "PASSword1234"; $password2 = "PASSword1234";
$password3 = "PASSword1234-;"; $password3 = "PASSword1234-;";
$regex = uConfig::passRegex(); $regex = $this->config->passRegex();
$this->assertRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\"");
$this->assertRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\"");
$this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); $this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\"");
$this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\""); $this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\"");
uConfig::$passStrength = 1; $this->config->passStrength = 1;
$regex = uConfig::passRegex(); $regex = $this->config->passRegex();
$this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\"");
$this->assertRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\"");
$this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); $this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\"");
$this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\""); $this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\"");
uConfig::$passStrength = 2; $this->config->passStrength = 2;
$regex = uConfig::passRegex(); $regex = $this->config->passRegex();
$this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\"");
$this->assertNotRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertNotRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\"");
$this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); $this->assertRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\"");
$this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\""); $this->assertRegExp($regex, $password3, "Regex: \"$regex\", password: \"$password3\"");
uConfig::$passStrength = 3; $this->config->passStrength = 3;
$regex = uConfig::passRegex(); $regex = $this->config->passRegex();
$this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\""); $this->assertNotRegExp($regex, $password0, "Regex: \"$regex\", password: \"$password0\"");
$this->assertNotRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\""); $this->assertNotRegExp($regex, $password1, "Regex: \"$regex\", password: \"$password1\"");
$this->assertNotRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\""); $this->assertNotRegExp($regex, $password2, "Regex: \"$regex\", password: \"$password2\"");
@ -138,19 +191,19 @@ class ConfigTest extends UloggerDatabaseTestCase {
$password_len5 = "12345"; $password_len5 = "12345";
$password_len10 = "1234567890"; $password_len10 = "1234567890";
uConfig::$passLenMin = 5; $this->config->passLenMin = 5;
uConfig::$passStrength = 0; $this->config->passStrength = 0;
$regex = uConfig::passRegex(); $regex = $this->config->passRegex();
$this->assertRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\""); $this->assertRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\"");
$this->assertRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\""); $this->assertRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\"");
uConfig::$passLenMin = 7; $this->config->passLenMin = 7;
$regex = uConfig::passRegex(); $regex = $this->config->passRegex();
$this->assertNotRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\""); $this->assertNotRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\"");
$this->assertRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\""); $this->assertRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\"");
uConfig::$passLenMin = 12; $this->config->passLenMin = 12;
$regex = uConfig::passRegex(); $regex = $this->config->passRegex();
$this->assertNotRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\""); $this->assertNotRegExp($regex, $password_len5, "Regex: \"$regex\", password: \"$password_len5\"");
$this->assertNotRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\""); $this->assertNotRegExp($regex, $password_len10, "Regex: \"$regex\", password: \"$password_len10\"");
} }

View File

@ -626,7 +626,7 @@ class ImportTest extends UloggerAPITestCase {
} }
public function testImportNoLongitude() { public function testImportNoLongitude() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count");
@ -673,7 +673,7 @@ class ImportTest extends UloggerAPITestCase {
} }
public function testImportNoLatitude() { public function testImportNoLatitude() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count");
@ -720,7 +720,7 @@ class ImportTest extends UloggerAPITestCase {
} }
public function testImportNoGPX() { public function testImportNoGPX() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count");
@ -761,7 +761,7 @@ class ImportTest extends UloggerAPITestCase {
} }
public function testImportCorrupt() { public function testImportCorrupt() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count"); $this->assertEquals(0, $this->getConnection()->getRowCount("tracks"), "Wrong row count");

View File

@ -666,7 +666,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleTrackDeleteOtherUser() { 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->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT));
$this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count");
$this->assertTrue($this->authenticate($this->testUser, $this->testPass), "Authentication failed"); $this->assertTrue($this->authenticate($this->testUser, $this->testPass), "Authentication failed");
@ -728,7 +728,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleTrackUpdateEmptyName() { public function testHandleTrackUpdateEmptyName() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$userId = $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $userId = $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT));
$this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count");
@ -752,7 +752,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleTrackUpdateNonexistantTrack() { public function testHandleTrackUpdateNonexistantTrack() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$newName = "New name"; $newName = "New name";
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$userId = $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $userId = $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT));
@ -776,7 +776,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleTrackMissingAction() { public function testHandleTrackMissingAction() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$options = [ $options = [
@ -794,7 +794,7 @@ class InternalAPITest extends UloggerAPITestCase {
/* handleuser.php */ /* handleuser.php */
public function testHandleUserMissingAction() { public function testHandleUserMissingAction() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$options = [ $options = [
@ -809,7 +809,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleUserNonAdmin() { 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->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT));
$this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count");
$this->assertTrue($this->authenticate($this->testUser, $this->testPass), "Authentication failed"); $this->assertTrue($this->authenticate($this->testUser, $this->testPass), "Authentication failed");
@ -829,7 +829,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleUserSelf() { public function testHandleUserSelf() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$this->assertEquals(1, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertEquals(1, $this->getConnection()->getRowCount("users"), "Wrong row count");
@ -847,7 +847,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleUserEmptyLogin() { public function testHandleUserEmptyLogin() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$this->assertEquals(1, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertEquals(1, $this->getConnection()->getRowCount("users"), "Wrong row count");
@ -865,7 +865,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleUserNoAuth() { 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->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT));
$this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count");
@ -908,7 +908,7 @@ class InternalAPITest extends UloggerAPITestCase {
} }
public function testHandleUserAddSameLogin() { public function testHandleUserAddSameLogin() {
$lang = (new uLang("en"))->getStrings(); $lang = (new uLang($this->mockConfig))->getStrings();
$this->assertTrue($this->authenticate(), "Authentication failed"); $this->assertTrue($this->authenticate(), "Authentication failed");
$this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT)); $this->addTestUser($this->testUser, password_hash($this->testPass, PASSWORD_DEFAULT));
$this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count"); $this->assertEquals(2, $this->getConnection()->getRowCount("users"), "Wrong row count");

View File

@ -1,11 +1,20 @@
<?php <?php
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
if (!defined("ROOT_DIR")) { define("ROOT_DIR", __DIR__ . "/../.."); }
require_once(__DIR__ . "/../../helpers/config.php"); require_once(__DIR__ . "/../../helpers/config.php");
require_once(__DIR__ . "/../../helpers/lang.php"); require_once(__DIR__ . "/../../helpers/lang.php");
class LangTest extends TestCase { class LangTest extends TestCase {
protected $mockConfig;
public function setUp() {
parent::setUp();
$this->mockConfig = new uConfig(false);
}
public function testGetLanguages() { public function testGetLanguages() {
$languages = uLang::getLanguages(); $languages = uLang::getLanguages();
$this->assertNotEmpty($languages); $this->assertNotEmpty($languages);
@ -16,16 +25,18 @@ class LangTest extends TestCase {
} }
public function testGetStrings() { public function testGetStrings() {
$lang = new uLang("en"); $lang = new uLang($this->mockConfig);
$this->assertEquals("User", $lang->getStrings()["user"]); $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"]); $this->assertEquals("Użytkownik", $lang->getStrings()["user"]);
} }
public function testGetSetupStrings() { public function testGetSetupStrings() {
$lang = new uLang("en"); $lang = new uLang($this->mockConfig);
$this->assertEquals("Congratulations!", $lang->getSetupStrings()["congratulations"]); $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"]); $this->assertEquals("Gratulacje!", $lang->getSetupStrings()["congratulations"]);
} }
} }

View File

@ -17,125 +17,125 @@
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
/** /**
* Exit with error status and message * Exit with error status and message
* *
* @param string $message Message * @param string $message Message
*/ */
function exitWithError($message) { function exitWithError($message) {
$response = []; $response = [];
$response['error'] = true; $response['error'] = true;
$response['message'] = $message; $response['message'] = $message;
header('Content-Type: application/json'); header('Content-Type: application/json');
echo json_encode($response); echo json_encode($response);
exit(); exit();
} }
/** /**
* Exit with success status * Exit with success status
* *
* @param array $params Optional params * @param array $params Optional params
* @return void * @return void
*/ */
function exitWithSuccess($params = []) { function exitWithSuccess($params = []) {
$response = []; $response = [];
$response['error'] = false; $response['error'] = false;
header('Content-Type: application/json'); header('Content-Type: application/json');
echo json_encode(array_merge($response, $params)); echo json_encode(array_merge($response, $params));
exit(); 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(); $auth = new uAuth();
if (!$auth->isAuthenticated() && $action != "auth") { if ($action !== "auth" && !$auth->isAuthenticated()) {
$auth->sendUnauthorizedHeader(); $auth->sendUnauthorizedHeader();
exitWithError("Unauthorized"); exitWithError("Unauthorized");
} }
switch ($action) { switch ($action) {
// action: authorize // action: authorize
case "auth": case "auth":
$login = uUtils::postString('user'); $login = uUtils::postString('user');
$pass = uUtils::postPass('pass'); $pass = uUtils::postPass('pass');
if ($auth->checkLogin($login, $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");
}
exitWithSuccess(); exitWithSuccess();
break; } else {
$auth->sendUnauthorizedHeader();
exitWithError("Unauthorized");
}
break;
default: // action: adduser (currently unused)
exitWithError("Unknown command"); case "adduser":
break; 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;
}
?> ?>

View File

@ -30,12 +30,12 @@
/** @var bool Is user authenticated */ /** @var bool Is user authenticated */
private $isAuthenticated = false; private $isAuthenticated = false;
/** @var null|uUser */ /** @var null|uUser */
public $user = null; public $user;
public function __construct() { public function __construct() {
$this->sessionStart(); $this->sessionStart();
$user = (new uUser())->getFromSession(); $user = uUser::getFromSession();
if ($user->isValid) { if ($user->isValid) {
$this->setAuthenticated($user); $this->setAuthenticated($user);
} }

View File

@ -20,75 +20,60 @@
require_once(ROOT_DIR . "/helpers/db.php"); require_once(ROOT_DIR . "/helpers/db.php");
require_once(ROOT_DIR . "/helpers/layer.php"); require_once(ROOT_DIR . "/helpers/layer.php");
/**
* Initialize on file include
*/
uConfig::init();
/** /**
* Handles config values * Handles config values
*/ */
class uConfig { class uConfig {
/**
* Singleton instance
*
* @var uConfig Object instance
*/
private static $instance;
/** /**
* @var string Version number * @var string Version number
*/ */
public static $version = "1.0-beta"; public $version = "1.0-beta";
/** /**
* @var string Default map drawing framework * @var string Default map drawing framework
*/ */
public static $mapApi = "openlayers"; public $mapApi = "openlayers";
/** /**
* @var string|null Google maps key * @var string|null Google maps key
*/ */
public static $googleKey; public $googleKey;
/** /**
* @var uLayer[] Openlayers extra map layers * @var uLayer[] Openlayers extra map layers
*/ */
public static $olLayers = []; public $olLayers = [];
/** /**
* @var float Default latitude for initial map * @var float Default latitude for initial map
*/ */
public static $initLatitude = 52.23; public $initLatitude = 52.23;
/** /**
* @var float Default longitude for initial map * @var float Default longitude for initial map
*/ */
public static $initLongitude = 21.01; public $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 = "";
/** /**
* @var bool Require login/password authentication * @var bool Require login/password authentication
*/ */
public static $requireAuthentication = true; public $requireAuthentication = true;
/** /**
* @var bool All users tracks are visible to authenticated user * @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 * @var int Miniumum required length of user password
*/ */
public static $passLenMin = 10; public $passLenMin = 10;
/** /**
* @var int Required strength of user password * @var int Required strength of user password
@ -97,49 +82,65 @@ class uConfig {
* 2 = require mixed case and numbers * 2 = require mixed case and numbers
* 3 = require mixed case, numbers and non-alphanumeric characters * 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 * @var int Default interval in seconds for live auto reload
*/ */
public static $interval = 10; public $interval = 10;
/** /**
* @var string Default language code * @var string Default language code
*/ */
public static $lang = "en"; public $lang = "en";
/** /**
* @var string Default units * @var string Default units
*/ */
public static $units = "metric"; public $units = "metric";
/** /**
* @var int Stroke weight * @var int Stroke weight
*/ */
public static $strokeWeight = 2; public $strokeWeight = 2;
/** /**
* @var string Stroke color * @var string Stroke color
*/ */
public static $strokeColor = '#ff0000'; public $strokeColor = '#ff0000';
/** /**
* @var int Stroke opacity * @var float Stroke opacity
*/ */
public static $strokeOpacity = 1; public $strokeOpacity = 1.0;
private static $fileLoaded = false; public function __construct($useDatabase = true) {
private static $initialized = false; if ($useDatabase) {
$this->setFromDatabase();
/**
* Static initializer
*/
public static function init() {
if (!self::$initialized) {
self::setFromFile();
self::setFromDatabase();
self::setFromCookies();
self::$initialized = true;
} }
$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 * Read config values from database
*/ */
public static function setFromDatabase() { public function setFromDatabase() {
try { try {
$query = "SELECT map_api, latitude, longitude, google_key, require_auth, public_tracks, $query = "SELECT map_api, latitude, longitude, google_key, require_auth, public_tracks,
pass_lenmin, pass_strength, interval_seconds, lang, units, pass_lenmin, pass_strength, interval_seconds, lang, units,
@ -163,30 +164,91 @@ class uConfig {
$result = self::db()->query($query); $result = self::db()->query($query);
$row = $result->fetch(); $row = $result->fetch();
if ($row) { if ($row) {
if (!empty($row['map_api'])) { self::$mapApi = $row['map_api']; } if (!empty($row['map_api'])) { $this->mapApi = $row['map_api']; }
if (is_numeric($row['latitude'])) { self::$initLatitude = $row['latitude']; } if (is_numeric($row['latitude'])) { $this->initLatitude = (float) $row['latitude']; }
if (is_numeric($row['longitude'])) { self::$initLongitude = $row['longitude']; } if (is_numeric($row['longitude'])) { $this->initLongitude = (float) $row['longitude']; }
if (!empty($row['google_key'])) { self::$googleKey = $row['google_key']; } if (!empty($row['google_key'])) { $this->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['require_auth']) || is_bool($row['require_auth'])) { $this->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['public_tracks']) || is_bool($row['public_tracks'])) { $this->publicTracks = (bool) $row['public_tracks']; }
if (is_numeric($row['pass_lenmin'])) { self::$passLenMin = $row['pass_lenmin']; } if (is_numeric($row['pass_lenmin'])) { $this->passLenMin = (int) $row['pass_lenmin']; }
if (is_numeric($row['pass_strength'])) { self::$passStrength = $row['pass_strength']; } if (is_numeric($row['pass_strength'])) { $this->passStrength = (int) $row['pass_strength']; }
if (is_numeric($row['interval_seconds'])) { self::$interval = $row['interval_seconds']; } if (is_numeric($row['interval_seconds'])) { $this->interval = (int) $row['interval_seconds']; }
if (!empty($row['lang'])) { self::$lang = $row['lang']; } if (!empty($row['lang'])) { $this->lang = $row['lang']; }
if (!empty($row['units'])) { self::$units = $row['units']; } if (!empty($row['units'])) { $this->units = $row['units']; }
if (is_numeric($row['stroke_weight'])) { self::$strokeWeight = $row['stroke_weight']; } if (is_numeric($row['stroke_weight'])) { $this->strokeWeight = (int) $row['stroke_weight']; }
if (is_numeric($row['stroke_color'])) { self::$strokeColor = self::getColorAsHex($row['stroke_color']); } if (is_numeric($row['stroke_color'])) { $this->strokeColor = self::getColorAsHex($row['stroke_color']); }
if (is_numeric($row['stroke_opacity'])) { self::$strokeOpacity = $row['stroke_opacity'] / 100; } if (is_numeric($row['stroke_opacity'])) { $this->strokeOpacity = $row['stroke_opacity'] / 100; }
} }
self::setLayersFromDatabase(); $this->setLayersFromDatabase();
if (!self::$requireAuthentication) { if (!$this->requireAuthentication) {
// tracks must be public if we don't require authentication // tracks must be public if we don't require authentication
self::$publicTracks = true; $this->publicTracks = true;
} }
} catch (PDOException $e) { } catch (PDOException $e) {
// TODO: handle exception // TODO: handle exception
syslog(LOG_ERR, $e->getMessage()); 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 * Read config values from database
* @throws PDOException * @throws PDOException
*/ */
private static function setLayersFromDatabase() { private function setLayersFromDatabase() {
self::$olLayers = []; $this->olLayers = [];
$query = "SELECT id, name, url, priority FROM " . self::db()->table('ol_layers'); $query = "SELECT id, name, url, priority FROM " . self::db()->table('ol_layers');
$result = self::db()->query($query); $result = self::db()->query($query);
while ($row = $result->fetch()) { 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 * Read config values stored in cookies
*/ */
private static function setFromCookies() { private function setFromCookies() {
if (isset($_COOKIE["ulogger_api"])) { self::$mapApi = $_COOKIE["ulogger_api"]; } if (isset($_COOKIE["ulogger_api"])) { $this->mapApi = $_COOKIE["ulogger_api"]; }
if (isset($_COOKIE["ulogger_lang"])) { self::$lang = $_COOKIE["ulogger_lang"]; } if (isset($_COOKIE["ulogger_lang"])) { $this->lang = $_COOKIE["ulogger_lang"]; }
if (isset($_COOKIE["ulogger_units"])) { self::$units = $_COOKIE["ulogger_units"]; } if (isset($_COOKIE["ulogger_units"])) { $this->units = $_COOKIE["ulogger_units"]; }
if (isset($_COOKIE["ulogger_interval"])) { self::$interval = $_COOKIE["ulogger_interval"]; } 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() { public function validPassStrength($password) {
return self::$fileLoaded; return preg_match($this->passRegex(), $password);
} }
/** /**
@ -245,22 +291,22 @@ class uConfig {
* Valid for both php and javascript * Valid for both php and javascript
* @return string * @return string
*/ */
public static function passRegex() { public function passRegex() {
$regex = ""; $regex = "";
if (self::$passStrength > 0) { if ($this->passStrength > 0) {
// lower and upper case // lower and upper case
$regex .= "(?=.*[a-z])(?=.*[A-Z])"; $regex .= "(?=.*[a-z])(?=.*[A-Z])";
} }
if (self::$passStrength > 1) { if ($this->passStrength > 1) {
// digits // digits
$regex .= "(?=.*[0-9])"; $regex .= "(?=.*[0-9])";
} }
if (self::$passStrength > 2) { if ($this->passStrength > 2) {
// not latin, not digits // not latin, not digits
$regex .= "(?=.*[^a-zA-Z0-9])"; $regex .= "(?=.*[^a-zA-Z0-9])";
} }
if (self::$passLenMin > 0) { if ($this->passLenMin > 0) {
$regex .= "(?=.{" . self::$passLenMin . ",})"; $regex .= "(?=.{" . $this->passLenMin . ",})";
} }
if (empty($regex)) { if (empty($regex)) {
$regex = ".*"; $regex = ".*";

View File

@ -17,8 +17,6 @@
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
require_once(ROOT_DIR . "/helpers/config.php");
/** /**
* PDO wrapper * PDO wrapper
*/ */
@ -44,6 +42,23 @@
*/ */
protected static $driver; 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 * PDO constuctor
* *
@ -73,7 +88,7 @@
*/ */
private function initTables() { private function initTables() {
self::$tables = []; 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['positions'] = $prefix . "positions";
self::$tables['tracks'] = $prefix . "tracks"; self::$tables['tracks'] = $prefix . "tracks";
self::$tables['users'] = $prefix . "users"; self::$tables['users'] = $prefix . "users";
@ -88,12 +103,39 @@
*/ */
public static function getInstance() { public static function getInstance() {
if (!self::$instance) { 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; 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 * Get full table name including prefix
* *
* @param string $name Name * @param string $name Name

View File

@ -61,9 +61,10 @@
/** /**
* Constructor * Constructor
* *
* @param string $language Language code (IANA) * @param uConfig $config Config
*/ */
public function __construct($language = "en") { public function __construct($config) {
$language = $config->lang;
$lang = []; $lang = [];
$langSetup = []; $langSetup = [];
// always load en base // always load en base
@ -76,9 +77,9 @@
} }
// choose password messages based on config // choose password messages based on config
$passRules = "passrules_" . uConfig::$passStrength; $passRules = "passrules_" . $config->passStrength;
$lang['passrules'] = isset($lang[$passRules]) ? $lang[$passRules] : ""; $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->strings = $lang;
$this->setupStrings = $langSetup; $this->setupStrings = $langSetup;
} }

View File

@ -16,7 +16,6 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/db.php"); require_once(ROOT_DIR . "/helpers/db.php");
require_once(ROOT_DIR . "/helpers/track.php"); require_once(ROOT_DIR . "/helpers/track.php");
require_once(ROOT_DIR . "/helpers/position.php"); require_once(ROOT_DIR . "/helpers/position.php");
@ -75,7 +74,7 @@
*/ */
public static function add($login, $pass, $isAdmin = false) { public static function add($login, $pass, $isAdmin = false) {
$userid = false; $userid = false;
if (!empty($login) && !empty($pass) && self::validPassStrength($pass)) { if (!empty($login) && !empty($pass)) {
$hash = password_hash($pass, PASSWORD_DEFAULT); $hash = password_hash($pass, PASSWORD_DEFAULT);
$table = self::db()->table('users'); $table = self::db()->table('users');
try { try {
@ -152,7 +151,7 @@
*/ */
public function setPass($pass) { public function setPass($pass) {
$ret = false; $ret = false;
if (!empty($this->login) && !empty($pass) && self::validPassStrength($pass)) { if (!empty($this->login) && !empty($pass)) {
$hash = password_hash($pass, PASSWORD_DEFAULT); $hash = password_hash($pass, PASSWORD_DEFAULT);
try { try {
$query = "UPDATE " . self::db()->table('users') . " SET password = ? WHERE login = ?"; $query = "UPDATE " . self::db()->table('users') . " SET password = ? WHERE login = ?";
@ -178,16 +177,6 @@
return password_verify($password, $this->hash); 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 * Store uUser object in session
*/ */
@ -199,16 +188,17 @@
* Fill uUser object properties from session data * Fill uUser object properties from session data
* @return uUser * @return uUser
*/ */
public function getFromSession() { public static function getFromSession() {
$user = new uUser();
if (isset($_SESSION['user'])) { if (isset($_SESSION['user'])) {
$sessionUser = $_SESSION['user']; $sessionUser = $_SESSION['user'];
$this->id = $sessionUser->id; $user->id = $sessionUser->id;
$this->login = $sessionUser->login; $user->login = $sessionUser->login;
$this->hash = $sessionUser->hash; $user->hash = $sessionUser->hash;
$this->isAdmin = $sessionUser->isAdmin; $user->isAdmin = $sessionUser->isAdmin;
$this->isValid = $sessionUser->isValid; $user->isValid = $sessionUser->isValid;
} }
return $this; return $user;
} }
/** /**

View File

@ -28,7 +28,8 @@
$pass = uUtils::postPass('pass'); $pass = uUtils::postPass('pass');
$action = uUtils::postString('action'); $action = uUtils::postString('action');
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$lang = (new uLang($config))->getStrings();
$langsArr = uLang::getLanguages(); $langsArr = uLang::getLanguages();
$auth = new uAuth(); $auth = new uAuth();
@ -39,13 +40,13 @@
if ($action === 'auth' && !$auth->isAuthenticated()) { if ($action === 'auth' && !$auth->isAuthenticated()) {
$auth->exitWithRedirect('login.php?auth_error=1'); $auth->exitWithRedirect('login.php?auth_error=1');
} }
if (uConfig::$requireAuthentication && !$auth->isAuthenticated()) { if ($config->requireAuthentication && !$auth->isAuthenticated()) {
$auth->exitWithRedirect('login.php'); $auth->exitWithRedirect('login.php');
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="<?= uConfig::$lang ?>"> <html lang="<?= $config->lang ?>">
<head> <head>
<title><?= $lang['title'] ?></title> <title><?= $lang['title'] ?></title>
<?php include('meta.php'); ?> <?php include('meta.php'); ?>
@ -78,7 +79,7 @@
<label for="track"><?= $lang['track'] ?></label> <label for="track"><?= $lang['track'] ?></label>
<select id="track" data-bind="currentTrackId" name="track"></select> <select id="track" data-bind="currentTrackId" name="track"></select>
<input id="latest" type="checkbox" data-bind="showLatest"> <label for="latest"><?= $lang['latest'] ?></label><br> <input id="latest" type="checkbox" data-bind="showLatest"> <label for="latest"><?= $lang['latest'] ?></label><br>
<input id="auto-reload" type="checkbox" data-bind="autoReload"> <label for="auto-reload"><?= $lang['autoreload'] ?></label> (<a id="set-interval" data-bind="onSetInterval"><span id="interval" data-bind="interval"><?= uConfig::$interval ?></span></a> s)<br> <input id="auto-reload" type="checkbox" data-bind="autoReload"> <label for="auto-reload"><?= $lang['autoreload'] ?></label> (<a id="set-interval" data-bind="onSetInterval"><span id="interval" data-bind="interval"><?= $config->interval ?></span></a> s)<br>
<a id="force-reload" data-bind="onReload"> <?= $lang['reload'] ?></a><br> <a id="force-reload" data-bind="onReload"> <?= $lang['reload'] ?></a><br>
</div> </div>
@ -91,8 +92,8 @@
<div> <div>
<label for="api"><?= $lang['api'] ?></label> <label for="api"><?= $lang['api'] ?></label>
<select id="api" name="api" data-bind="mapApi"> <select id="api" name="api" data-bind="mapApi">
<option value="gmaps"<?= (uConfig::$mapApi === 'gmaps') ? ' selected' : '' ?>>Google Maps</option> <option value="gmaps"<?= ($config->mapApi === 'gmaps') ? ' selected' : '' ?>>Google Maps</option>
<option value="openlayers"<?= (uConfig::$mapApi === 'openlayers') ? ' selected' : '' ?>>OpenLayers</option> <option value="openlayers"<?= ($config->mapApi === 'openlayers') ? ' selected' : '' ?>>OpenLayers</option>
</select> </select>
</div> </div>
@ -100,7 +101,7 @@
<label for="lang"><?= $lang['language'] ?></label> <label for="lang"><?= $lang['language'] ?></label>
<select id="lang" name="lang" data-bind="lang"> <select id="lang" name="lang" data-bind="lang">
<?php foreach ($langsArr as $langCode => $langName): ?> <?php foreach ($langsArr as $langCode => $langName): ?>
<option value="<?= $langCode ?>"<?= (uConfig::$lang === $langCode) ? ' selected' : '' ?>><?= $langName ?></option> <option value="<?= $langCode ?>"<?= ($config->lang === $langCode) ? ' selected' : '' ?>><?= $langName ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</div> </div>
@ -108,9 +109,9 @@
<div class="section"> <div class="section">
<label for="units"><?= $lang['units'] ?></label> <label for="units"><?= $lang['units'] ?></label>
<select id="units" name="units" data-bind="units"> <select id="units" name="units" data-bind="units">
<option value="metric"<?= (uConfig::$units === 'metric') ? ' selected' : '' ?>><?= $lang['metric'] ?></option> <option value="metric"<?= ($config->units === 'metric') ? ' selected' : '' ?>><?= $lang['metric'] ?></option>
<option value="imperial"<?= (uConfig::$units === 'imperial') ? ' selected' : '' ?>><?= $lang['imperial'] ?></option> <option value="imperial"<?= ($config->units === 'imperial') ? ' selected' : '' ?>><?= $lang['imperial'] ?></option>
<option value="nautical"<?= (uConfig::$units === 'nautical') ? ' selected' : '' ?>><?= $lang['nautical'] ?></option> <option value="nautical"<?= ($config->units === 'nautical') ? ' selected' : '' ?>><?= $lang['nautical'] ?></option>
</select> </select>
</div> </div>
@ -142,7 +143,7 @@
</div> </div>
<div id="menu-button"><a data-bind="onMenuToggle"></a></div> <div id="menu-button"><a data-bind="onMenuToggle"></a></div>
<div id="footer"><a target="_blank" href="https://github.com/bfabiszewski/ulogger-server"><span class="mi">μ</span>logger</a> <?= uConfig::$version ?></div> <div id="footer"><a target="_blank" href="https://github.com/bfabiszewski/ulogger-server"><span class="mi">μ</span>logger</a> <?= $config->version ?></div>
</div> </div>
<div id="main"> <div id="main">

View File

@ -23,11 +23,12 @@
$auth_error = uUtils::getBool('auth_error', false); $auth_error = uUtils::getBool('auth_error', false);
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$lang = (new uLang($config))->getStrings();
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="<?= uConfig::$lang ?>"> <html lang="<?= $config->lang ?>">
<head> <head>
<title><?= $lang["title"] ?></title> <title><?= $lang["title"] ?></title>
<?php include("meta.php"); ?> <?php include("meta.php"); ?>
@ -49,7 +50,7 @@
<br> <br>
<input type="submit" value="<?= $lang["login"] ?>"> <input type="submit" value="<?= $lang["login"] ?>">
<input type="hidden" name="action" value="auth"> <input type="hidden" name="action" value="auth">
<?php if (!uConfig::$requireAuthentication): ?> <?php if (!$config->requireAuthentication): ?>
<div id="cancel"><a href="<?= BASE_URL ?>"><?= $lang["cancel"] ?></a></div> <div id="cancel"><a href="<?= BASE_URL ?>"><?= $lang["cancel"] ?></a></div>
<?php endif; ?> <?php endif; ?>
</form> </form>

View File

@ -33,7 +33,7 @@ if (file_exists(ROOT_DIR . '/vendor/autoload.php')) {
} }
// check we are running in CLI mode // check we are running in CLI mode
if (PHP_SAPI != 'cli') { if (PHP_SAPI !== 'cli') {
exit('Call me on CLI only!' . PHP_EOL); exit('Call me on CLI only!' . PHP_EOL);
} }
@ -90,7 +90,9 @@ if (!$getopt->getOption('import-existing-track')) {
$gpxFiles = $getopt->getOperand('gpx'); $gpxFiles = $getopt->getOperand('gpx');
foreach ($gpxFiles as $i => $gpxFile) { foreach ($gpxFiles as $i => $gpxFile) {
// skip last track? // 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); $gpxName = basename($gpxFile);
@ -105,7 +107,8 @@ foreach ($gpxFiles as $i => $gpxFile) {
print('importing ' . $gpxFile.'...' . PHP_EOL); print('importing ' . $gpxFile.'...' . PHP_EOL);
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$lang = (new uLang($config))->getStrings();
$gpx = false; $gpx = false;
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
@ -125,8 +128,8 @@ foreach ($gpxFiles as $i => $gpxFile) {
} }
uUtils::exitWithError($message); uUtils::exitWithError($message);
} }
else if ($gpx->getName() != "gpx") { else if ($gpx->getName() !== "gpx") {
uUtils::exitWithError($lang["iparsefailure"]); uUtils::exitWithError($lang["iparsefailure"]);
} }
else if (empty($gpx->trk)) { else if (empty($gpx->trk)) {
uUtils::exitWithError($lang["idatafailure"]); uUtils::exitWithError($lang["idatafailure"]);
@ -165,8 +168,8 @@ foreach ($gpxFiles as $i => $gpxFile) {
if (count($ext->provider)) { $provider = (string) $ext->provider; } if (count($ext->provider)) { $provider = (string) $ext->provider; }
} }
$ret = $track->addPosition($userId, $ret = $track->addPosition($userId,
$time, (double) $point["lat"], (double) $point["lon"], $altitude, $time, (double) $point["lat"], (double) $point["lon"], $altitude,
$speed, $bearing, $accuracy, $provider, NULL, NULL); $speed, $bearing, $accuracy, $provider, NULL, NULL);
if ($ret === false) { if ($ret === false) {
$track->delete(); $track->delete();
uUtils::exitWithError($lang["servererror"]); uUtils::exitWithError($lang["servererror"]);

View File

@ -30,6 +30,21 @@ if (version_compare(PHP_VERSION, "5.5.0", "<")) {
} }
define("ROOT_DIR", dirname(__DIR__)); 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/db.php");
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/lang.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"); require_once(ROOT_DIR . "/helpers/utils.php");
$command = uUtils::postString("command"); $command = uUtils::postString("command");
$language = uUtils::getString("lang", "en");
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getOfflineInstance();
$langSetup = (new uLang(uConfig::$lang))->getSetupStrings(); $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"; $tPositions = $prefix . "positions";
$tTracks = $prefix . "tracks"; $tTracks = $prefix . "tracks";
$tUsers = $prefix . "users"; $tUsers = $prefix . "users";
@ -79,7 +97,7 @@ switch ($command) {
if (!$error) { if (!$error) {
$messages[] = "<span class=\"ok\">{$langSetup["dbtablessuccess"]}</span>"; $messages[] = "<span class=\"ok\">{$langSetup["dbtablessuccess"]}</span>";
$messages[] = $langSetup["setupuser"]; $messages[] = $langSetup["setupuser"];
$form = "<form id=\"userForm\" method=\"post\" action=\"setup.php\" onsubmit=\"return validateForm()\"><input type=\"hidden\" name=\"command\" value=\"adduser\">"; $form = "<form id=\"userForm\" method=\"post\" action=\"setup.php?lang=$language\" onsubmit=\"return validateForm()\"><input type=\"hidden\" name=\"command\" value=\"adduser\">";
$form .= "<label><b>{$lang["username"]}</b></label><input type=\"text\" placeholder=\"{$lang["usernameenter"]}\" name=\"login\" required>"; $form .= "<label><b>{$lang["username"]}</b></label><input type=\"text\" placeholder=\"{$lang["usernameenter"]}\" name=\"login\" required>";
$form .= "<label><b>{$lang["password"]}</b></label><input type=\"password\" placeholder=\"{$lang["passwordenter"]}\" name=\"pass\" required>"; $form .= "<label><b>{$lang["password"]}</b></label><input type=\"password\" placeholder=\"{$lang["passwordenter"]}\" name=\"pass\" required>";
$form .= "<label><b>{$lang["passwordrepeat"]}</b></label><input type=\"password\" placeholder=\"{$lang["passwordenter"]}\" name=\"pass2\" required>"; $form .= "<label><b>{$lang["passwordrepeat"]}</b></label><input type=\"password\" placeholder=\"{$lang["passwordenter"]}\" name=\"pass2\" required>";
@ -90,6 +108,7 @@ switch ($command) {
break; break;
case "adduser": case "adduser":
$config->save();
$login = uUtils::postString("login"); $login = uUtils::postString("login");
$pass = uUtils::postPass("pass"); $pass = uUtils::postPass("pass");
@ -104,43 +123,54 @@ switch ($command) {
break; break;
default: default:
$langsArr = uLang::getLanguages();
$langsOpts = "";
foreach ($langsArr as $langCode => $langName) {
$langsOpts .= "<option value=\"$langCode\"" . ($config->lang === $langCode ? " selected" : "") . ">$langName</option>";
}
$messages[] = "<div id=\"language\">
<label for=\"lang\">{$lang['language']}</label>
<select id=\"lang\" name=\"lang\" onchange=\"return changeLang(this)\">
$langsOpts
</select>
</div>";
$messages[] = "<img src=\"../icons/favicon-32x32.png\" alt=\"µLogger\">" . $langSetup["welcome"]; $messages[] = "<img src=\"../icons/favicon-32x32.png\" alt=\"µLogger\">" . $langSetup["welcome"];
if (!isset($enabled) || $enabled === false) { if (!isset($enabled) || $enabled === false) {
$messages[] = sprintf($langSetup["disabledwarn"], "<b>\$enabled</b>", "<b>true</b>"); $messages[] = sprintf($langSetup["disabledwarn"], "<b>\$enabled</b>", "<b>true</b>");
$messages[] = sprintf($langSetup["lineshouldread"], "<br><span class=\"warn\">\$enabled = false;</span><br>", "<br><span class=\"ok\">\$enabled = true;</span>"); $messages[] = sprintf($langSetup["lineshouldread"], "<br><span class=\"warn\">\$enabled = false;</span><br>", "<br><span class=\"ok\">\$enabled = true;</span>");
$messages[] = $langSetup["dorestart"]; $messages[] = $langSetup["dorestart"];
$messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php?lang=$language\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
if (!uConfig::isFileLoaded()) { if (!$dbConfigLoaded) {
$messages[] = $langSetup["createconfig"]; $messages[] = $langSetup["createconfig"];
$messages[] = $langSetup["dorestart"]; $messages[] = $langSetup["dorestart"];
$messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php?lang=$language\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
if (ini_get("session.auto_start") === "1") { if (ini_get("session.auto_start") === "1") {
$messages[] = sprintf($langSetup["optionwarn"], "session.auto_start", "0 (off)"); $messages[] = sprintf($langSetup["optionwarn"], "session.auto_start", "0 (off)");
$messages[] = $langSetup["dorestart"]; $messages[] = $langSetup["dorestart"];
$messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php?lang=$language\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
if (!extension_loaded("pdo")) { if (!extension_loaded("pdo")) {
$messages[] = sprintf($langSetup["extensionwarn"], "PDO"); $messages[] = sprintf($langSetup["extensionwarn"], "PDO");
$messages[] = $langSetup["dorestart"]; $messages[] = $langSetup["dorestart"];
$messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php?lang=$language\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
if (empty(uConfig::$dbdsn)) { if (empty($configDSN)) {
$messages[] = sprintf($langSetup["nodbsettings"], "\$dbdsn"); $messages[] = sprintf($langSetup["nodbsettings"], "\$dbdsn");
$messages[] = $langSetup["dorestart"]; $messages[] = $langSetup["dorestart"];
$messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php?lang=$language\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
try { try {
$pdo = getPdo(); $pdo = getPdo();
} catch (PDOException $e) { } catch (PDOException $e) {
$isSqlite = stripos(uConfig::$dbdsn, "sqlite") === 0; $isSqlite = stripos($configDSN, "sqlite") === 0;
if (!$isSqlite && empty(uConfig::$dbuser)) { if (!$isSqlite && empty($configUser)) {
$messages[] = sprintf($langSetup["nodbsettings"], "\$dbuser, \$dbpass"); $messages[] = sprintf($langSetup["nodbsettings"], "\$dbuser, \$dbpass");
} else { } else {
$messages[] = $langSetup["dbconnectfailed"]; $messages[] = $langSetup["dbconnectfailed"];
@ -148,15 +178,15 @@ switch ($command) {
$messages[] = sprintf($langSetup["serversaid"], "<b>" . htmlentities($e->getMessage()) . "</b>"); $messages[] = sprintf($langSetup["serversaid"], "<b>" . htmlentities($e->getMessage()) . "</b>");
} }
$messages[] = $langSetup["dorestart"]; $messages[] = $langSetup["dorestart"];
$messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php?lang=$language\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
$pdo = null; $pdo = null;
$dbName = uDb::getDbName(uConfig::$dbdsn); $dbName = uDb::getDbName($configDSN);
$dbName = empty($dbName) ? '""' : "<b>" . htmlentities($dbName) . "</b>"; $dbName = empty($dbName) ? '""' : "<b>" . htmlentities($dbName) . "</b>";
$messages[] = sprintf($langSetup["scriptdesc"], "'$tPositions', '$tTracks', '$tUsers'", $dbName); $messages[] = sprintf($langSetup["scriptdesc"], "'$tPositions', '$tTracks', '$tUsers'", $dbName);
$messages[] = $langSetup["scriptdesc2"]; $messages[] = $langSetup["scriptdesc2"];
$messages[] = "<form method=\"post\" action=\"setup.php\"><input type=\"hidden\" name=\"command\" value=\"setup\"><button>{$langSetup["startbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php?lang=$language\"><input type=\"hidden\" name=\"command\" value=\"setup\"><button>{$langSetup["startbutton"]}</button></form>";
break; break;
} }
@ -417,14 +447,15 @@ function getQueries($dbDriver) {
* @throws PDOException * @throws PDOException
*/ */
function getPdo() { function getPdo() {
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]; global $configDSN, $configUser, $configPass;
return new PDO(uConfig::$dbdsn, uConfig::$dbuser, uConfig::$dbpass, $options); $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ];
return new PDO($configDSN, $configUser, $configPass, $options);
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="<?= uConfig::$lang ?>"> <html lang="<?= $language ?>">
<head> <head>
<title><?= $lang["title"] ?></title> <title><?= $lang["title"] ?></title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
@ -455,6 +486,14 @@ function getPdo() {
-webkit-border-radius: 5px; -webkit-border-radius: 5px;
} }
#language {
text-align: right;
}
#language label {
font-size: small;
}
.warn { .warn {
color: #ffc747; color: #ffc747;
} }
@ -466,7 +505,6 @@ function getPdo() {
<!--suppress ES6ConvertVarToLetConst --> <!--suppress ES6ConvertVarToLetConst -->
<script> <script>
var lang = <?= json_encode($lang) ?>; var lang = <?= json_encode($lang) ?>;
var pass_regex = <?= uConfig::passRegex() ?>;
function validateForm() { function validateForm() {
var form = document.getElementById('userForm'); var form = document.getElementById('userForm');
@ -481,12 +519,13 @@ function getPdo() {
alert(lang['passnotmatch']); alert(lang['passnotmatch']);
return false; return false;
} }
if (!pass_regex.test(pass)) {
alert(lang['passlenmin'] + '\n' + lang['passrules']);
return false;
}
return true; return true;
} }
function changeLang(el) {
window.location = '?lang=' + el.value;
return false;
}
</script> </script>
</head> </head>

View File

@ -17,44 +17,49 @@
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
require_once(dirname(__DIR__) . "/helpers/auth.php"); require_once(dirname(__DIR__) . "/helpers/auth.php");
require_once(ROOT_DIR . "/helpers/utils.php"); require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/utils.php");
$auth = new uAuth(); $auth = new uAuth();
if (!$auth->isAuthenticated()) { $config = uConfig::getInstance();
$auth->sendUnauthorizedHeader(); if (!$auth->isAuthenticated()) {
uUtils::exitWithError("Unauthorized"); $auth->sendUnauthorizedHeader();
} uUtils::exitWithError("Unauthorized");
}
$login = uUtils::postString('login'); $login = uUtils::postString('login');
$oldpass = uUtils::postPass('oldpass'); $oldpass = uUtils::postPass('oldpass');
$pass = uUtils::postPass('pass'); $pass = uUtils::postPass('pass');
// FIXME: strings need to be localized // FIXME: strings need to be localized
if (empty($pass)) { if (empty($pass)) {
uUtils::exitWithError("Empty password"); 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)) { } else if ($auth->isAdmin()) {
uUtils::exitWithError("Empty login"); // different user, only admin
$passUser = new uUser($login);
if (!$passUser->isValid) {
uUtils::exitWithError("User unknown");
} }
if ($auth->user->login === $login) { } else {
// current user uUtils::exitWithError("Unauthorized");
$passUser = $auth->user; }
if (!$passUser->validPassword($oldpass)) { if ($passUser->setPass($pass) === false) {
uUtils::exitWithError("Wrong old password"); uUtils::exitWithError("Server error");
} }
} else if ($auth->isAdmin()) { $auth->updateSession();
// different user, only admin uUtils::exitWithSuccess();
$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();
?> ?>

View File

@ -23,7 +23,8 @@ require_once(ROOT_DIR . "/helpers/lang.php");
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
$auth = new uAuth(); $auth = new uAuth();
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$lang = (new uLang($config))->getStrings();
/** /**
* Add kml marker style element * Add kml marker style element
@ -62,13 +63,13 @@ $type = uUtils::getString('type', 'kml');
$userId = uUtils::getInt('userid'); $userId = uUtils::getInt('userid');
$trackId = uUtils::getInt('trackid'); $trackId = uUtils::getInt('trackid');
if (!uConfig::$publicTracks && if (!$config->publicTracks &&
(!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $userId))) { (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $userId))) {
// unauthorized // unauthorized
exit(); exit();
} }
if (uConfig::$units === "imperial") { if ($config->units === "imperial") {
$factor_kmh = 0.62; //to mph $factor_kmh = 0.62; //to mph
$unit_kmh = "mph"; $unit_kmh = "mph";
$factor_m = 3.28; // to feet $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("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", "xsi", NULL, "http://www.w3.org/2001/XMLSchema-instance");
$xml->writeAttributeNs("xmlns", "ulogger", NULL, "https://github.com/bfabiszewski/ulogger-android/1"); $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->writeAttribute("version", "1.1");
$xml->startElement("metadata"); $xml->startElement("metadata");
$xml->writeElement("name", $positionsArr[0]->trackName); $xml->writeElement("name", $positionsArr[0]->trackName);

View File

@ -22,7 +22,8 @@ require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/lang.php"); require_once(ROOT_DIR . "/helpers/lang.php");
$auth = new uAuth(); $auth = new uAuth();
$langStrings = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$langStrings = (new uLang($config))->getStrings();
$result = []; $result = [];
$resultAuth = [ $resultAuth = [
@ -35,20 +36,20 @@ if ($auth->isAuthenticated()) {
} }
$resultConfig = [ $resultConfig = [
"interval" => uConfig::$interval, "interval" => $config->interval,
"units" => uConfig::$units, "units" => $config->units,
"lang" => uConfig::$lang, "lang" => $config->lang,
"mapApi" => uConfig::$mapApi, "mapApi" => $config->mapApi,
"gkey" => uConfig::$googleKey, "gkey" => $config->googleKey,
"initLatitude" => uConfig::$initLatitude, "initLatitude" => $config->initLatitude,
"initLongitude" => uConfig::$initLongitude, "initLongitude" => $config->initLongitude,
"passRegex" => uConfig::passRegex(), "passRegex" => $config->passRegex(),
"strokeWeight" => uConfig::$strokeWeight, "strokeWeight" => $config->strokeWeight,
"strokeColor" => uConfig::$strokeColor, "strokeColor" => $config->strokeColor,
"strokeOpacity" => uConfig::$strokeOpacity, "strokeOpacity" => $config->strokeOpacity,
"olLayers" => [] "olLayers" => []
]; ];
foreach (uConfig::$olLayers as $key => $val) { foreach ($config->olLayers as $key => $val) {
$resultConfig["olLayers"][$key] = $val; $resultConfig["olLayers"][$key] = $val;
} }

View File

@ -18,10 +18,12 @@
*/ */
require_once(dirname(__DIR__) . "/helpers/auth.php"); 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/position.php");
require_once(ROOT_DIR . "/helpers/utils.php"); require_once(ROOT_DIR . "/helpers/utils.php");
$auth = new uAuth(); $auth = new uAuth();
$config = uConfig::getInstance();
$userId = uUtils::getInt('userid'); $userId = uUtils::getInt('userid');
$trackId = uUtils::getInt('trackid'); $trackId = uUtils::getInt('trackid');
@ -30,7 +32,7 @@ $last = uUtils::getBool('last');
$positionsArr = []; $positionsArr = [];
if ($userId) { if ($userId) {
if (uConfig::$publicTracks || if ($config->publicTracks ||
($auth->isAuthenticated() && ($auth->isAdmin() || $auth->user->id === $userId))) { ($auth->isAuthenticated() && ($auth->isAdmin() || $auth->user->id === $userId))) {
if ($trackId) { if ($trackId) {
// get all track data // get all track data
@ -44,7 +46,7 @@ if ($userId) {
} }
} }
} else if ($last) { } else if ($last) {
if (uConfig::$publicTracks || ($auth->isAuthenticated() && ($auth->isAdmin()))) { if ($config->publicTracks || ($auth->isAuthenticated() && ($auth->isAdmin()))) {
$positionsArr = uPosition::getLastAllUsers(); $positionsArr = uPosition::getLastAllUsers();
} }
} }

View File

@ -18,15 +18,17 @@
*/ */
require_once(dirname(__DIR__) . "/helpers/auth.php"); require_once(dirname(__DIR__) . "/helpers/auth.php");
require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/track.php"); require_once(ROOT_DIR . "/helpers/track.php");
$auth = new uAuth(); $auth = new uAuth();
$config = uConfig::getInstance();
$userId = uUtils::getInt('userid'); $userId = uUtils::getInt('userid');
$tracksArr = []; $tracksArr = [];
if ($userId) { if ($userId) {
if (uConfig::$publicTracks || if ($config->publicTracks ||
($auth->isAuthenticated() && ($auth->isAdmin() || $auth->user->id === $userId))) { ($auth->isAuthenticated() && ($auth->isAdmin() || $auth->user->id === $userId))) {
$tracksArr = uTrack::getAll($userId); $tracksArr = uTrack::getAll($userId);
} }

View File

@ -19,12 +19,14 @@
*/ */
require_once(dirname(__DIR__) . "/helpers/auth.php"); require_once(dirname(__DIR__) . "/helpers/auth.php");
require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/track.php"); require_once(ROOT_DIR . "/helpers/track.php");
$auth = new uAuth(); $auth = new uAuth();
$config = uConfig::getInstance();
$usersArr = []; $usersArr = [];
if (uConfig::$publicTracks || $auth->isAdmin()) { if ($config->publicTracks || $auth->isAdmin()) {
$usersArr = uUser::getAll(); $usersArr = uUser::getAll();
} else if ($auth->isAuthenticated()) { } else if ($auth->isAuthenticated()) {
$usersArr = [ $auth->user ]; $usersArr = [ $auth->user ];

View File

@ -17,49 +17,50 @@
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
require_once(dirname(__DIR__) . "/helpers/auth.php"); require_once(dirname(__DIR__) . "/helpers/auth.php");
require_once(ROOT_DIR . "/helpers/lang.php"); require_once(ROOT_DIR . "/helpers/lang.php");
require_once(ROOT_DIR . "/helpers/track.php"); require_once(ROOT_DIR . "/helpers/track.php");
require_once(ROOT_DIR . "/helpers/utils.php"); require_once(ROOT_DIR . "/helpers/utils.php");
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
$auth = new uAuth(); $auth = new uAuth();
$action = uUtils::postString('action'); $action = uUtils::postString('action');
$positionId = uUtils::postInt('posid'); $positionId = uUtils::postInt('posid');
$comment = uUtils::postString('comment'); $comment = uUtils::postString('comment');
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$lang = (new uLang($config))->getStrings();
if (empty($action) || empty($positionId)) { if (empty($action) || empty($positionId)) {
uUtils::exitWithError($lang["servererror"]); uUtils::exitWithError($lang["servererror"]);
} }
$position = new uPosition($positionId); $position = new uPosition($positionId);
if (!$position->isValid || if (!$position->isValid ||
(!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $position->userId))) { (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $position->userId))) {
uUtils::exitWithError($lang["servererror"]); uUtils::exitWithError($lang["servererror"]);
} }
switch ($action) { switch ($action) {
case 'update': case 'update':
$position->comment = $comment; $position->comment = $comment;
if ($position->update() === false) { if ($position->update() === false) {
uUtils::exitWithError($lang["servererror"]);
}
break;
case 'delete':
if ($position->delete() === false) {
uUtils::exitWithError($lang["servererror"]);
}
break;
default:
uUtils::exitWithError($lang["servererror"]); 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();
?> ?>

View File

@ -17,48 +17,49 @@
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
require_once(dirname(__DIR__) . "/helpers/auth.php"); require_once(dirname(__DIR__) . "/helpers/auth.php");
require_once(ROOT_DIR . "/helpers/lang.php"); require_once(ROOT_DIR . "/helpers/lang.php");
require_once(ROOT_DIR . "/helpers/track.php"); require_once(ROOT_DIR . "/helpers/track.php");
require_once(ROOT_DIR . "/helpers/utils.php"); require_once(ROOT_DIR . "/helpers/utils.php");
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
$auth = new uAuth(); $auth = new uAuth();
$action = uUtils::postString('action'); $action = uUtils::postString('action');
$trackId = uUtils::postInt('trackid'); $trackId = uUtils::postInt('trackid');
$trackName = uUtils::postString('trackname'); $trackName = uUtils::postString('trackname');
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$lang = (new uLang($config))->getStrings();
if (empty($action) || empty($trackId)) { if (empty($action) || empty($trackId)) {
uUtils::exitWithError($lang["servererror"]); uUtils::exitWithError($lang["servererror"]);
} }
$track = new uTrack($trackId); $track = new uTrack($trackId);
if (!$track->isValid || if (!$track->isValid ||
(!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $track->userId))) { (!$auth->isAuthenticated() || (!$auth->isAdmin() && $auth->user->id !== $track->userId))) {
uUtils::exitWithError($lang["servererror"]); uUtils::exitWithError($lang["servererror"]);
} }
switch ($action) { switch ($action) {
case 'update': case 'update':
if (empty($trackName) || $track->update($trackName) === false) { if (empty($trackName) || $track->update($trackName) === false) {
uUtils::exitWithError($lang["servererror"]);
}
break;
case 'delete':
if ($track->delete() === false) {
uUtils::exitWithError($lang["servererror"]);
}
break;
default:
uUtils::exitWithError($lang["servererror"]); 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();
?> ?>

View File

@ -17,63 +17,64 @@
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
require_once(dirname(__DIR__) . "/helpers/auth.php"); require_once(dirname(__DIR__) . "/helpers/auth.php");
require_once(ROOT_DIR . "/helpers/lang.php"); require_once(ROOT_DIR . "/helpers/lang.php");
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/utils.php"); require_once(ROOT_DIR . "/helpers/utils.php");
$auth = new uAuth(); $auth = new uAuth();
$config = uConfig::getInstance();
$action = uUtils::postString('action'); $action = uUtils::postString('action');
$login = uUtils::postString('login'); $login = uUtils::postString('login');
$pass = uUtils::postPass('pass'); $pass = uUtils::postPass('pass');
$admin = uUtils::postBool('admin', false); $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)) { if ($auth->user->login === $login || empty($action) || empty($login) || !$auth->isAuthenticated() || !$auth->isAdmin()) {
uUtils::exitWithError($lang["servererror"]); uUtils::exitWithError($lang["servererror"]);
} }
if ($admin && !$auth->isAdmin()) { if ($admin && !$auth->isAdmin()) {
uUtils::exitWithError($lang["notauthorized"]); uUtils::exitWithError($lang["notauthorized"]);
} }
$aUser = new uUser($login); $aUser = new uUser($login);
$data = NULL; $data = NULL;
switch ($action) { switch ($action) {
case 'add': case 'add':
if ($aUser->isValid) { if ($aUser->isValid) {
uUtils::exitWithError($lang["userexists"]); uUtils::exitWithError($lang["userexists"]);
} }
if (empty($pass) || ($userId = uUser::add($login, $pass, $admin)) === false) { if (empty($pass) || !$config->validPassStrength($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:
uUtils::exitWithError($lang["servererror"]); 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);
?> ?>

View File

@ -26,7 +26,8 @@ require_once(ROOT_DIR . "/helpers/lang.php");
$auth = new uAuth(); $auth = new uAuth();
$lang = (new uLang(uConfig::$lang))->getStrings(); $config = uConfig::getInstance();
$lang = (new uLang($config))->getStrings();
$uploadErrors = []; $uploadErrors = [];
$uploadErrors[UPLOAD_ERR_INI_SIZE] = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; $uploadErrors[UPLOAD_ERR_INI_SIZE] = "The uploaded file exceeds the upload_max_filesize directive in php.ini";