Merge branch 'remastering' of https://git.steelants.cz/SImple-Home/PHP_SMART_HOME_V3 into remastering

This commit is contained in:
JonatanRek 2020-10-03 18:21:34 +02:00
commit a70caca58d
12 changed files with 247 additions and 82 deletions

View File

@ -1,9 +1,9 @@
RewriteEngine On RewriteEngine On
# require https # require https
RewriteCond %{HTTPS} off #RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/api/update #RewriteCond %{REQUEST_URI} !^/api/update
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] #RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#token to HTTP_AUTHORIZATION #token to HTTP_AUTHORIZATION
RewriteCond %{HTTP:Authorization} ^(.*) RewriteCond %{HTTP:Authorization} ^(.*)

View File

@ -1,4 +1,15 @@
<?php <?php
//Debug
error_reporting(E_ALL);
ini_set( 'display_errors','1');
//setup
ini_set ('session.cookie_httponly', '1');
ini_set('session.cookie_domain', $_SERVER['HTTP_HOST']);
ini_set('session.cookie_path', str_replace("login", "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI'])));
ini_set('session.cookie_secure', '1');
mb_internal_encoding ("UTF-8");
session_start(); session_start();
// import configs // import configs
@ -75,16 +86,7 @@ $apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRI
$apiLogManager->write("[API] POST body\n" . json_encode($_POST, JSON_PRETTY_PRINT), LogRecordTypes::INFO); $apiLogManager->write("[API] POST body\n" . json_encode($_POST, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
$apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO); $apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
//Debug
error_reporting(E_ALL);
ini_set( 'display_errors','1');
//setup
ini_set ('session.cookie_httponly', '1');
ini_set('session.cookie_domain', $_SERVER['HTTP_HOST']);
ini_set('session.cookie_path', str_replace("login", "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI'])));
ini_set('session.cookie_secure', '1');
mb_internal_encoding ("UTF-8");
Debugger::flag('dbconnect'); Debugger::flag('dbconnect');
//D B Conector //D B Conector

View File

@ -76,7 +76,7 @@ class EndpointsApi extends ApiController{
//Log Data Save //Log Data Save
if (isset($obj['logs'])){ if (isset($obj['logs'])){
foreach ($deviceLogs as $log) { foreach ($obj['logs'] as $log) {
$logManager = new LogManager('../logs/devices/'. date("Y-m-d").'.log'); $logManager = new LogManager('../logs/devices/'. date("Y-m-d").'.log');
$logManager->setLevel(LOGLEVEL); $logManager->setLevel(LOGLEVEL);
$logManager->write("[Device Log Msg] Device_ID " . $deviceId . "->" . $log, LogRecordTypes::ERROR); $logManager->write("[Device Log Msg] Device_ID " . $deviceId . "->" . $log, LogRecordTypes::ERROR);

View File

@ -17,6 +17,7 @@ class UpdatesApi {
return true; return true;
} }
return false; return false;
} }
public function default(){ public function default(){
@ -31,18 +32,18 @@ class UpdatesApi {
header('Content-type: text/plain; charset=utf8', true); header('Content-type: text/plain; charset=utf8', true);
//Filtrování IP adress // //Filtrování IP adress
if (DEBUGMOD != 1) { // if (DEBUGMOD != 1) {
if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) { // if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
echo json_encode(array( // echo json_encode(array(
'state' => 'unsuccess', // 'state' => 'unsuccess',
'errorMSG' => "Using API from your IP insnt alowed!", // 'errorMSG' => "Using API from your IP insnt alowed!",
)); // ));
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); // header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
$logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordTypes::INFO); // $logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordTypes::INFO);
exit(); // exit();
} // }
} // }
$macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC']; $macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC'];
$localBinary = "../updater/" . str_replace(':', '', $macAddress) . ".bin"; $localBinary = "../updater/" . str_replace(':', '', $macAddress) . ".bin";

View File

@ -12,7 +12,7 @@ class WidgetApi extends ApiController{
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId); $subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
if ($subDeviceData['type'] == 'on/off'){ if ($subDeviceData['type'] == 'on/off'){
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value']; $lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($subDeviceData['device_id'], 'on/off', !$lastValue); RecordManager::create($subDeviceData['device_id'], 'on/off', (int) !$lastValue);
$response = !$lastValue; $response = !$lastValue;
} else { } else {
throw new Exception("Bad Request", 403); throw new Exception("Bad Request", 403);

View File

@ -1,7 +1,7 @@
<?php <?php
if (!empty ($_POST)){ if (!empty ($_POST)){
if (!empty ($_FILES['deviceFirmware']) && !empty ($_FILES['deviceFirmware']['tmp_name']) && !empty ($_POST['deviceId'])) {
$deviceManager = new DeviceManager (); $deviceManager = new DeviceManager ();
if (!empty ($_FILES['deviceFirmware']) && !empty ($_FILES['deviceFirmware']['tmp_name']) && !empty ($_POST['deviceId'])) {
$file = $_FILES['deviceFirmware']; $file = $_FILES['deviceFirmware'];
$deviceMac = $deviceManager->getDeviceById ($_POST['deviceId'])['mac']; $deviceMac = $deviceManager->getDeviceById ($_POST['deviceId'])['mac'];
$fileName = (!empty ($deviceMac) ? str_replace (":", "", $deviceMac) . ".bin" : ""); $fileName = (!empty ($deviceMac) ? str_replace (":", "", $deviceMac) . ".bin" : "");
@ -10,15 +10,22 @@ if (!empty ($_POST)){
unlink("../updater/" . $fileName); unlink("../updater/" . $fileName);
} }
if ($fileName != "") { if ($fileName != "") {
echo 'coping file'.$fileName .copy ($file['tmp_name'], "../updater/" . $fileName);; copy ($file['tmp_name'], "../updater/" . $fileName);
} else {
} }
} }
if (isset ($_POST['deviceCommand']) && !empty ($_POST['deviceId'])) { if (isset ($_POST['deviceCommand']) && !empty ($_POST['deviceId'])) {
$deviceManager = new DeviceManager ();
$deviceManager->edit ($_POST['deviceId'], array ('command' => $_POST['deviceCommand'])); $deviceManager->edit ($_POST['deviceId'], array ('command' => $_POST['deviceCommand']));
} else if (!empty ($_POST['deviceCommand'])) {
$devices = $deviceManager->getAllDevices();
foreach ($devices as $key => $device) {
$deviceManager->edit ($device['device_id'], array ('command' => $_POST['deviceCommand']));
}
}
if (!empty ($_POST['deviceRoomId']) && !empty ($_POST['deviceId'])) {
$deviceManager->edit ($_POST['deviceId'], array ('room_id' => $_POST['deviceRoomId']));
}
if (!empty ($_POST['deviceName']) && !empty ($_POST['deviceId'])) {
$deviceManager->edit ($_POST['deviceId'], array ('name' => $_POST['deviceName']));
} }
header('Location: ./device'); header('Location: ./device');
die(); die();

View File

@ -3,7 +3,8 @@ class DeviceManager{
public static $devices; public static $devices;
static function getAllDevices () { static function getAllDevices () {
return Db::loadAll ("SELECT * FROM devices WHERE approved != ?", Array(2)); return Db::loadAll ("SELECT devices.* FROM devices
WHERE approved != ?", Array(2));
} }
static function getAllDevicesInRoom ($roomId = "") { static function getAllDevicesInRoom ($roomId = "") {
@ -26,6 +27,12 @@ class DeviceManager{
return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId)); return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
} }
static function getAllDevicesSorted ($sort, $sortType = "ASC") {
return Db::loadAll ("SELECT devices.* FROM devices
LEFT JOIN rooms ON (devices.room_id = rooms.room_id)
WHERE devices.approved != ? ORDER BY $sort $sortType", Array(2));
}
public static function create ($name, $token) { public static function create ($name, $token) {
$defaultRoom = RoomManager::getDefaultRoomId(); $defaultRoom = RoomManager::getDefaultRoomId();
$device = array ( $device = array (

View File

@ -35,7 +35,7 @@ class LogManager
} }
public function __destruct(){ public function __destruct(){
if (isset($this->logFile)) { if (isset($this->logFile) && $this->logFile != "Unable to open file!") {
fclose($this->logFile); fclose($this->logFile);
} }
} }

View File

@ -6,6 +6,9 @@ class Device extends Template
function __construct () { function __construct () {
$userManager = new UserManager (); $userManager = new UserManager ();
$deviceManager = new DeviceManager (); $deviceManager = new DeviceManager ();
$subDeviceManager = new SubDeviceManager ();
$recordManager = new RecordManager ();
$roomManager = new RoomManager ();
$langMng = new LanguageManager ('en'); $langMng = new LanguageManager ('en');
if (!$userManager->isLogin ()) { if (!$userManager->isLogin ()) {
@ -15,9 +18,73 @@ class Device extends Template
$template = new Template ('device'); $template = new Template ('device');
$template->prepare ('title', $langMng->get ("m_devices")); $template->prepare ('title', $langMng->get ("m_devices"));
if (!empty ($_GET['sort']) && !empty ($_SESSION['sort']) && $_SESSION['sort'] != $_GET['sort']) {
unset($_SESSION['sort']);
header('Location: device?sort=' . $_GET["sort"] . "&sortType=ASC");
die();
}
if (isset ($_GET['sortType'])) {
switch ($_GET['sortType']) {
case "DESC":
$sortType = "";
$sortIcon = "&#xf0dd";
break;
case "ASC":
$sortType = "DESC";
$sortIcon = "&#xf0de";
break;
case "":
unset($_GET["sort"]);
unset($_GET["sortType"]);
header('Location: device');
die();
break;
}
} else {
$sortType = "ASC";
}
if (!empty ($_GET['sort']) && !empty ($_GET['sortType'])) {
$template->prepare ('sortIcon', array ($_GET['sort'] => $sortIcon));
$actualSort = "devices.device_id";
switch ($_GET['sort']) {
case "name":
$actualSort = "devices.name";
break;
case "room":
$actualSort = "rooms.name";
break;
case "ip":
$actualSort = "devices.ip_address";
break;
case "mac":
$actualSort = "devices.mac";
break;
case "token":
$actualSort = "devices.token";
break;
}
$devices = $deviceManager->getAllDevicesSorted ($actualSort, $_GET['sortType']);
} else {
$devices = $deviceManager->getAllDevices (); $devices = $deviceManager->getAllDevices ();
}
if (!empty ($_GET['sort'])) {
$_SESSION['sort'] = $_GET['sort'];
}
foreach ($devices as $key => $device) { foreach ($devices as $key => $device) {
$subdevice = $subDeviceManager->getSubDeviceByMasterAndType ($device['device_id'], "wifi");
if (!empty ($subdevice['subdevice_id'])) {
$record = $recordManager->getLastRecord($subdevice['subdevice_id']);
if (!empty ($record)) {
$devices[$key]['signal'] = $record['value'] . " " . $subdevice['unit'];
}
}
if (empty ($devices[$key]['signal'])) {
$devices[$key]['signal'] = "";
}
$localBinary = "../updater/" . str_replace (':', '', $device['mac']) . ".bin"; $localBinary = "../updater/" . str_replace (':', '', $device['mac']) . ".bin";
if (file_exists ($localBinary)) { if (file_exists ($localBinary)) {
$hash = md5_file ($localBinary); $hash = md5_file ($localBinary);
@ -29,11 +96,40 @@ class Device extends Template
} else { } else {
$devices[$key]['firmware_hash'] = "false"; $devices[$key]['firmware_hash'] = "false";
} }
if (empty ($device['mac'])) {
$devices[$key]['firmware_hash'] = "";
} }
}
if (!empty ($_GET['sort']) && !empty ($_GET['sortType']) && $_GET['sort'] == "firmware") {
if ($_GET['sortType'] == "DESC") {
usort($devices, function($a, $b) {
return $a['firmware_hash'] <=> $b['firmware_hash'];
});
} else if ($_GET['sortType'] == "ASC") {
usort($devices, function($a, $b) {
return $b['firmware_hash'] <=> $a['firmware_hash'];
});
}
} else if (!empty ($_GET['sort']) && !empty ($_GET['sortType']) && $_GET['sort'] == "signal") {
if ($_GET['sortType'] == "DESC") {
usort($devices, function($a, $b) {
return $a['signal'] <=> $b['signal'];
});
} else if ($_GET['sortType'] == "ASC") {
usort($devices, function($a, $b) {
return $b['signal'] <=> $a['signal'];
});
}
}
$rooms = $roomManager->getAllRooms();
$template->prepare ('baseDir', BASEDIR); $template->prepare ('baseDir', BASEDIR);
$template->prepare ('debugMod', DEBUGMOD); $template->prepare ('debugMod', DEBUGMOD);
$template->prepare ('logToLiveTime', LOGTIMOUT); $template->prepare ('logToLiveTime', LOGTIMOUT);
$template->prepare ('rooms', $rooms);
$template->prepare ('sortType', $sortType);
$template->prepare ('devices', $devices); $template->prepare ('devices', $devices);
$template->prepare ('langMng', $langMng); $template->prepare ('langMng', $langMng);

View File

@ -3,7 +3,7 @@ class Logout extends Template
{ {
function __construct() function __construct()
{ {
global $userManager; $userManager = new UserManager ();
$userManager->logout(); $userManager->logout();
header('Location: ' . BASEURL . 'login'); header('Location: ' . BASEURL . 'login');
die(); die();

View File

@ -3,7 +3,7 @@ class Oauth extends Template
{ {
function __construct() function __construct()
{ {
global $userManager; $userManager = new UserManager ();
$langMng = new LanguageManager('en'); $langMng = new LanguageManager('en');
$template = new Template('oauth'); $template = new Template('oauth');

View File

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<?php <?php
$partial = new Partial('head'); $partial = new Partial('head');
@ -8,6 +9,7 @@
?> ?>
<title><?php echo $TITLE ?></title> <title><?php echo $TITLE ?></title>
</head> </head>
<body class="no-transitions"> <body class="no-transitions">
<div class="row no-gutters main"> <div class="row no-gutters main">
<div class="col-md-3 d-sm-none"></div> <div class="col-md-3 d-sm-none"></div>
@ -22,26 +24,69 @@
</div> </div>
<div class="col-md-9 main-body"> <div class="col-md-9 main-body">
<table class="table is-fluid"> <table class="table is-fluid">
<thead>
<tr> <tr>
<th>#</th> <th><a href="device">#</a></th>
<th>Name</th> <th><a href="device?sort=name&sortType=<?php echo $SORTTYPE; ?>">Name</a><i class="fa"><?php echo (!empty($SORTICON['name']) ? $SORTICON['name'] : ""); ?></i></th>
<th>Room</th> <th><a href="device?sort=room&sortType=<?php echo $SORTTYPE; ?>">Room</a><i class="fa"><?php echo (!empty($SORTICON['room']) ? $SORTICON['room'] : ""); ?></i></th>
<th>Firmware</th> <th><a href="device?sort=signal&sortType=<?php echo $SORTTYPE; ?>">Signal</a><i class="fa"><?php echo (!empty($SORTICON['signal']) ? $SORTICON['signal'] : ""); ?></i></th>
<th>IP Address<br>(Mac)</th> <th><a href="device?sort=firmware&sortType=<?php echo $SORTTYPE; ?>">Firmware</a><i class="fa"><?php echo (!empty($SORTICON['firmware']) ? $SORTICON['firmware'] : ""); ?></i></th>
<th>Action</th> <th>
<a href="device?sort=ip&sortType=<?php echo $SORTTYPE; ?>">IP Address</a><i class="fa"><?php echo (!empty($SORTICON['ip']) ? $SORTICON['ip'] : ""); ?></i><br>
<a href="device?sort=mac&sortType=<?php echo $SORTTYPE; ?>">(Mac)</a><i class="fa"><?php echo (!empty($SORTICON['mac']) ? $SORTICON['mac'] : ""); ?></i><br>
<a href="device?sort=token&sortType=<?php echo $SORTTYPE; ?>">Token</a><i class="fa"><?php echo (!empty($SORTICON['token']) ? $SORTICON['token'] : ""); ?></i>
</th>
<th>Action
<form method="post" action="">
<button class="fa custom-file-input" type="submit" name="deviceCommand" value="reset" title="Reset All"><b>&#xf01e;</b></button>
<div style="float: clear;"></div>
</form>
</th>
</tr> </tr>
</thead>
<tbody>
<?php if (!empty($DEVICES)) : ?> <?php if (!empty($DEVICES)) : ?>
<?php foreach ($DEVICES as $device) : ?> <?php foreach ($DEVICES as $device) : ?>
<tr> <tr>
<td><i class="fa">&#x<?php echo (!empty($device['icon']) ? $device['icon'] : ""); ?></i></td> <td><i class="fa">&#x<?php echo (!empty($device['icon']) ? $device['icon'] : ""); ?></i></td>
<td><?php echo (!empty($device['name']) ? $device['name'] : ""); ?></td> <td>
<td>Room</td> <form method="post" action="">
<input type="hidden" name="deviceId" value="<?php echo (!empty($device['device_id']) ? $device['device_id'] : ""); ?>">
<input class="input" type="text" onchange="this.form.submit();" name="deviceName" value="<?php echo (!empty($device['name']) ? $device['name'] : ""); ?>">
</form>
</td>
<td>
<form method="post" action="">
<input type="hidden" name="deviceId" value="<?php echo (!empty($device['device_id']) ? $device['device_id'] : ""); ?>">
<select class="input" name="deviceRoomId" onchange="this.form.submit();">
<?php
if (!empty($ROOMS)) {
foreach ($ROOMS as $key => $room) {
echo '<option value="' . $room['room_id'] . '" ' . ($device['room_id'] == $room['room_id'] ? 'selected' : '') . '>' . $room['name'] . '</option>';
}
}
?>
</select>
</form>
</td>
<td><?php echo (!empty($device['signal']) ? $device['signal'] : ""); ?></td>
<td> <td>
<?php if (!empty($device['mac'])) : ?> <?php if (!empty($device['mac'])) : ?>
<i class="fa <?php echo (!empty($device['firmware_hash']) ? ($device['firmware_hash'] != "need" ? "fa-check-circle" : "fa-circle") : "fa-times-circle"); ?>" style="float: center; <?php echo (!empty($device['firmware_hash']) ? ($device['firmware_hash'] != "need" ? "color: green;" : "color: yellow;") : "color: red;"); ?>"></i> <?php
$icon = "fa-circle";
$color = "yellow";
if (!empty($device['firmware_hash'])) {
if ($device['firmware_hash'] == "true") {
$icon = "fa-check-circle";
$color = "green";
} else if ($device['firmware_hash'] == "need") {
$icon = "fa-arrow-circle-up";
$color = "#6495ED";
} else {
$icon = "fa-times-circle";
$color = "red";
}
}
?>
<i class="fa <?php echo $icon; ?>" style="color: <?php echo $color; ?>;"></i>
<?php echo $device['firmware_hash'] ?> <?php echo $device['firmware_hash'] ?>
<button class="fa custom-file-input" type="button" onclick="document.getElementById('deviceFirmware-<?php echo $device['device_id'] ?>').click();">&#xf0ee;</button> <button class="fa custom-file-input" type="button" onclick="document.getElementById('deviceFirmware-<?php echo $device['device_id'] ?>').click();">&#xf0ee;</button>
<form style="display: none;" method="post" action="" enctype="multipart/form-data"> <form style="display: none;" method="post" action="" enctype="multipart/form-data">
@ -51,7 +96,9 @@
<?php endif; ?> <?php endif; ?>
<div type="float: clear;"></div> <div type="float: clear;"></div>
</td> </td>
<td><?php echo (!empty($device['mac']) ? $device['mac'] : ""); ?><br><?php echo (!empty($device['ip_address']) ? $device['ip_address'] : ""); ?></td> <td><?php echo (!empty($device['mac']) ? $device['mac'] : ""); ?><br>
<?php echo (!empty($device['ip_address']) ? $device['ip_address'] : ""); ?><br>
<?php echo (!empty($device['token']) ? $device['token'] : ""); ?></td>
<td> <td>
<?php if (!empty($device['mac'])) : ?> <?php if (!empty($device['mac'])) : ?>
<form method="post" action=""> <form method="post" action="">
@ -65,7 +112,6 @@
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
<tbody>
</table> </table>
</div> </div>
@ -75,6 +121,12 @@
$partial->render(); $partial->render();
//TODO js do main.js //TODO js do main.js
?> ?>
<script>
$(function() {
$("#sortable").sortable();
$("#sortable").disableSelection();
});
</script>
</body> </body>
</html> </html>