1
0

Separated SQL stuff from main code.

This commit is contained in:
Markus Birth 2018-04-22 17:48:25 +02:00
parent baf361074d
commit 333256d4c7
Signed by: mbirth
GPG Key ID: A9928D7A098C3A9A
5 changed files with 282 additions and 151 deletions

View File

@ -4,13 +4,14 @@
setlocale(LC_TIME, "fr_FR");
// MySQL / MariaDB
$_config['sql_type'] = 'mysql';
$_config['sql_host'] = '';
$_config['sql_user'] = '';
$_config['sql_pass'] = '';
$_config['sql_db'] = '';
$_config['sql_prefix'] = '';
$_config['default_accuracy'] = 1000; //meters
$_config['default_trackerID'] = 'all';

47
lib/db/AbstractDb.php Normal file
View File

@ -0,0 +1,47 @@
<?php
class AbstractDb
{
public function isEpochExisting($trackerId, $epoch)
{
}
public function addLocation(
$accuracy,
$altitude,
$battery_level,
$heading,
$description,
$event,
$latitude,
$longitude,
$radius,
$trig,
$tracker_id,
$epoch,
$vertical_accuracy,
$velocity,
$pressure,
$connection,
$place_id,
$osm_id
) {
}
public function getMarkers($time_from, $time_to, $min_accuracy = 1000)
{
}
public function getMarkerLatLon($epoch)
{
}
public function deleteMarker($epoch)
{
}
public function updateLocationData($epoch, $latitude, $longitude, $location_name, $place_id, $osm_id)
{
}
}

139
lib/db/MySql.php Normal file
View File

