initial PDO support

This commit is contained in:
Bartek Fabiszewski 2019-01-23 12:23:25 +01:00
parent 12778505e5
commit 61661e7fb7
7 changed files with 348 additions and 212 deletions

View File

@ -41,10 +41,9 @@ $init_longitude = 21.01;
$gkey = ""; $gkey = "";
// MySQL config // MySQL config
$dbhost = ""; // mysql host, eg. localhost $dbdsn = ""; // DSN eg. "mysql:host=localhost;port=3307;dbname=testdb;charset=utf8"
$dbuser = ""; // database user $dbuser = ""; // database user
$dbpass = ""; // database pass $dbpass = ""; // database pass
$dbname = ""; // database name
$dbprefix = ""; // optional table names prefix, eg. "ulogger_" $dbprefix = ""; // optional table names prefix, eg. "ulogger_"
// other // other

View File

@ -44,10 +44,9 @@
static $init_longitude = 21.01; static $init_longitude = 21.01;
// MySQL config // MySQL config
static $dbhost = ""; // mysql host, eg. localhost static $dbdsn = ""; // database dsn
static $dbuser = ""; // database user static $dbuser = ""; // database user
static $dbpass = ""; // database pass static $dbpass = ""; // database pass
static $dbname = ""; // database name
static $dbprefix = ""; // optional table names prefix, eg. "ulogger_" static $dbprefix = ""; // optional table names prefix, eg. "ulogger_"
// require login/password authentication // require login/password authentication
@ -82,7 +81,7 @@
static $strokeWeight = 2; static $strokeWeight = 2;
static $strokeColor = '#ff0000'; static $strokeColor = '#ff0000';
static $strokeOpacity = 1; static $strokeOpacity = 1;
private static $fileLoaded = false; private static $fileLoaded = false;
private static $initialized = false; private static $initialized = false;
@ -114,10 +113,9 @@
if (isset($ol_layers)) { self::$ol_layers = $ol_layers; } if (isset($ol_layers)) { self::$ol_layers = $ol_layers; }
if (isset($init_latitude)) { self::$init_latitude = $init_latitude; } if (isset($init_latitude)) { self::$init_latitude = $init_latitude; }
if (isset($init_longitude)) { self::$init_longitude = $init_longitude; } if (isset($init_longitude)) { self::$init_longitude = $init_longitude; }
if (isset($dbhost)) { self::$dbhost = $dbhost; } if (isset($dbdsn)) { self::$dbdsn = $dbdsn; }
if (isset($dbuser)) { self::$dbuser = $dbuser; } if (isset($dbuser)) { self::$dbuser = $dbuser; }
if (isset($dbpass)) { self::$dbpass = $dbpass; } if (isset($dbpass)) { self::$dbpass = $dbpass; }
if (isset($dbname)) { self::$dbname = $dbname; }
if (isset($dbprefix)) { self::$dbprefix = $dbprefix; } if (isset($dbprefix)) { self::$dbprefix = $dbprefix; }
if (isset($require_authentication)) { self::$require_authentication = (bool) $require_authentication; } if (isset($require_authentication)) { self::$require_authentication = (bool) $require_authentication; }
if (isset($public_tracks)) { self::$public_tracks = (bool) $public_tracks; } if (isset($public_tracks)) { self::$public_tracks = (bool) $public_tracks; }

View File

