ulogger-server/helpers/position.php

409 lines
14 KiB
PHP
Raw Normal View History

<?php
/* μlogger
*
* Copyright(C) 2017 Bartek Fabiszewski (www.fabiszewski.net)
*
* This is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
2019-11-16 12:43:47 +01:00
require_once(ROOT_DIR . "/helpers/db.php");
2019-07-12 21:50:21 +02:00
require_once(ROOT_DIR . "/helpers/track.php");
require_once(ROOT_DIR . "/helpers/upload.php");
2017-04-09 23:35:55 +02:00
/**
* Positions handling
*/
class uPosition {
2019-01-24 19:07:41 +01:00
/** @param int Position id */
public $id;
2019-01-24 19:07:41 +01:00
/** @param int Unix time stamp */
2017-05-22 13:39:40 +02:00
public $timestamp;
2019-01-24 19:07:41 +01:00
/** @param int User id */
public $userId;
2019-01-24 19:07:41 +01:00
/** @param String User login */
public $userLogin;
2019-01-24 19:07:41 +01:00
/** @param int Track id */
public $trackId;
2019-01-24 19:07:41 +01:00
/** @param String Track name */
public $trackName;
2019-01-24 19:07:41 +01:00
/** @param double Latitude */
public $latitude;
2019-01-24 19:07:41 +01:00
/** @param double Longitude */
public $longitude;
2019-01-24 19:07:41 +01:00
/** @param double Altitude */
public $altitude;
2019-01-24 19:07:41 +01:00
/** @param double Speed */
public $speed;
2019-01-24 19:07:41 +01:00
/** @param double Bearing */
public $bearing;
2019-01-24 19:07:41 +01:00
/** @param int Accuracy */
public $accuracy;
2019-01-24 19:07:41 +01:00
/** @param String Provider */
public $provider;
2019-01-24 19:07:41 +01:00
/** @param String Comment */
2019-07-12 21:50:21 +02:00
public $comment;
/** @param String Image path */
public $image;
public $isValid = false;
2017-04-09 23:35:55 +02:00
/**
* Constructor
* @param integer $positionId Position id
*/
public function __construct($positionId = NULL) {
if (!empty($positionId)) {
2019-01-24 19:07:41 +01:00
$query = "SELECT p.id, " . self::db()->unix_timestamp('p.time') . " AS tstamp, p.user_id, p.track_id,
2017-04-09 23:35:55 +02:00
p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider,
2019-07-12 21:50:21 +02:00
p.comment, p.image, u.login, t.name
2019-01-23 12:23:25 +01:00
FROM " . self::db()->table('positions') . " p
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)
WHERE id = ? LIMIT 1";
2019-01-23 12:23:25 +01:00
$params = [ $positionId ];
try {
$this->loadWithQuery($query, $params);
} catch (PDOException $e) {
// TODO: handle exception
2019-01-24 19:07:41 +01:00
syslog(LOG_ERR, $e->getMessage());
2019-01-23 12:23:25 +01:00
}
}
}
/**
* Get db instance
*
* @return uDb instance
*/
private static function db() {
2019-05-15 11:48:24 +02:00
return uDb::getInstance();
}
2017-04-09 23:35:55 +02:00
/**
* Add position
*
* @param int $userId
* @param int $trackId
2019-01-24 19:07:41 +01:00
* @param int $timestamp Unix time stamp
2017-04-09 23:35:55 +02:00
* @param double $lat
* @param double $lon
* @param double $altitude Optional
* @param double $speed Optional
* @param double $bearing Optional
* @param int $accuracy Optional
* @param string $provider Optional
* @param string $comment Optional
2019-07-12 21:50:21 +02:00
* @param int $image Optional
2017-04-09 23:35:55 +02:00
* @return int|bool New position id in database, false on error
*/
public static function add($userId, $trackId, $timestamp, $lat, $lon,
$altitude = NULL, $speed = NULL, $bearing = NULL, $accuracy = NULL,
2019-07-12 21:50:21 +02:00
$provider = NULL, $comment = NULL, $image = NULL) {
$positionId = false;
if (is_numeric($lat) && is_numeric($lon) && is_numeric($timestamp) && is_numeric($userId) && is_numeric($trackId)) {
2017-04-24 23:29:56 +02:00
$track = new uTrack($trackId);
if ($track->isValid && $track->userId == $userId) {
2019-01-23 12:23:25 +01:00
try {
$table = self::db()->table('positions');
$query = "INSERT INTO $table
(user_id, track_id,
2019-07-12 21:50:21 +02:00
time, latitude, longitude, altitude, speed, bearing, accuracy, provider, comment, image)
2019-01-24 19:07:41 +01:00
VALUES (?, ?, " . self::db()->from_unixtime('?') . ", ?, ?, ?, ?, ?, ?, ?, ?, ?)";
2019-01-23 12:23:25 +01:00
$stmt = self::db()->prepare($query);
$params = [ $userId, $trackId,
2019-07-12 21:50:21 +02:00
$timestamp, $lat, $lon, $altitude, $speed, $bearing, $accuracy, $provider, $comment, $image ];
2019-01-23 12:23:25 +01:00
$stmt->execute($params);
$positionId = self::db()->lastInsertId("${table}_id_seq");
} catch (PDOException $e) {
// TODO: handle error
2019-01-24 19:07:41 +01:00
syslog(LOG_ERR, $e->getMessage());
2017-04-24 23:29:56 +02:00
}
}
}
return $positionId;
}
2017-04-12 20:16:39 +02:00
/**
2017-04-14 17:24:09 +02:00
* Delete all user's positions, optionally limit to given track
2017-04-12 20:16:39 +02:00
*
2017-04-14 17:24:09 +02:00
* @param int $userId User id
* @param int $trackId Optional track id
2017-04-12 20:16:39 +02:00
* @return bool True if success, false otherwise
*/
public static function deleteAll($userId, $trackId = NULL) {
2017-04-12 20:16:39 +02:00
$ret = false;
if (!empty($userId)) {
2017-04-14 17:24:09 +02:00
$args = [];
$where = "WHERE user_id = ?";
2019-01-23 12:23:25 +01:00
$args[] = $userId;
2017-04-14 17:24:09 +02:00
if (!empty($trackId)) {
$where .= " AND track_id = ?";
2019-01-23 12:23:25 +01:00
$args[] = $trackId;
2017-04-14 17:24:09 +02:00
}
2019-07-12 21:50:21 +02:00
self::removeImages($userId, $trackId);
2019-01-23 12:23:25 +01:00
try {
$query = "DELETE FROM " . self::db()->table('positions') . " $where";
$stmt = self::db()->prepare($query);
$stmt->execute($args);
2017-04-12 20:16:39 +02:00
$ret = true;
2019-01-23 12:23:25 +01:00
} catch (PDOException $e) {
// TODO: handle exception
2019-01-24 19:07:41 +01:00
syslog(LOG_ERR, $e->getMessage());
2017-04-12 20:16:39 +02:00
}
}
return $ret;
}
2017-04-09 23:35:55 +02:00
/**
* Get last position data from database
2017-04-09 23:35:55 +02:00
* (for given user if specified)
*
* @param int $userId Optional user id
* @return uPosition Position
2017-04-09 23:35:55 +02:00
*/
public static function getLast($userId = NULL) {
if (!empty($userId)) {
$where = "WHERE p.user_id = ?";
2019-01-23 12:23:25 +01:00
$params = [ $userId ];
} else {
$where = "";
$params = NULL;
}
2019-01-24 19:07:41 +01:00
$query = "SELECT p.id, " . self::db()->unix_timestamp('p.time') . " AS tstamp, p.user_id, p.track_id,
2017-04-09 23:35:55 +02:00
p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider,
2019-07-12 21:50:21 +02:00
p.comment, p.image, u.login, t.name
2019-01-23 12:23:25 +01:00
FROM " . self::db()->table('positions') . " p
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)
$where
2017-05-22 11:25:02 +02:00
ORDER BY p.time DESC, p.id DESC LIMIT 1";
$position = new uPosition();
2019-01-23 12:23:25 +01:00
try {
$position->loadWithQuery($query, $params);
} catch (PDOException $e) {
// TODO: handle exception
2019-01-24 19:07:41 +01:00
syslog(LOG_ERR, $e->getMessage());
2019-01-23 12:23:25 +01:00
}
return $position;
}
/**
* Get last positions for all users
*
* @return array|bool Array of uPosition positions, false on error
*/
public static function getLastAllUsers() {
$query = "SELECT p.id, " . self::db()->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,
2019-07-12 21:50:21 +02:00
p.comment, p.image, u.login, t.name
FROM " . self::db()->table('positions') . " p
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)
WHERE p.id = (
SELECT p2.id FROM " . self::db()->table('positions') . " p2
WHERE p2.user_id = p.user_id
ORDER BY p2.time DESC, p2.id DESC
LIMIT 1
)";
$positionsArr = [];
try {
$result = self::db()->query($query);
while ($row = $result->fetch()) {
$positionsArr[] = self::rowToObject($row);
}
} catch (PDOException $e) {
// TODO: handle exception
syslog(LOG_ERR, $e->getMessage());
2019-07-12 21:50:21 +02:00
$positionsArr = false;
}
return $positionsArr;
}
2019-05-15 11:32:36 +02:00
/**
* Get array of all positions
*
* @param int $userId Optional limit to given user id
* @param int $trackId Optional limit to given track id
* @param int $afterId Optional limit to positions with id greater then given id
2019-07-12 21:50:21 +02:00
* @param array $rules Optional rules
* @return uPosition[]|bool Array of uPosition positions, false on error
2019-05-15 11:32:36 +02:00
*/
2019-07-12 21:50:21 +02:00
public static function getAll($userId = NULL, $trackId = NULL, $afterId = NULL, $rules = []) {
if (!empty($userId)) {
2019-01-23 12:23:25 +01:00
$rules[] = "p.user_id = " . self::db()->quote($userId);
}
if (!empty($trackId)) {
2019-01-23 12:23:25 +01:00
$rules[] = "p.track_id = " . self::db()->quote($trackId);
2017-04-09 23:35:55 +02:00
}
2019-07-12 21:50:21 +02:00
if (!empty($afterId)) {
2019-05-15 11:32:36 +02:00
$rules[] = "p.id > " . self::db()->quote($afterId);
}
if (!empty($rules)) {
$where = "WHERE " . implode(" AND ", $rules);
2017-04-09 23:35:55 +02:00
} else {
$where = "";
}
2019-01-24 19:07:41 +01:00
$query = "SELECT p.id, " . self::db()->unix_timestamp('p.time') . " AS tstamp, p.user_id, p.track_id,
2017-04-09 23:35:55 +02:00
p.latitude, p.longitude, p.altitude, p.speed, p.bearing, p.accuracy, p.provider,
2019-07-12 21:50:21 +02:00
p.comment, p.image, u.login, t.name
2019-01-23 12:23:25 +01:00
FROM " . self::db()->table('positions') . " p
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)
2017-04-09 23:35:55 +02:00
$where
ORDER BY p.time, p.id";
$positionsArr = [];
2019-01-23 12:23:25 +01:00
try {
$result = self::db()->query($query);
while ($row = $result->fetch()) {
$positionsArr[] = self::rowToObject($row);
}
} catch (PDOException $e) {
// TODO: handle exception
2019-01-24 19:07:41 +01:00
syslog(LOG_ERR, $e->getMessage());
2019-07-12 21:50:21 +02:00
$positionsArr = false;
}
return $positionsArr;
}
2019-07-12 21:50:21 +02:00
/**
* Get array of all positions with image
*
* @param int $userId Optional limit to given user id
* @param int $trackId Optional limit to given track id
* @param int $afterId Optional limit to positions with id greater then given id
* @param array $rules Optional rules
* @return uPosition[]|bool Array of uPosition positions, false on error
*/
public static function getAllWithImage($userId = NULL, $trackId = NULL, $afterId = NULL, $rules = []) {
$rules[] = "p.image IS NOT NULL";
return self::getAll($userId, $trackId, $afterId, $rules);
}
/**
* Delete all user's uploads, optionally limit to given track
*
* @param int $userId User id
* @param int $trackId Optional track id
* @return bool True if success, false otherwise
*/
public static function removeImages($userId, $trackId = NULL) {
if (($positions = uPosition::getAllWithImage($userId, $trackId)) !== false) {
/** @var uUpload $position */
foreach ($positions as $position) {
try {
$query = "UPDATE " . self::db()->table('positions') . "
SET image = NULL WHERE id = ?";
$stmt = self::db()->prepare($query);
$stmt->execute([ $position->id ]);
// ignore unlink errors
uUpload::delete($position->image);
} catch (PDOException $e) {
// TODO: handle exception
syslog(LOG_ERR, $e->getMessage());
return false;
}
}
}
return true;
}
2017-04-09 23:35:55 +02:00
/**
* Calculate distance to target point using haversine formula
*
* @param uPosition $target Target position
* @return int Distance in meters
*/
public function distanceTo($target) {
$lat1 = deg2rad($this->latitude);
$lon1 = deg2rad($this->longitude);
$lat2 = deg2rad($target->latitude);
$lon2 = deg2rad($target->longitude);
$latD = $lat2 - $lat1;
$lonD = $lon2 - $lon1;
2019-11-16 12:43:47 +01:00
$bearing = 2 * asin(sqrt((sin($latD / 2) ** 2) + cos($lat1) * cos($lat2) * (sin($lonD / 2) ** 2)));
return $bearing * 6371000;
}
2017-04-09 23:35:55 +02:00
/**
* Calculate time elapsed since target point
*
* @param uPosition $target Target position
* @return int Number of seconds
*/
public function secondsTo($target) {
2017-05-22 13:39:40 +02:00
return $this->timestamp - $target->timestamp;
}
2017-04-09 23:35:55 +02:00
/**
* Convert database row to uPosition
*
* @param array $row Row
* @return uPosition Position
*/
private static function rowToObject($row) {
$position = new uPosition();
$position->id = $row['id'];
2017-05-22 13:39:40 +02:00
$position->timestamp = $row['tstamp'];
$position->userId = $row['user_id'];
$position->userLogin = $row['login'];
$position->trackId = $row['track_id'];
$position->trackName = $row['name'];
$position->latitude = $row['latitude'];
$position->longitude = $row['longitude'];
$position->altitude = $row['altitude'];
$position->speed = $row['speed'];
$position->bearing = $row['bearing'];
$position->accuracy = $row['accuracy'];
$position->provider = $row['provider'];
$position->comment = $row['comment'];
2019-07-12 21:50:21 +02:00
$position->image = $row['image'];
$position->isValid = true;
return $position;
}
2017-04-09 23:35:55 +02:00
/**
* Fill class properties with database query result
*
* @param string $query Query
2019-01-23 12:23:25 +01:00
* @param array|null $params Optional array of bind parameters
* @throws PDOException
2017-04-09 23:35:55 +02:00
*/
2019-01-23 12:23:25 +01:00
private function loadWithQuery($query, $params = NULL) {
$stmt = self::db()->prepare($query);
2019-01-23 12:23:25 +01:00
$stmt->execute($params);
2019-01-24 19:07:41 +01:00
$stmt->bindColumn('id', $this->id, PDO::PARAM_INT);
$stmt->bindColumn('tstamp', $this->timestamp, PDO::PARAM_INT);
$stmt->bindColumn('user_id', $this->userId, PDO::PARAM_INT);
$stmt->bindColumn('track_id', $this->trackId, PDO::PARAM_INT);
2019-01-23 12:23:25 +01:00
$stmt->bindColumn('latitude', $this->latitude);
$stmt->bindColumn('longitude', $this->longitude);
$stmt->bindColumn('altitude', $this->altitude);
$stmt->bindColumn('speed', $this->speed);
$stmt->bindColumn('bearing', $this->bearing);
2019-01-24 19:07:41 +01:00
$stmt->bindColumn('accuracy', $this->accuracy, PDO::PARAM_INT);
2019-01-23 12:23:25 +01:00
$stmt->bindColumn('provider', $this->provider);
$stmt->bindColumn('comment', $this->comment);
2019-07-12 21:50:21 +02:00
$stmt->bindColumn('image', $this->image);
2019-01-23 12:23:25 +01:00
$stmt->bindColumn('login', $this->userLogin);
$stmt->bindColumn('name', $this->trackName);
2019-01-24 19:07:41 +01:00
if ($stmt->fetch(PDO::FETCH_BOUND)) {
$this->isValid = true;
}
}
2017-04-09 23:35:55 +02:00
}
?>