Use static initializer in uConfig class

This commit is contained in:
Bartek Fabiszewski 2017-04-18 09:25:21 +02:00
parent f4c1ada374
commit ffef321be9
10 changed files with 68 additions and 59 deletions

View File

@ -19,8 +19,6 @@
define("ROOT_DIR", __DIR__); define("ROOT_DIR", __DIR__);
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
$config = new uConfig();
require_once(ROOT_DIR . "/lang.php"); require_once(ROOT_DIR . "/lang.php");
require_once(ROOT_DIR . "/helpers/user.php"); require_once(ROOT_DIR . "/helpers/user.php");
@ -31,12 +29,12 @@ $sid = session_id();
// check for forced login to authorize admin in case of public access // check for forced login to authorize admin in case of public access
$force_login = (isset($_REQUEST['force_login']) ? $_REQUEST['force_login'] : false); $force_login = (isset($_REQUEST['force_login']) ? $_REQUEST['force_login'] : false);
if ($force_login) { if ($force_login) {
$config::$require_authentication = true; uConfig::$require_authentication = true;
} }
$user = new uUser(); $user = new uUser();
$user->getFromSession(); $user->getFromSession();
if (!$user->isValid && ($config::$require_authentication || defined('headless'))) { if (!$user->isValid && (uConfig::$require_authentication || defined('headless'))) {
/* authentication */ /* authentication */
$login = (isset($_REQUEST['user']) ? $_REQUEST['user'] : NULL); $login = (isset($_REQUEST['user']) ? $_REQUEST['user'] : NULL);
$pass = (isset($_REQUEST['pass']) ? $_REQUEST['pass'] : NULL); $pass = (isset($_REQUEST['pass']) ? $_REQUEST['pass'] : NULL);

View File

@ -17,6 +17,12 @@
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
*/ */
/**
* Initialize on file include
*/
uConfig::init();
/** /**
* Handles config values * Handles config values
*/ */
@ -82,18 +88,23 @@
private static $fileLoaded = false; private static $fileLoaded = false;
private static $initialized = false;
/** /**
* Constructor * Static initializer
*/ */
public function __construct() { static public function init() {
$this->setFromFile(); if (!self::$initialized) {
$this->setFromCookies(); self::setFromFile();
self::setFromCookies();
self::$initialized = true;
}
} }
/** /**
* Read config values from "/config.php" file * Read config values from "/config.php" file
*/ */
private function setFromFile() { private static function setFromFile() {
$configFile = ROOT_DIR . "/config.php"; $configFile = ROOT_DIR . "/config.php";
if (self::$fileLoaded || !file_exists($configFile)) { if (self::$fileLoaded || !file_exists($configFile)) {
return; return;
@ -132,14 +143,19 @@
/** /**
* Read config values stored in cookies * Read config values stored in cookies
*/ */
private function setFromCookies() { private static function setFromCookies() {
if (isset($_COOKIE["ulogger_api"])) { self::$mapapi = $_COOKIE["ulogger_api"]; } if (isset($_COOKIE["ulogger_api"])) { self::$mapapi = $_COOKIE["ulogger_api"]; }
if (isset($_COOKIE["ulogger_lang"])) { self::$lang = $_COOKIE["ulogger_lang"]; } if (isset($_COOKIE["ulogger_lang"])) { self::$lang = $_COOKIE["ulogger_lang"]; }
if (isset($_COOKIE["ulogger_units"])) { self::$units = $_COOKIE["ulogger_units"]; } if (isset($_COOKIE["ulogger_units"])) { self::$units = $_COOKIE["ulogger_units"]; }
if (isset($_COOKIE["ulogger_interval"])) { self::$interval = $_COOKIE["ulogger_interval"]; } if (isset($_COOKIE["ulogger_interval"])) { self::$interval = $_COOKIE["ulogger_interval"]; }
} }
public function isFileLoaded() { /**
* Is config loaded from file?
*
* @return True if loaded, false otherwise
*/
public static function isFileLoaded() {
return self::$fileLoaded; return self::$fileLoaded;
} }
@ -147,7 +163,7 @@
* Regex to test if password matches strength and length requirements. * Regex to test if password matches strength and length requirements.
* Valid for both php and javascript * Valid for both php and javascript
*/ */
public function passRegex() { public static function passRegex() {
static $regex = ""; static $regex = "";
if (self::$pass_strength > 0) { if (self::$pass_strength > 0) {
// lower and upper case // lower and upper case

View File

@ -62,10 +62,9 @@
*/ */
public static function getInstance() { public static function getInstance() {
if (!self::$instance) { if (!self::$instance) {
$config = new uConfig(); self::$instance = new self(uConfig::$dbhost, uConfig::$dbuser, uConfig::$dbpass, uConfig::$dbname);
self::$instance = new self($config::$dbhost, $config::$dbuser, $config::$dbpass, $config::$dbname);
self::$tables = []; self::$tables = [];
$prefix = preg_replace('/[^a-z0-9_]/i', '', $config::$dbprefix); $prefix = preg_replace('/[^a-z0-9_]/i', '', uConfig::$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";

View File

@ -156,8 +156,7 @@
* @return bool True if matches, false otherwise * @return bool True if matches, false otherwise
*/ */
private function validPassStrength($password) { private function validPassStrength($password) {
$config = new uConfig(); return preg_match(uConfig::passRegex(), $password);
return preg_match($config->passRegex(), $password);
} }
/** /**
@ -225,8 +224,7 @@
* @return bool True if admin, false otherwise * @return bool True if admin, false otherwise
*/ */
private function isAdmin($login) { private function isAdmin($login) {
$config = new uConfig(); return (!empty(uConfig::$admin_user) && uConfig::$admin_user == $login);
return (!empty($config::$admin_user) && $config::$admin_user == $login);
} }
} }
?> ?>

View File

@ -23,7 +23,7 @@
$displayUserId = NULL; $displayUserId = NULL;
$usersArr = []; $usersArr = [];
if ($user->isAdmin || $config::$public_tracks) { if ($user->isAdmin || uConfig::$public_tracks) {
// public access or admin user // public access or admin user
// get last position user // get last position user
$lastPosition = new uPosition(); $lastPosition = new uPosition();
@ -67,27 +67,27 @@
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i&amp;subset=cyrillic" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i&amp;subset=cyrillic" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/main.css"> <link rel="stylesheet" type="text/css" href="css/main.css">
<script> <script>
var interval = '<?= $config::$interval ?>'; var interval = '<?= uConfig::$interval ?>';
var userid = '<?= ($displayUserId) ? $displayUserId : -1 ?>'; var userid = '<?= ($displayUserId) ? $displayUserId : -1 ?>';
var trackid = '<?= ($displayTrackId) ? $displayTrackId : -1 ?>'; var trackid = '<?= ($displayTrackId) ? $displayTrackId : -1 ?>';
var units = '<?= $config::$units ?>'; var units = '<?= uConfig::$units ?>';
var mapapi = '<?= $config::$mapapi ?>'; var mapapi = '<?= uConfig::$mapapi ?>';
var gkey = '<?= !empty($config::$gkey) ? $config::$gkey : "null" ?>'; var gkey = '<?= !empty(uConfig::$gkey) ? uConfig::$gkey : "null" ?>';
var layer_ocm = '<?= $config::$layer_ocm ?>'; var layer_ocm = '<?= uConfig::$layer_ocm ?>';
var layer_mq = '<?= $config::$layer_mq ?>'; var layer_mq = '<?= uConfig::$layer_mq ?>';
var layer_osmapa = '<?= $config::$layer_osmapa ?>'; var layer_osmapa = '<?= uConfig::$layer_osmapa ?>';
var layer_ump = '<?= $config::$layer_ump ?>'; var layer_ump = '<?= uConfig::$layer_ump ?>';
var init_latitude = '<?= $config::$init_latitude ?>'; var init_latitude = '<?= uConfig::$init_latitude ?>';
var init_longitude = '<?= $config::$init_longitude ?>'; var init_longitude = '<?= uConfig::$init_longitude ?>';
var lang = <?= json_encode($lang) ?>; var lang = <?= json_encode($lang) ?>;
var admin = <?= json_encode($user->isAdmin) ?>; var admin = <?= json_encode($user->isAdmin) ?>;
var auth = '<?= ($user->isValid) ? $user->login : "null" ?>'; var auth = '<?= ($user->isValid) ? $user->login : "null" ?>';
var pass_regex = <?= $config->passRegex() ?>; var pass_regex = <?= uConfig::passRegex() ?>;
</script> </script>
<script type="text/javascript" src="js/main.js"></script> <script type="text/javascript" src="js/main.js"></script>
<?php if ($config::$mapapi == "gmaps"): ?> <?php if (uConfig::$mapapi == "gmaps"): ?>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js<?= !empty($config::$gkey) ? "?key={$config::$gkey}" : "" ?>"></script> <script type="text/javascript" src="//maps.googleapis.com/maps/api/js<?= !empty(uConfig::$gkey) ? "?key=" . uConfig::$gkey : "" ?>"></script>
<script type="text/javascript" src="js/api_gmaps.js"></script> <script type="text/javascript" src="js/api_gmaps.js"></script>
<?php else: ?> <?php else: ?>
<script type="text/javascript" src="//openlayers.org/api/OpenLayers.js"></script> <script type="text/javascript" src="//openlayers.org/api/OpenLayers.js"></script>
@ -145,7 +145,7 @@
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
<input id="latest" type="checkbox" onchange="toggleLatest();"> <?= $lang["latest"] ?><br> <input id="latest" type="checkbox" onchange="toggleLatest();"> <?= $lang["latest"] ?><br>
<input type="checkbox" onchange="autoReload();"> <?= $lang["autoreload"] ?> (<a href="javascript:void(0);" onclick="setTime();"><span id="auto"><?= $config::$interval ?></span></a> s)<br> <input type="checkbox" onchange="autoReload();"> <?= $lang["autoreload"] ?> (<a href="javascript:void(0);" onclick="setTime();"><span id="auto"><?= uConfig::$interval ?></span></a> s)<br>
</form> </form>
<a href="javascript:void(0);" onclick="loadTrack(userid, trackid, 0);"> <?= $lang["reload"] ?></a><br> <a href="javascript:void(0);" onclick="loadTrack(userid, trackid, 0);"> <?= $lang["reload"] ?></a><br>
</div> </div>
@ -160,8 +160,8 @@
<?= $lang["api"] ?><br> <?= $lang["api"] ?><br>
<form> <form>
<select name="api" onchange="loadMapAPI(this.options[this.selectedIndex].value);"> <select name="api" onchange="loadMapAPI(this.options[this.selectedIndex].value);">
<option value="gmaps"<?= ($config::$mapapi == "gmaps") ? " selected" : "" ?>>Google Maps</option> <option value="gmaps"<?= (uConfig::$mapapi == "gmaps") ? " selected" : "" ?>>Google Maps</option>
<option value="openlayers"<?= ($config::$mapapi == "openlayers") ? " selected" : "" ?>>OpenLayers</option> <option value="openlayers"<?= (uConfig::$mapapi == "openlayers") ? " selected" : "" ?>>OpenLayers</option>
</select> </select>
</form> </form>
</div> </div>
@ -172,7 +172,7 @@
<select name="units" onchange="setLang(this.options[this.selectedIndex].value);"> <select name="units" onchange="setLang(this.options[this.selectedIndex].value);">
<?php asort($langsArr); ?> <?php asort($langsArr); ?>
<?php foreach ($langsArr as $langCode => $langName): ?> <?php foreach ($langsArr as $langCode => $langName): ?>
<option value="<?= $langCode ?>"<?= ($config::$lang == $langCode) ? " selected" : "" ?>><?= $langName ?></option> <option value="<?= $langCode ?>"<?= (uConfig::$lang == $langCode) ? " selected" : "" ?>><?= $langName ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</form> </form>
@ -182,8 +182,8 @@
<?= $lang["units"] ?><br> <?= $lang["units"] ?><br>
<form> <form>
<select name="units" onchange="setUnits(this.options[this.selectedIndex].value);"> <select name="units" onchange="setUnits(this.options[this.selectedIndex].value);">
<option value="metric"<?= ($config::$units == "metric") ? " selected" : "" ?>><?= $lang["metric"] ?></option> <option value="metric"<?= (uConfig::$units == "metric") ? " selected" : "" ?>><?= $lang["metric"] ?></option>
<option value="imperial"<?= ($config::$units == "imperial") ? " selected" : "" ?>><?= $lang["imperial"] ?></option> <option value="imperial"<?= (uConfig::$units == "imperial") ? " selected" : "" ?>><?= $lang["imperial"] ?></option>
</select> </select>
</form> </form>
</div> </div>
@ -207,7 +207,7 @@
</div> </div>
<div id="menu-close" onclick="toggleMenu();">»</div> <div id="menu-close" onclick="toggleMenu();">»</div>
<div id="footer"><a target="_blank" href="https://github.com/bfabiszewski/ulogger-server"><span class="mi">μ</span>logger</a> <?= $config::$version ?></div> <div id="footer"><a target="_blank" href="https://github.com/bfabiszewski/ulogger-server"><span class="mi">μ</span>logger</a> <?= uConfig::$version ?></div>
</div> </div>
<div id="main"> <div id="main">

View File

@ -33,12 +33,12 @@
// override with translated strings if needed // override with translated strings if needed
// missing strings will be displayed in English // missing strings will be displayed in English
if ($config::$lang != "en" && array_key_exists($config::$lang, $langsArr)) { if (uConfig::$lang != "en" && array_key_exists(uConfig::$lang, $langsArr)) {
require_once(ROOT_DIR . "/lang/{$config::$lang}.php"); require_once(ROOT_DIR . "/lang/" . uConfig::$lang . ".php");
} }
// choose password messages based on config // choose password messages based on config
$lang['passrules'] = isset($lang["passrules"][$config::$pass_strength]) ? $lang["passrules"][$config::$pass_strength] : ""; $lang['passrules'] = isset($lang["passrules"][uConfig::$pass_strength]) ? $lang["passrules"][uConfig::$pass_strength] : "";
$lang['passlenmin'] = sprintf($lang["passlenmin"], $config::$pass_lenmin); $lang['passlenmin'] = sprintf($lang["passlenmin"], uConfig::$pass_lenmin);
?> ?>

View File

@ -27,13 +27,11 @@ $enabled = false;
define("ROOT_DIR", dirname(__DIR__)); define("ROOT_DIR", dirname(__DIR__));
require_once(ROOT_DIR . "/helpers/user.php"); require_once(ROOT_DIR . "/helpers/user.php");
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
$config = new uConfig();
require_once(ROOT_DIR . "/lang.php"); require_once(ROOT_DIR . "/lang.php");
$command = isset($_REQUEST['command']) ? $_REQUEST['command'] : NULL; $command = isset($_REQUEST['command']) ? $_REQUEST['command'] : NULL;
$prefix = preg_replace('/[^a-z0-9_]/i', '', $config::$dbprefix); $prefix = preg_replace('/[^a-z0-9_]/i', '', uConfig::$dbprefix);
$tPositions = $prefix . "positions"; $tPositions = $prefix . "positions";
$tTracks = $prefix . "tracks"; $tTracks = $prefix . "tracks";
$tUsers = $prefix . "users"; $tUsers = $prefix . "users";
@ -87,7 +85,7 @@ switch ($command) {
$error = false; $error = false;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try { try {
$mysqli = new mysqli($config::$dbhost, $config::$dbuser, $config::$dbpass, $config::$dbname); $mysqli = new mysqli(uConfig::$dbhost, uConfig::$dbuser, uConfig::$dbpass, uConfig::$dbname);
} catch (mysqli_sql_exception $e ) { } catch (mysqli_sql_exception $e ) {
$messages[] = "<span class=\"warn\">{$langSetup["dbconnectfailed"]}</span>"; $messages[] = "<span class=\"warn\">{$langSetup["dbconnectfailed"]}</span>";
$messages[] = sprintf($langSetup["serversaid"], "<b>" . $e->getMessage() . "</b>"); $messages[] = sprintf($langSetup["serversaid"], "<b>" . $e->getMessage() . "</b>");
@ -153,19 +151,19 @@ switch ($command) {
$messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>"; $messages[] = "<form method=\"post\" action=\"setup.php\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
if (!$config->isFileLoaded()) { if (!uConfig::isFileLoaded()) {
$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\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
if (empty($config::$dbname) || empty($config::$dbhost) || empty($config::$dbuser)) { if (empty(uConfig::$dbname) || empty(uConfig::$dbhost) || empty(uConfig::$dbuser)) {
$messages[] = sprintf($langSetup["nodbsettings"], "\$dbname, \$dbhost, \$dbuser, \$dbpass"); $messages[] = sprintf($langSetup["nodbsettings"], "\$dbname, \$dbhost, \$dbuser, \$dbpass");
$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\"><button>{$langSetup["restartbutton"]}</button></form>";
break; break;
} }
$messages[] = sprintf($langSetup["scriptdesc"], "'$tPositions', '$tTracks', '$tUsers'", "<b>{$config::$dbname}</b>"); $messages[] = sprintf($langSetup["scriptdesc"], "'$tPositions', '$tTracks', '$tUsers'", "<b>" . uConfig::$dbname . "</b>");
$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\"><input type=\"hidden\" name=\"command\" value=\"setup\"><button>{$langSetup["startbutton"]}</button></form>";
break; break;
@ -211,7 +209,7 @@ switch ($command) {
</style> </style>
<script type="text/javascript"> <script type="text/javascript">
var lang = <?= json_encode($lang) ?>; var lang = <?= json_encode($lang) ?>;
var pass_regex = <?= $config->passRegex() ?>; var pass_regex = <?= uConfig::passRegex() ?>;
function validateForm() { function validateForm() {
var form = document.getElementById('userForm'); var form = document.getElementById('userForm');

View File

@ -17,7 +17,7 @@
* 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__) . "/auth.php"); // sets $user, $config require_once(dirname(__DIR__) . "/auth.php"); // sets $user
require_once(ROOT_DIR . "/helpers/position.php"); require_once(ROOT_DIR . "/helpers/position.php");
/** /**
@ -57,12 +57,12 @@ $type = isset($_REQUEST["type"]) ? $_REQUEST["type"] : "kml";
$userId = (isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? (int) $_REQUEST["userid"] : NULL; $userId = (isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? (int) $_REQUEST["userid"] : NULL;
$trackId = (isset($_REQUEST["trackid"]) && is_numeric($_REQUEST["trackid"])) ? (int) $_REQUEST["trackid"] : NULL; $trackId = (isset($_REQUEST["trackid"]) && is_numeric($_REQUEST["trackid"])) ? (int) $_REQUEST["trackid"] : NULL;
if (!$config::$public_tracks && !$user->isAdmin && $user->id !== $userId) { if (!uConfig::$public_tracks && !$user->isAdmin && $user->id !== $userId) {
// unauthorized // unauthorized
exit(); exit();
} }
if ($config::$units == "imperial") { if (uConfig::$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

View File

@ -17,7 +17,7 @@
* 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__) . "/auth.php"); // sets $user, $config require_once(dirname(__DIR__) . "/auth.php"); // sets $user
require_once(ROOT_DIR . "/helpers/position.php"); require_once(ROOT_DIR . "/helpers/position.php");
$userId = (isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? (int) $_REQUEST["userid"] : NULL; $userId = (isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? (int) $_REQUEST["userid"] : NULL;
@ -26,7 +26,7 @@ $trackId = (isset($_REQUEST["trackid"]) && is_numeric($_REQUEST["trackid"])) ? (
if ($userId) { if ($userId) {
$positionsArr = []; $positionsArr = [];
if ($config::$public_tracks || $user->isAdmin || $user->id === $userId) { if (uConfig::$public_tracks || $user->isAdmin || $user->id === $userId) {
$position = new uPosition(); $position = new uPosition();
if ($trackId) { if ($trackId) {
// get all track data // get all track data

View File

@ -17,7 +17,7 @@
* 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__) . "/auth.php"); // sets $user, $config require_once(dirname(__DIR__) . "/auth.php"); // sets $user
require_once(ROOT_DIR . "/helpers/track.php"); require_once(ROOT_DIR . "/helpers/track.php");
$userId = (isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? (int) $_REQUEST["userid"] : NULL; $userId = (isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? (int) $_REQUEST["userid"] : NULL;
@ -25,7 +25,7 @@ $userId = (isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? (int
if ($userId) { if ($userId) {
$tracksArr = []; $tracksArr = [];
if ($config::$public_tracks || $user->isAdmin || $user->id === $userId) { if (uConfig::$public_tracks || $user->isAdmin || $user->id === $userId) {
$track = new uTrack(); $track = new uTrack();
$tracksArr = $track->getAll($userId); $tracksArr = $track->getAll($userId);
} }