@ -20,9 +20,9 @@
require_once(ROOT_DIR . "/helpers/config.php"); require_once(ROOT_DIR . "/helpers/config.php");
/** /**
* mysqli wrapper * PDO wrapper
*/ */
class uDb extends mysqli { class uDb extends PDO {
/** /**
* Singleton instance * Singleton instance
* *
@ -38,23 +38,25 @@
protected static $tables; protected static $tables;
/** /**
* Private constuctor * PDO constuctor
* *
* @param string $host * @param string $dsn
* @param string $user * @param string $user
* @param string $pass * @param string $pass
* @param string $name
* @param int $port
* @param string $socket
*/ */
public function __construct($host, $user, $pass, $name, $port = null, $socket = null) { public function __construct($dsn, $user, $pass) {
@parent::__construct($host, $user, $pass, $name, $port, $socket); try {
if ($this->connect_error) { $options = [
PDO::ATTR_EMULATE_PREPARES => false, // try to use native prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // throw exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // return assoc array by default
];
@parent::__construct($dsn, $user, $pass, $options);
$this->initTables();
} catch (PDOException $e) {
header("HTTP/1.1 503 Service Unavailable"); header("HTTP/1.1 503 Service Unavailable");
die("Database connection error (" . $this->connect_error . ")"); die("Database connection error (" . $e->getMessage() . ")");
} }
$this->set_charset('utf8');
$this->initTables();
} }
/** /**
@ -75,7 +77,7 @@
*/ */
public static function getInstance() { public static function getInstance() {
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(uConfig::$dbhost, uConfig::$dbuser, uConfig::$dbpass, uConfig::$dbname); self::$instance = new self(uConfig::$dbdsn, uConfig::$dbuser, uConfig::$dbpass);
} }
return self::$instance; return self::$instance;
} }

View File