@ -0,0 +1,139 @@
<?php
require_once(__DIR__ . '/AbstractDb.php');
class MySql extends AbstractDb
{
/** @var \mysqli $db */
protected $db;
protected $prefix;
public function __construct($db, $hostname = null, $username = null, $password = null, $prefix = '')
{
$this->db = new \mysqli($hostname, $username, $password, $db);
$this->prefix = $prefix;
}
public function isEpochExisting($trackerId, $epoch)
{
$sql = 'SELECT epoch FROM ' . $this->prefix . 'locations WHERE tracker_id = ? AND epoch = ?';
$stmt = $this->db->prepare($sql);
$stmt->bind_param('si', $trackerId, $epoch);
$stmt->execute();
$stmt->store_result();
return ($stmt->num_rows > 0);
}
public function addLocation(
$accuracy,
$altitude,
$battery_level,
$heading,
$description,
$event,
$latitude,
$longitude,
$radius,
$trig,
$tracker_id,
$epoch,
$vertical_accuracy,
$velocity,
$pressure,
$connection,
$place_id,
$osm_id
) {
$sql = 'INSERT INTO ' . $this->prefix . 'locations (accuracy, altitude, battery_level, heading, description, event, latitude, longitude, radius, trig, tracker_id, epoch, vertical_accuracy, velocity, pressure, connection, place_id, osm_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
$stmt = $this->db->prepare($sql);
$stmt->bind_param('iiiissddissiiidsii', $accuracy, $altitude, $battery_level, $heading, $description, $event, $latitude, $longitude, $radius, $trig, $tracker_id, $epoch, $vertical_accuracy, $velocity, $pressure, $connection, $place_id, $osm_id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
public function getMarkers($time_from, $time_to, $min_accuracy = 1000)
{
$sql = 'SELECT * FROM ' . $this->prefix . 'locations WHERE epoch >= ? AND epoch <= ? AND accuracy < ? AND altitude >=0 ORDER BY tracker_id, epoch ASC';
$stmt = $this->db->prepare($sql);
if (!$stmt) {
return false;
}
$stmt->bind_param('iii', $time_from, $time_to, $min_accuracy);
$stmt->execute();
$result = $stmt->get_result();
$stmt->store_result();
$markers = array();
while ($data = $result->fetch_assoc()) {
// Loop through results here $data[]
$markers[$data['tracker_id']][] = $data;
}
$stmt->close();
return $markers;
}
public function getMarkerLatLon($epoch)
{
$sql = 'SELECT latitude, longitude FROM ' . $this->prefix . 'locations WHERE epoch = ?';
$stmt = $mysqli->prepare($sql);
if (!$stmt) {
return false;
}
$stmt->bind_param('i', $epoch);
if (!$stmt->execute()) {
return false;
}
$stmt->execute();
$result = $stmt->get_result();
$stmt->store_result();
while ($data = $result->fetch_assoc()) {
// Loop through results here $data[]
$marker = $data;
}
return $marker;
}
public function deleteMarker($epoch)
{
$sql = 'DELETE FROM ' . $this->prefix . 'locations WHERE epoch = ?';
$stmt = $this->db->prepare($sql);
if (!$stmt) {
return false;
}
$stmt->bind_param('i', $epoch);
$result = $stmt->execute();
$stmt->close();
return $result;
}
public function updateLocationData($epoch, $latitude, $longitude, $location_name, $place_id, $osm_id)
{
$sql = 'UPDATE ' . $this->prefix . 'locations SET display_name = ?, place_id = ?, osm_id = ? WHERE epoch = ? AND latitude = ? AND longitude = ?';
$stmt = $mysqli->prepare($sql);
if (!$stmt) {
return false;
}
$stmt->bind_param('siiidd', $location_name, $place_id, $osm_id, $epoch, $latitude, $longitude);
$result = $stmt->execute();
$stmt->close();
return $result;
}
}

View File

@ -26,8 +26,17 @@ $data = @json_decode($payload, true);
if ($data['_type'] == 'location') {
# CREATE TABLE locations (dt TIMESTAMP, tid CHAR(2), lat DECIMAL(9,6), lon DECIMAL(9,6));
$mysqli = new mysqli($_config['sql_host'], $_config['sql_user'], $_config['sql_pass'], $_config['sql_db']);
if ($_config['sql_type'] == 'mysql') {
require_once('lib/db/MySql.php');
$sql = new MySql($_config['sql_db'], $_config['sql_host'], $_config['sql_user'], $_config['sql_pass'], $_config['sql_prefix']);
} elseif ($_config['sql_type'] == 'sqlite') {
require_once('lib/db/SQLite.php');
$sql = new SQLite($_config['sql_db']);
} else {
die('Invalid database type: ' . $_config['sql_type']);
}
# CREATE TABLE locations (dt TIMESTAMP, tid CHAR(2), lat DECIMAL(9,6), lon DECIMAL(9,6));
//http://owntracks.org/booklet/tech/json/
//iiiissddissiiidsiis
@ -49,56 +58,47 @@ if ($data['_type'] == 'location') {
if (array_key_exists('conn', $data)) $connection = strval($data['conn']);
$sql = "SELECT epoch FROM ".$_config['sql_prefix']."locations WHERE tracker_id = '$tracker_id' AND epoch = $epoch";
_log("Duplicate SQL = ".$sql);
if ($stmt = $mysqli->prepare($sql)){
$stmt->execute();
$stmt->store_result();
_log("Duplicate SQL : Rows found = ".$stmt->num_rows);
//record only if same data found at same epoch / tracker_id
if (!$sql->isEpochExisting($tracker_id, $epoch)) {
//record only if same data found at same epoch / tracker_id
if($stmt->num_rows == 0) {
$sql = "INSERT INTO ".$_config['sql_prefix']."locations (accuracy, altitude, battery_level, heading, description, event, latitude, longitude, radius, trig, tracker_id, epoch, vertical_accuracy, velocity, pressure, connection, place_id, osm_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('iiiissddissiiidsii', $accuracy, $altitude, $battery_level, $heading, $description, $event, $latitude, $longitude, $radius, $trig, $tracker_id, $epoch, $vertical_accuracy, $velocity, $pressure, $connection, $place_id, $osm_id);
if ($stmt->execute()){
# bind parameters (s = string, i = integer, d = double, b = blob)
http_response_code(200);
$response['msg'] = "OK record saved";
_log("Insert OK");
$result = $sql->addLocation(
$accuracy,
$altitude,
$battery_level,
$heading,
$description,
$event,
$latitude,
$longitude,
$radius,
$trig,
$tracker_id,
$epoch,
$vertical_accuracy,
$velocity,
$pressure,
$connection,
$place_id,
$osm_id
);
}else{
http_response_code(500);
die("Can't write to database : ".$stmt->error);
$response['msg'] = "Can't write to database";
_log("Insert KO - Can't write to database : ".$stmt->error);
}
if ($result) {
http_response_code(200);
$response['msg'] = "OK record saved";
_log("Insert OK");
} else {
http_response_code(500);
die("Can't write to database : ".$stmt->error);
$response['msg'] = "Can't write to database";
_log("Insert KO - Can't write to database : ".$stmt->error);
}
}else{
_log("Duplicate location found for epoc $epoch / tid '$tracker_id' - no insert");
}
$stmt->close();
}else{
http_response_code(500);
die("Can't read from database");
$response['msg'] = "Can't read from database";
_log("Can't read from database");
} else {
_log("Duplicate location found for epoc $epoch / tid '$tracker_id' - no insert");
}
$stmt->close();
}else{
} else {
http_response_code(204);
$response['msg'] = "OK type is not location";
_log("OK type is not location : " . $data['_type']);
@ -109,4 +109,3 @@ $response = array();
print json_encode($response);
fclose($fp);
?>

147
rpc.php
View File

@ -8,9 +8,18 @@
$response = array();
$mysqli = new mysqli($_config['sql_host'], $_config['sql_user'], $_config['sql_pass'], $_config['sql_db']);
if ($_config['sql_type'] == 'mysql') {
require_once('lib/db/MySql.php');
/** @var MySql $sql */
$sql = new MySql($_config['sql_db'], $_config['sql_host'], $_config['sql_user'], $_config['sql_pass'], $_config['sql_prefix']);
} elseif ($_config['sql_type'] == 'sqlite') {
require_once('lib/db/SQLite.php');
/** @var SQLite $sql */
$sql = new SQLite($_config['sql_db']);
} else {
die('Invalid database type: ' . $_config['sql_type']);
}
if (array_key_exists('action', $_REQUEST)) {
if($_REQUEST['action'] === 'getMarkers'){
@ -37,30 +46,16 @@
$time_to = mktime(23, 59, 59, $time_to['tm_mon']+1, $time_to['tm_mday'], $time_to['tm_year']+1900);
//$time_to = strtotime('+1 day', $time_to);
$sql = "SELECT * FROM ".$_config['sql_prefix']."locations WHERE epoch >= $time_from AND epoch <= $time_to AND accuracy < ".$accuracy." AND altitude >=0 ORDER BY tracker_id, epoch ASC";
$stmt = $mysqli->prepare($sql);
if(!$stmt){
$response['status'] = false;
$response['error'] = $mysqli->error;
http_response_code(500);
}
$stmt->execute();
$result = $stmt->get_result();
$stmt->store_result();
$tracker_id = "";
while($data = $result->fetch_assoc()){
//Loop through results here $data[]
$markers[$data['tracker_id']][] = $data;
}
$stmt->close();
$response['status'] = true;
$response['markers'] = json_encode($markers);
$markers = $sql->getMarkers($time_from, $time_to, $accuracy);
if ($markers === false) {
$response['status'] = false;
$response['error'] = 'Database query error';
http_response_code(500);
} else {
$response['status'] = true;
$response['markers'] = json_encode($markers);
}
}else if($_REQUEST['action'] === 'deleteMarker'){
@ -70,71 +65,38 @@
$response['status'] = false;
http_response_code(204);
}else{
$stmt = $mysqli->prepare("DELETE FROM ".$_config['sql_prefix']."locations WHERE epoch = ?");
if(!$stmt){
$response['error'] = "Unable to prepare statement : " . $mysqli->error;
$result = $sql->deleteMarker($_REQUEST['epoch']);
if ($result === false) {
$response['error'] = 'Unable to delete marker from database.';
$response['status'] = false;
http_response_code(500);
}else{
$stmt->bind_param('i', $_REQUEST['epoch']);
//$stmt->bindParam(':epoc', $_POST['epoch'], PDO::PARAM_INT);
if(!$stmt->execute()){
$response['error'] = "Unable to delete marker from database : " . $stmt->error;
$response['status'] = false;
http_response_code(500);
}
} else {
$response['msg'] = "Marker deleted from database";
$response['status'] = true;
$stmt->close();
}
}
}
}
}else if($_REQUEST['action'] === 'geoDecode'){
} elseif ($_REQUEST['action'] === 'geoDecode') {
if(!array_key_exists('epoch', $_REQUEST)){
if (!array_key_exists('epoch', $_REQUEST)) {
$response['error'] = "No epoch provided for marker removal";
$response['status'] = false;
http_response_code(204);
}else{
} else {
// GET MARKER'S LAT & LONG DATA
$stmt = $mysqli->prepare("SELECT latitude, longitude FROM ".$_config['sql_prefix']."locations WHERE epoch = ?");
if(!$stmt){
$response['error'] = "Unable to prepare statement : " . $mysqli->error;
// GET MARKER'S LAT & LONG DATA
$marker = $sql->getMarkerLatLon($_REQUEST['epoch']);
if ($marker === false) {
$response['error'] = 'Unable to get marker from database.';
$response['status'] = false;
http_response_code(500);
}else{
$stmt->bind_param('i', $_REQUEST['epoch']);
//$stmt->bindParam(':epoc', $_POST['epoch'], PDO::PARAM_INT);
if(!$stmt->execute()){
$response['error'] = "Unable to get marker from database : " . $stmt->error;
$response['status'] = false;
}
$stmt->execute();
$result = $stmt->get_result();
$stmt->store_result();
while($data = $result->fetch_assoc()){
//Loop through results here $data[]
$marker = $data;
}
} else {
$latitude = $marker['latitude'];
$longitude = $marker['longitude'];
// GEO DECODE LAT & LONG
$geo_decode_url = $_config['geo_reverse_lookup_url'] . 'lat=' .$latitude. '&lon='.$longitude;
$geo_decode_json = file_get_contents($geo_decode_url);
$geo_decode_json = file_get_contents($geo_decode_url);
$geo_decode = @json_decode($geo_decode_json, true);
$place_id = intval($geo_decode['place_id']);
@ -144,29 +106,17 @@
if($location == '') { $location = @json_encode($geo_decode); }
//UPDATE MARKER WITH GEODECODED LOCATION
$stmt = $mysqli->prepare("UPDATE ".$_config['sql_prefix']."locations SET display_name = ?, place_id = ?, osm_id = ? WHERE epoch = ? AND latitude = ? AND longitude = ?");
$result = $sql->updateLocationData($epoch, $latitude, $longitude, $location_name, $place_id, $osm_id);
if(!$stmt){
$response['error'] = "Unable to prepare statement : " . $mysqli->error;
if ($result === false) {
$response['error'] = 'Unable to update marker in database.';
$response['status'] = false;
http_response_code(500);
}else{
$stmt->bind_param('siiidd', $location, $place_id, $osm_id, $_REQUEST['epoch'], $latitude, $longitude);
if(!$stmt->execute()){
$response['error'] = "Unable to update marker in database : " . $stmt->error;
$response['status'] = false;
http_response_code(500);
}else{
//SEND BACK DATA
$response['msg'] = "Marker's location fetched and saved to database";
$response['location'] = $location;
$response['status'] = true;
}
} else {
$response['msg'] = 'Marker\'s location fetched and saved to database';
$response['location'] = $location;
$response['status'] = true;
}
$stmt->close();
}
}
@ -177,15 +127,10 @@
http_response_code(404);
}
}else{
$response['error'] = "Invalid request type or no action";
$response['status'] = false;
http_response_code(404);
}
echo json_encode($response);
?>
echo json_encode($response);