@ -54,12 +54,17 @@
$query = "SELECT p.id, UNIX_TIMESTAMP(p.time) AS tstamp, p.user_id, p.track_id, $query = "SELECT p.id, UNIX_TIMESTAMP(p.time) AS tstamp, p.user_id, p.track_id,
p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider, p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider,
p.comment, p.image_id, u.login, t.name p.comment, p.image_id, u.login, t.name
FROM `" . self::db()->table('positions') . "` p FROM " . self::db()->table('positions') . " p
LEFT JOIN `" . self::db()->table('users') . "` u ON (p.user_id = u.id) LEFT JOIN " . self::db()->table('users') . " u ON (p.user_id = u.id)
LEFT JOIN `" . self::db()->table('tracks') . "` t ON (p.track_id = t.id) LEFT JOIN " . self::db()->table('tracks') . " t ON (p.track_id = t.id)
WHERE id = ? LIMIT 1"; WHERE id = ? LIMIT 1";
$params = [ 'i', $positionId ]; $params = [ $positionId ];
$this->loadWithQuery($query, $params); try {
$this->loadWithQuery($query, $params);
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
}
} }
} }
@ -99,19 +104,20 @@
if (is_numeric($lat) && is_numeric($lon) && is_numeric($timestamp) && is_numeric($userId) && is_numeric($trackId)) { if (is_numeric($lat) && is_numeric($lon) && is_numeric($timestamp) && is_numeric($userId) && is_numeric($trackId)) {
$track = new uTrack($trackId); $track = new uTrack($trackId);
if ($track->isValid && $track->userId == $userId) { if ($track->isValid && $track->userId == $userId) {
$query = "INSERT INTO `" . self::db()->table('positions') . "` try {
(user_id, track_id, $table = self::db()->table('positions');
time, latitude, longitude, altitude, speed, bearing, accuracy, provider, comment, image_id) $query = "INSERT INTO $table
VALUES (?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?, ?)"; (user_id, track_id,
$stmt = self::db()->prepare($query); time, latitude, longitude, altitude, speed, bearing, accuracy, provider, comment, image_id)
$stmt->bind_param('iisddddddssi', VALUES (?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$userId, $trackId, $stmt = self::db()->prepare($query);
$timestamp, $lat, $lon, $altitude, $speed, $bearing, $accuracy, $provider, $comment, $imageId); $params = [ $userId, $trackId,
$stmt->execute(); $timestamp, $lat, $lon, $altitude, $speed, $bearing, $accuracy, $provider, $comment, $imageId ];
if (!self::db()->error && !$stmt->errno) { $stmt->execute($params);
$positionId = self::db()->insert_id; $positionId = self::db()->lastInsertId("${table}_id_seq");
} catch (PDOException $e) {
// TODO: handle error
} }
$stmt->close();
} }
} }
return $positionId; return $positionId;
@ -129,21 +135,20 @@
if (!empty($userId)) { if (!empty($userId)) {
$args = []; $args = [];
$where = "WHERE user_id = ?"; $where = "WHERE user_id = ?";
$args[0] = "i"; $args[] = $userId;
$args[1] = &$userId;
if (!empty($trackId)) { if (!empty($trackId)) {
$where .= " AND track_id = ?"; $where .= " AND track_id = ?";
$args[0] .= "i"; $args[] = $trackId;
$args[2] = &$trackId;
} }
$query = "DELETE FROM `" . self::db()->table('positions') . "` $where"; try {
$stmt = self::db()->prepare($query); $query = "DELETE FROM " . self::db()->table('positions') . " $where";
call_user_func_array([ $stmt, 'bind_param' ], $args); $stmt = self::db()->prepare($query);
$stmt->execute(); $stmt->execute($args);
if (!self::db()->error && !$stmt->errno) {
$ret = true; $ret = true;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
return $ret; return $ret;
} }
@ -158,7 +163,7 @@
public static function getLast($userId = NULL) { public static function getLast($userId = NULL) {
if (!empty($userId)) { if (!empty($userId)) {
$where = "WHERE p.user_id = ?"; $where = "WHERE p.user_id = ?";
$params = [ 'i', $userId ]; $params = [ $userId ];
} else { } else {
$where = ""; $where = "";
$params = NULL; $params = NULL;
@ -166,13 +171,18 @@
$query = "SELECT p.id, UNIX_TIMESTAMP(p.time) AS tstamp, p.user_id, p.track_id, $query = "SELECT p.id, UNIX_TIMESTAMP(p.time) AS tstamp, p.user_id, p.track_id,
p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider, p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider,
p.comment, p.image_id, u.login, t.name p.comment, p.image_id, u.login, t.name
FROM `" . self::db()->table('positions') . "` p FROM " . self::db()->table('positions') . " p
LEFT JOIN `" . self::db()->table('users') . "` u ON (p.user_id = u.id) LEFT JOIN " . self::db()->table('users') . " u ON (p.user_id = u.id)
LEFT JOIN `" . self::db()->table('tracks') . "` t ON (p.track_id = t.id) LEFT JOIN " . self::db()->table('tracks') . " t ON (p.track_id = t.id)
$where $where
ORDER BY p.time DESC, p.id DESC LIMIT 1"; ORDER BY p.time DESC, p.id DESC LIMIT 1";
$position = new uPosition(); $position = new uPosition();
$position->loadWithQuery($query, $params); try {
$position->loadWithQuery($query, $params);
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
}
return $position; return $position;
} }
@ -186,10 +196,10 @@
public static function getAll($userId = NULL, $trackId = NULL) { public static function getAll($userId = NULL, $trackId = NULL) {
$rules = []; $rules = [];
if (!empty($userId)) { if (!empty($userId)) {
$rules[] = "p.user_id = '" . self::db()->real_escape_string($userId) ."'"; $rules[] = "p.user_id = " . self::db()->quote($userId);
} }
if (!empty($trackId)) { if (!empty($trackId)) {
$rules[] = "p.track_id = '" . self::db()->real_escape_string($trackId) ."'"; $rules[] = "p.track_id = " . self::db()->quote($trackId);
} }
if (!empty($rules)) { if (!empty($rules)) {
$where = "WHERE " . implode(" AND ", $rules); $where = "WHERE " . implode(" AND ", $rules);
@ -199,20 +209,21 @@
$query = "SELECT p.id, UNIX_TIMESTAMP(p.time) AS tstamp, p.user_id, p.track_id, $query = "SELECT p.id, UNIX_TIMESTAMP(p.time) AS tstamp, p.user_id, p.track_id,
p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider, p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider,
p.comment, p.image_id, u.login, t.name p.comment, p.image_id, u.login, t.name
FROM `" . self::db()->table('positions') . "` p FROM " . self::db()->table('positions') . " p
LEFT JOIN `" . self::db()->table('users') . "` u ON (p.user_id = u.id) LEFT JOIN " . self::db()->table('users') . " u ON (p.user_id = u.id)
LEFT JOIN `" . self::db()->table('tracks') . "` t ON (p.track_id = t.id) LEFT JOIN " . self::db()->table('tracks') . " t ON (p.track_id = t.id)
$where $where
ORDER BY p.time, p.id"; ORDER BY p.time, p.id";
$result = self::db()->query($query); try {
if ($result === false) { $positionsArr = [];
return false; $result = self::db()->query($query);
while ($row = $result->fetch()) {
$positionsArr[] = self::rowToObject($row);
}
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$positionsArr = [];
while ($row = $result->fetch_assoc()) {
$positionsArr[] = self::rowToObject($row);
}
$result->close();
return $positionsArr; return $positionsArr;
} }
@ -274,27 +285,32 @@
* Fill class properties with database query result * Fill class properties with database query result
* *
* @param string $query Query * @param string $query Query
* @param array|null $bindParams Optional array of bind parameters (types, params) * @param array|null $params Optional array of bind parameters
* @throws PDOException
*/ */
private function loadWithQuery($query, $bindParams = NULL) { private function loadWithQuery($query, $params = NULL) {
$stmt = self::db()->prepare($query); $stmt = self::db()->prepare($query);
if (is_array($bindParams)) { $stmt->execute($params);
$params = [];
foreach ($bindParams as &$value) { $stmt->bindColumn('id', $this->id);
$params[] =& $value; $stmt->bindColumn('tstamp', $this->timestamp);
} $stmt->bindColumn('user_id', $this->userId);
call_user_func_array([ $stmt, 'bind_param' ], $params); $stmt->bindColumn('track_id', $this->trackId);
} $stmt->bindColumn('latitude', $this->latitude);
if ($stmt->execute()) { $stmt->bindColumn('longitude', $this->longitude);
$stmt->bind_result($this->id, $this->timestamp, $this->userId, $this->trackId, $stmt->bindColumn('altitude', $this->altitude);
$this->latitude, $this->longitude, $this->altitude, $this->speed, $stmt->bindColumn('speed', $this->speed);
$this->bearing, $this->accuracy, $this->provider, $stmt->bindColumn('bearing', $this->bearing);
$this->comment, $this->imageId, $this->userLogin, $this->trackName); $stmt->bindColumn('accuracy', $this->accuracy);
if ($stmt->fetch()) { $stmt->bindColumn('provider', $this->provider);
$this->isValid = true; $stmt->bindColumn('comment', $this->comment);
} $stmt->bindColumn('image_id', $this->imageId);
} $stmt->bindColumn('login', $this->userLogin);
$stmt->close(); $stmt->bindColumn('name', $this->trackName);
$stmt->fetch(PDO::FETCH_BOUND);
$this->isValid = true;
$stmt = null;
} }
} }

View File

@ -41,15 +41,20 @@
public function __construct($trackId = NULL) { public function __construct($trackId = NULL) {
if (!empty($trackId)) { if (!empty($trackId)) {
$query = "SELECT id, user_id, name, comment FROM `" . self::db()->table('tracks') . "` WHERE id = ? LIMIT 1"; try {
$stmt = self::db()->prepare($query); $query = "SELECT id, user_id, name, comment FROM " . self::db()->table('tracks') . " WHERE id = ? LIMIT 1";
$stmt->bind_param('i', $trackId); $stmt = self::db()->prepare($query);
$stmt->execute(); $stmt->execute([$trackId]);
$stmt->bind_result($this->id, $this->userId, $this->name, $this->comment); $stmt->bindColumn('id', $this->id);
if ($stmt->fetch()) { $stmt->bindColumn('user_id', $this->userId);
$stmt->bindColumn('name', $this->name);
$stmt->bindColumn('comment', $this->comment);
$stmt->fetch();
$this->isValid = true; $this->isValid = true;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
} }
@ -77,14 +82,17 @@
public static function add($userId, $name, $comment = NULL) { public static function add($userId, $name, $comment = NULL) {
$trackId = false; $trackId = false;
if (!empty($userId) && !empty($name)) { if (!empty($userId) && !empty($name)) {
$query = "INSERT INTO `" . self::db()->table('tracks') . "` (user_id, name, comment) VALUES (?, ?, ?)"; try {
$stmt = self::db()->prepare($query); $table = self::db()->table('tracks');
$stmt->bind_param('iss', $userId, $name, $comment); $query = "INSERT INTO $table (user_id, name, comment) VALUES (?, ?, ?)";
$stmt->execute(); $stmt = self::db()->prepare($query);
if (!self::db()->error && !$stmt->errno) { $params = [ $userId, $name, $comment ];
$trackId = self::db()->insert_id; $stmt->execute($params);
$trackId = self::db()->lastInsertId("${table}_id_seq");
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
return $trackId; return $trackId;
} }
@ -125,19 +133,20 @@
return false; return false;
} }
// delete track metadata // delete track metadata
$query = "DELETE FROM `" . self::db()->table('tracks') . "` WHERE id = ?"; try {
$stmt = self::db()->prepare($query); $query = "DELETE FROM " . self::db()->table('tracks') . " WHERE id = ?";
$stmt->bind_param('i', $this->id); $stmt = self::db()->prepare($query);
$stmt->execute(); $stmt->execute([ $this->id ]);
if (!self::db()->error && !$stmt->errno) {
$ret = true; $ret = true;
$this->id = NULL; $this->id = NULL;
$this->userId = NULL; $this->userId = NULL;
$this->name = NULL; $this->name = NULL;
$this->comment = NULL; $this->comment = NULL;
$this->isValid = false; $this->isValid = false;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
return $ret; return $ret;
} }
@ -155,16 +164,18 @@
if (is_null($comment)) { $comment = $this->comment; } if (is_null($comment)) { $comment = $this->comment; }
if ($comment == "") { $comment = NULL; } if ($comment == "") { $comment = NULL; }
if ($this->isValid) { if ($this->isValid) {
$query = "UPDATE `" . self::db()->table('tracks') . "` SET name = ?, comment = ? WHERE id = ?"; try {
$stmt = self::db()->prepare($query); $query = "UPDATE " . self::db()->table('tracks') . " SET name = ?, comment = ? WHERE id = ?";
$stmt->bind_param('ssi', $name, $comment, $this->id); $stmt = self::db()->prepare($query);
$stmt->execute(); $params = [ $name, $comment, $this->id ];
if (!self::db()->error && !$stmt->errno) { $stmt->execute($params);
$ret = true; $ret = true;
$this->name = $name; $this->name = $name;
$this->comment = $comment; $this->comment = $comment;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
return $ret; return $ret;
} }
@ -181,14 +192,15 @@
// remove all positions // remove all positions
if (uPosition::deleteAll($userId) === true) { if (uPosition::deleteAll($userId) === true) {
// remove all tracks // remove all tracks
$query = "DELETE FROM `" . self::db()->table('tracks') . "` WHERE user_id = ?"; try {
$stmt = self::db()->prepare($query); $query = "DELETE FROM " . self::db()->table('tracks') . " WHERE user_id = ?";
$stmt->bind_param('i', $userId); $stmt = self::db()->prepare($query);
$stmt->execute(); $stmt->execute([ $userId ]);
if (!self::db()->error && !$stmt->errno) {
$ret = true; $ret = true;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
} }
@ -203,20 +215,22 @@
*/ */
public static function getAll($userId = NULL) { public static function getAll($userId = NULL) {
if (!empty($userId)) { if (!empty($userId)) {
$where = "WHERE user_id='" . self::db()->real_escape_string($userId) ."'"; $where = "WHERE user_id=" . self::db()->quote($userId);
} else { } else {
$where = ""; $where = "";
} }
$query = "SELECT id, user_id, name, comment FROM `" . self::db()->table('tracks') . "` $where ORDER BY id DESC"; $query = "SELECT id, user_id, name, comment FROM " . self::db()->table('tracks') . " $where ORDER BY id DESC";
$result = self::db()->query($query); try {
if ($result === false) { $result = self::db()->query($query);
return false; $trackArr = [];
while ($row = $result->fetch()) {
$trackArr[] = self::rowToObject($row);
}
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
$trackArr = false;
} }
$trackArr = [];
while ($row = $result->fetch_assoc()) {
$trackArr[] = self::rowToObject($row);
}
$result->close();
return $trackArr; return $trackArr;
} }

View File

@ -43,15 +43,19 @@
*/ */
public function __construct($login = NULL) { public function __construct($login = NULL) {
if (!empty($login)) { if (!empty($login)) {
$sql = "SELECT id, login, password FROM `" . self::db()->table('users') . "` WHERE login = ? LIMIT 1"; try {
$stmt = self::db()->prepare($sql); $query = "SELECT id, login, password FROM " . self::db()->table('users') . " WHERE login = ? LIMIT 1";
$stmt->bind_param('s', $login); $stmt = self::db()->prepare($query);
$stmt->execute(); $stmt->execute([ $login ]);
$stmt->bind_result($this->id, $this->login, $this->hash); $stmt->bindColumn('id', $this->id);
if ($stmt->fetch()) { $stmt->bindColumn('login', $this->login);
$stmt->bindColumn('password', $this->hash);
$stmt->fetch();
$this->isValid = true; $this->isValid = true;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
$this->isAdmin = self::isAdmin($this->login); $this->isAdmin = self::isAdmin($this->login);
} }
} }
@ -79,14 +83,16 @@
$userid = false; $userid = false;
if (!empty($login) && !empty($pass) && self::validPassStrength($pass)) { if (!empty($login) && !empty($pass) && self::validPassStrength($pass)) {
$hash = password_hash($pass, PASSWORD_DEFAULT); $hash = password_hash($pass, PASSWORD_DEFAULT);
$sql = "INSERT INTO `" . self::db()->table('users') . "` (login, password) VALUES (?, ?)"; $table = self::db()->table('users');
$stmt = self::db()->prepare($sql); try {
$stmt->bind_param('ss', $login, $hash); $query = "INSERT INTO $table (login, password) VALUES (?, ?)";
$stmt->execute(); $stmt = self::db()->prepare($query);
if (!self::db()->error && !$stmt->errno) { $stmt->execute([ $login, $hash ]);
$userid = self::db()->insert_id; $userid = self::db()->lastInsertId("${table}_id_seq");
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
return $userid; return $userid;
} }
@ -105,19 +111,20 @@
return false; return false;
} }
// remove user // remove user
$sql = "DELETE FROM `" . self::db()->table('users') . "` WHERE id = ?"; try {
$stmt = self::db()->prepare($sql); $query = "DELETE FROM " . self::db()->table('users') . " WHERE id = ?";
$stmt->bind_param('i', $this->id); $stmt = self::db()->prepare($query);
$stmt->execute(); $stmt->execute([ $this->id ]);
if (!self::db()->error && !$stmt->errno) {
$ret = true; $ret = true;
$this->id = NULL; $this->id = NULL;
$this->login = NULL; $this->login = NULL;
$this->hash = NULL; $this->hash = NULL;
$this->isValid = false; $this->isValid = false;
$this->isAdmin = false; $this->isAdmin = false;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
return $ret; return $ret;
} }
@ -132,14 +139,15 @@
$ret = false; $ret = false;
if (!empty($this->login) && !empty($pass) && self::validPassStrength($pass)) { if (!empty($this->login) && !empty($pass) && self::validPassStrength($pass)) {
$hash = password_hash($pass, PASSWORD_DEFAULT); $hash = password_hash($pass, PASSWORD_DEFAULT);
$sql = "UPDATE `" . self::db()->table('users') . "` SET password = ? WHERE login = ?"; try {
$stmt = self::db()->prepare($sql); $query = "UPDATE " . self::db()->table('users') . " SET password = ? WHERE login = ?";
$stmt->bind_param('ss', $hash, $this->login); $stmt = self::db()->prepare($query);
$stmt->execute(); $stmt->execute([ $hash, $this->login ]);
if (!self::db()->error && !$stmt->errno) {
$ret = true; $ret = true;
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
} }
$stmt->close();
} }
return $ret; return $ret;
} }
@ -193,16 +201,18 @@
* @return array|bool Array of uUser users, false on error * @return array|bool Array of uUser users, false on error
*/ */
public static function getAll() { public static function getAll() {
$query = "SELECT id, login, password FROM `" . self::db()->table('users') . "` ORDER BY login"; try {
$result = self::db()->query($query); $query = "SELECT id, login, password FROM " . self::db()->table('users') . " ORDER BY login";
if ($result === false) { $result = self::db()->query($query);
return false; $userArr = [];
while ($row = $result->fetch()) {
$userArr[] = self::rowToObject($row);
}
} catch (PDOException $e) {
// TODO: handle exception
throw $e;
$userArr = false;
} }
$userArr = [];
while ($row = $result->fetch_assoc()) {
$userArr[] = self::rowToObject($row);
}
$result->close();
return $userArr; return $userArr;
} }

View File

@ -18,7 +18,7 @@
*/ */
// This script is disabled by default. Change below to true before running. // This script is disabled by default. Change below to true before running.
$enabled = false; $enabled = true;
/* -------------------------------------------- */ /* -------------------------------------------- */
@ -43,70 +43,27 @@ $tUsers = $prefix . "users";
$messages = []; $messages = [];
switch ($command) { switch ($command) {
case "setup": case "setup":
$queries = [];
// positions
$queries[] = "DROP TABLE IF EXISTS `$tPositions`";
$queries[] = "CREATE TABLE `$tPositions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
`track_id` int(11) NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`altitude` double DEFAULT NULL,
`speed` double DEFAULT NULL,
`bearing` double DEFAULT NULL,
`accuracy` int(11) DEFAULT NULL,
`provider` varchar(100) DEFAULT NULL,
`comment` varchar(255) DEFAULT NULL,
`image_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_trip_id` (`track_id`),
KEY `index_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
// tracks
$queries[] = "DROP TABLE IF EXISTS `$tTracks`";
$queries[] = "CREATE TABLE `$tTracks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`comment` varchar(1024) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
// users
$queries[] = "DROP TABLE IF EXISTS `$tUsers`";
$queries[] = "CREATE TABLE `$tUsers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(15) CHARACTER SET latin1 NOT NULL,
`password` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `login` (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
$error = false; $error = false;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try { try {
$mysqli = new mysqli(uConfig::$dbhost, uConfig::$dbuser, uConfig::$dbpass, uConfig::$dbname); $db = new PDO(uConfig::$dbdsn, uConfig::$dbuser, uConfig::$dbpass);
} catch (mysqli_sql_exception $e ) { } catch (PDOException $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>");
$messages[] = $langSetup["checkdbsettings"]; $messages[] = $langSetup["checkdbsettings"];
break; break;
} }
try { try {
$mysqli->set_charset('utf8'); $queries = getQueries($db);
foreach ($queries as $query) { foreach ($queries as $query) {
$mysqli->query($query); $db->query($query);
} }
} catch (mysqli_sql_exception $e) { } catch (PDOException $e) {
$messages[] = "<span class=\"warn\">{$langSetup["dbqueryfailed"]}</span>"; $messages[] = "<span class=\"warn\">{$langSetup["dbqueryfailed"]}</span>";
$messages[] = sprintf($langSetup["serversaid"], "<b>" . $e->getMessage() . "</b>"); $messages[] = sprintf($langSetup["serversaid"], "<b>" . $e->getMessage() . "</b>");
$error = true; $error = true;
} }
$mysqli->close(); $db = null;
if (!$error) { if (!$error) {
$messages[] = "<span class=\"ok\">{$langSetup["dbtablessuccess"]}</span>"; $messages[] = "<span class=\"ok\">{$langSetup["dbtablessuccess"]}</span>";
$messages[] = $langSetup["setupuser"]; $messages[] = $langSetup["setupuser"];
@ -169,6 +126,146 @@ switch ($command) {
break; break;
} }
function getQueries($db) {
$driver = $db->getAttribute(PDO::ATTR_DRIVER_NAME);
$queries = [];
switch($driver) {
case "mysql":
// positions
$queries[] = "DROP TABLE IF EXISTS `$tPositions`";
$queries[] = "CREATE TABLE `$tPositions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
`track_id` int(11) NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`altitude` double DEFAULT NULL,
`speed` double DEFAULT NULL,
`bearing` double DEFAULT NULL,
`accuracy` int(11) DEFAULT NULL,
`provider` varchar(100) DEFAULT NULL,
`comment` varchar(255) DEFAULT NULL,
`image_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_trip_id` (`track_id`),
KEY `index_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
// tracks
$queries[] = "DROP TABLE IF EXISTS `$tTracks`";
$queries[] = "CREATE TABLE `$tTracks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`comment` varchar(1024) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
// users
$queries[] = "DROP TABLE IF EXISTS `$tUsers`";
$queries[] = "CREATE TABLE `$tUsers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(15) CHARACTER SET latin1 NOT NULL,
`password` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `login` (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
break;
case "pgsql":
// positions
$queries[] = "DROP TABLE IF EXISTS $tPositions";
$queries[] = "CREATE TABLE $tPositions (
id SERIAL PRIMARY KEY,
time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
user_id INT NOT NULL,
track_id INT NOT NULL,
latitude DOUBLE PRECISION NOT NULL,
longitude DOUBLE PRECISION NOT NULL,
altitude DOUBLE PRECISION DEFAULT NULL,
speed DOUBLE PRECISION DEFAULT NULL,
bearing DOUBLE PRECISION DEFAULT NULL,
accuracy INT DEFAULT NULL,
provider VARCHAR(100) DEFAULT NULL,
comment VARCHAR(255) DEFAULT NULL,
image_id INT DEFAULT NULL
)";
$queries[] = "CREATE INDEX index_trip_id ON $tPositions (track_id)";
$queries[] = "CREATE INDEX index_user_id ON $tPositions (user_id)";
// tracks
$queries[] = "DROP TABLE IF EXISTS $tTracks";
$queries[] = "CREATE TABLE $tTracks (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL,
name VARCHAR(255) DEFAULT NULL,
comment VARCHAR(1024) DEFAULT NULL
)";
$queries[] = "CREATE INDEX user_id ON $tTracks (user_id)";
// users
$queries[] = "DROP TABLE IF EXISTS $tUsers";
$queries[] = "CREATE TABLE $tUsers (
id SERIAL PRIMARY KEY,
login varchar(15) NOT NULL UNIQUE,
password varchar(255) NOT NULL DEFAULT ''
)";
break;
case "sqlite":
// positions
$queries[] = "DROP TABLE IF EXISTS `$tPositions`";
$queries[] = "CREATE TABLE `$tPositions` (
`id` INTEGER NOT NULL ,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` INTEGER NOT NULL,
`track_id` INTEGER NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`altitude` double DEFAULT NULL,
`speed` double DEFAULT NULL,
`bearing` double DEFAULT NULL,
`accuracy` INTEGER DEFAULT NULL,
`provider` TEXT DEFAULT NULL,
`comment` TEXT DEFAULT NULL,
`image_id` INTEGER DEFAULT NULL,
PRIMARY KEY (`id`)
)";
$queries[] = "CREATE INDEX `positions_index_trip_id` ON `$tPositions` (`track_id`)";
$queries[] = "CREATE INDEX `positions_index_user_id` ON `$tPositions` (`user_id`)";
// tracks
$queries[] = "DROP TABLE IF EXISTS `$tTracks`";
$queries[] = "CREATE TABLE `$tTracks` (
`id` INTEGER NOT NULL,
`user_id` INTEGER NOT NULL,
`name` TEXT DEFAULT NULL,
`comment` TEXT DEFAULT NULL,
PRIMARY KEY (`id`)
)";
$queries[] = "CREATE INDEX `tracks_user_id` ON `$tTracks` (`user_id`)";
// users
$queries[] = "DROP TABLE IF EXISTS `$tUsers`";
$queries[] = "CREATE TABLE `$tUsers` (
`id` INTEGER NOT NULL ,
`login` TEXT NOT NULL,
`password` TEXT NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)";
$queries[] = "CREATE UNIQUE INDEX `users_login` ON `$tUsers` (`login`)";
break;
default:
throw InvalidArgumentException("Driver not supported");
}
}
?> ?>
<!DOCTYPE html> <!DOCTYPE html>