3.0: Remove old code base.

This commit is contained in:
Romano Schoonheim 2021-01-07 10:19:32 -08:00
parent aafd9622a6
commit a0f7b51ba1
160 changed files with 0 additions and 19504 deletions

@ -1 +0,0 @@
Subproject commit 0ee345e496ed3bd468ae9bcb583352c7561ce368

View File

@ -1,18 +0,0 @@
# https://editorconfig.org/
root = true
[*]
indent_style = tab
indent_size = 3
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
max_line_length = 80
[COMMIT_EDITMSG]
indent_size = 4
max_line_length = 80

View File

@ -1,6 +0,0 @@
.git
_FIRMWARE
_INSTALATION
_README_IMG
README.md
.todo

22
.gitignore vendored
View File

@ -1,23 +1 @@
.ftpconfig
.ftpconfig2
*.log
*.bin
config.php
_nemazat/index.html
_nemazat/css/main.css.map
_nemazat/css/main.css
_nemazat/css/font-awesome.min.css
.vscode/
.vscode/sftp.json
app/updater/*.bin
app/logs/*.log
backup/*.zip
vendor/
.idea/ .idea/

3
.gitmodules vendored
View File

@ -1,3 +0,0 @@
[submodule ".docker"]
path = .docker
url = https://github.com/GamerClassN7/Docker-Xamp-Server.git

View File

@ -1,22 +0,0 @@
RewriteEngine On
# require https
#RewriteCond %{HTTPS} off
#RewriteCond %{REQUEST_URI} !^/api/update
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#token to HTTP_AUTHORIZATION
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule . - [e=HTTP_AUTHORIZATION:%1]
# serve all files from public subfolder
RewriteCond %{REQUEST_FILENAME} !.php
RewriteCond %{REQUEST_FILENAME} !.log
RewriteCond %{REQUEST_FILENAME} !.ttfnot
RewriteCond %{REQUEST_FILENAME} \.
RewriteRule (.*) ./public/$1 [L]
# serve all other request as query parameters
RewriteRule (.*) ./public/index.php?url=$1 [L,QSA]
AddType application/x-httpd-php .php .phtml

13
.todo
View File

@ -1,13 +0,0 @@
//TODO: Automation last Run Time
//TODO: Check if every automation type Works
//TODO: Add Switch to Setting For debug mode
//TODO: hide menu item Debug When Debug mode is disabled
//TODO: Check if every setting works
//TODO: Add slector to automation execute all To execute only utomation whitch contain same day (as actual to speed up process)
//TODO: Check and fix time based automation
//TODO: 404 same like in ENergo COunter Project
//TODO: @FILIP Fix Editation of all Automations
//TODO: @FILIP test if registration work without an isuu even with notification
//TODO: Fix Default Room selection
//TODO: Fix User Delete button
//TODO: Fix new add email form

21
LICENSE
View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019 JonatanRek<gamerclassn7@gamil.com> :)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,255 +0,0 @@
<pre>
<?php
var_dump($_POST);
var_dump(file_exists("./app/updater/" . "3C71BF22FDCF" . ".bin"));
?>
</pre>
<form class="" action="" method="post">
<label for="operator">Typ podmínky</label>
<select class="" name="operator">
<option value="or">OR</option>
<option value="and">AND</option>
</select>
<div class="variableArea">
<button name="addButton" id="addButton">+</button>
</div>
<br>
<label for="resetOperator">Typ podmínky</label>
<select class="" name="resetOperator">
<option value="or">OR</option>
<option value="and">AND</option>
</select>
<div class="resetvariableArea">
<button name="restartaAddButton" id="restartAddButton">+</button>
</div>
<br>
<button type="submit" name="button">Odeslat</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function foo(element){
var id = element.attr("name").match(/\d+/)[0]
$("[name='variable["+id+"][value]']").remove();
$("[name='variable["+id+"][equaler]']").remove();
if (element.val() == "atDeviceValue") {
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
];
var varOperator = $('<select name="variable['+id+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varOperator);
var input = $("<input/>");
input.attr("type","text");
input.attr("name","variable["+id+"][value]");
element.parent().append(input);
} else if (element.val() == "time") {
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
];
var varOperator = $('<select name="variable['+id+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varOperator);
var input = $("<input/>");
input.attr("type","time");
input.attr("name","variable["+id+"][value]");
element.parent().append(input);
}else {
var arrVarOperator = [
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+id+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varOperator);
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+id+'][value]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varValue);
}
}
$("#addButton,#restartAddButton").click( function (event) {
event.preventDefault();
var numItems = $('.var').length
var arrVarSelect = [
{val : 'sunSet', text: 'Západ Slunce'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'inHome', text: 'Příchod'},
{val : 'outHome', text: 'Odchod'},
{val : 'time', text: 'Čas'},
{val : 'atDeviceValue', text: 'Při hodnotě zařízení'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'noOneHome', text: 'Nikdo Doma'},
{val : 'someOneHome', text: 'Nekdo Doma'},
];
var varSelect = $('<select name="variable['+numItems+'][what]">');
$(arrVarSelect).each(function() {
varSelect.append($('<option>').attr('value',this.val).text(this.text));
});
varSelect.attr("onchange", "foo($(this))");
/*onchange = function(e) {
console.log(this.value);
if (this.value == 'atDeviceValue') {
alert("ok");
}
};*/
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+numItems+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+numItems+'][value]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
var newDiv = $("<div class=var>").append(varSelect);
newDiv = newDiv.append(varOperator);
newDiv = newDiv.append(varValue);
$(this).parent().append(newDiv);
});
/*var arrVarSelect = [
{val : 'sunSet', text: 'Západ Slunce'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'inHome', text: 'Příchod'},
{val : 'outHome', text: 'Odchod'},
{val : 'time', text: 'Čas'},
{val : 'atDeviceValue', text: 'Při hodnotě zařízení'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'noOneHome', text: 'Nikdo Doma'},
{val : 'someOneHome', text: 'Nekdo Doma'},
];
var varSelect = $('<select name="variable['+numItems+'][]">');
$(arrVarSelect).each(function() {
varSelect.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+numItems+'][]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+numItems+'][]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
//TODO změna výstupní proměné na základě vstupu date,num etc
var newDiv = $("<div class=var>").append(varSelect);/*.change(
function (subEvent) {
alert(subEvent);
}
);*/
/*newDiv = newDiv.append(varOperator);
newDiv = newDiv.append(varValue);
$(".restartaAddButton")append(newDiv);*/
/*
var arrVarSelect = [
{val : 'sunSet', text: 'Západ Slunce'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'inHome', text: 'Příchod'},
{val : 'outHome', text: 'Odchod'},
{val : 'time', text: 'Čas'},
{val : 'atDeviceValue', text: 'Při hodnotě zařízení'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'noOneHome', text: 'Nikdo Doma'},
{val : 'someOneHome', text: 'Nekdo Doma'},
];
var varSelect = $('<select name="variable['+numItems+'][]">');
$(arrVarSelect).each(function() {
varSelect.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+numItems+'][]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+numItems+'][]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
//TODO změna výstupní proměné na základě vstupu date,num etc
var newDiv = $("<div class=var>").append(varSelect);/*.change(
function (subEvent) {
alert(subEvent);
}
);*/
/* newDiv = newDiv.append(varOperator);
newDiv = newDiv.append(varValue);
$(".variableArea").parent().append(newDiv);*/
</script>

File diff suppressed because one or more lines are too long

View File

@ -1,119 +0,0 @@
<?php
//Debug
error_reporting(E_ALL);
ini_set( 'display_errors','1');
//setup
parse_str($_SERVER['QUERY_STRING'], $params);
if (defined ("BASEDIR")) {
$urlSes = BASEDIR;
} else {
$urlSes = str_replace((!empty ($params['url']) ? $params['url'] : ""), "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI']));
}
if (defined ("BASEDIR") && defined ("BASEURL")) {
$domain = str_replace("http://", "", str_replace("https://", "", str_replace(BASEDIR, "", BASEURL)));
} else {
$domain = str_replace("/var/www/", "", $_SERVER['DOCUMENT_ROOT']);
}
session_set_cookie_params(
1209600,
$urlSes,
$domain,
true,
true
);
/*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');
ini_set('session.gc_maxlifetime', 1209600);*/
mb_internal_encoding ("UTF-8");
session_start();
// import configs
require_once '../library/Debugger.php';
Debugger::flag('loaders');
//Autoloader
class Autoloader {
protected static $extension = ".php";
protected static $root = __DIR__;
protected static $files = [];
static function ClassLoader ($className = ""){
$directorys = new RecursiveDirectoryIterator(static::$root, RecursiveDirectoryIterator::SKIP_DOTS);
//echo '<pre>';
//var_dump($directorys);
//echo '</pre>';
$files = new RecursiveIteratorIterator($directorys, RecursiveIteratorIterator::LEAVES_ONLY);
$filename = $className . static::$extension;
foreach ($files as $key => $file) {
if (strtolower($file->getFilename()) === strtolower($filename) && $file->isReadable()) {
include_once $file->getPathname();
return;
}
}
}
static function setRoot($rootPath){
static::$root = $rootPath;
}
}
spl_autoload_register("Autoloader::ClassLoader");
Autoloader::setRoot('/var/www/dev.steelants.cz/vasek/home-update/');
// import configs
require_once '../config/config.php';
class ErrorHandler {
static function exception($exception){
error_log($exception);
http_response_code($exception->getCode());
$message = [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTrace(),
];
echo json_encode($message);
$apiLogManager = new LogManager('../logs/apache/'. date("Y-m-d").'.log');
$apiLogManager->setLevel(LOGLEVEL);
$apiLogManager->write("[APACHE]\n" . json_encode($message, JSON_PRETTY_PRINT), LogRecordTypes::ERROR);
}
}
set_exception_handler("ErrorHandler::exception");
Debugger::flag('preload');
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$apiLogManager = new LogManager('../logs/api/'. date("Y-m-d").'.log');
$apiLogManager->setLevel(LOGLEVEL);
$apiLogManager->write("[API] headers\n" . json_encode($_SERVER, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
$apiLogManager->write("[API] request body\n" . json_encode($obj, 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);
Debugger::flag('dbconnect');
//D B Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
Debugger::flag('routes');
// import routes
require_once '../app/Routes.php';
Debugger::flag('done');
// echo Debugger::showFlags(false);

View File

@ -1,66 +0,0 @@
<?php
$router = new Router();
$router->setDefault(function(){
echo $_GET['url'].': 404';
$logManager = new LogManager();
$logManager->setLevel(LOGLEVEL);
$logManager->write("[ROUTER]" . $_GET['url'] . "not found", LogRecordTypes::WARNING);
unset($logManager);
});
//Pages
$router->any('/', 'Log');
$router->any('/log', 'Log');
$router->any('/server', 'Server');
$router->any('/login', 'Login');
$router->any('/logout', 'Logout');
$router->any('/automation', 'Automation');
$router->any('/setting', 'Setting');
$router->any('/device', 'Device');
$router->any('/device/{sortBy}/{sortType}', 'Device');
$router->any('/plugins', 'Plugins');
$router->any('/ajax', 'Ajax');
$router->any('/oauth', 'Oauth');
//Vue APP
$router->post('/api/login', 'AuthApi@login');
$router->post('/api/logout', 'AuthApi@logout');
$router->get('/api/rooms', 'RoomsApi@default');
$router->get('/api/rooms/{roomId}/update', 'RoomsApi@update');
$router->get('/api/devices', 'DevicesApi@default');
$router->get('/api/plugins', 'PluginsApi@default');
$router->get('/api/users', 'UsersApi@default');
$router->get('/api/server', 'ServerApi@default');
$router->get('/api/server/log', 'ServerApi@logStatus');
$router->post('/api/widgets/{widgetId}/run', 'WidgetApi@run');
$router->get('/api/widgets/{widgetId}/detail', 'WidgetApi@detail');
$router->get('/api/widgets/{widgetId}/detail/{period}', 'WidgetApi@detail');
//cron
$router->post('/cron/clean', 'CronApi@clean');
$router->post('/cron/fetch', 'CronApi@fetch');
//Google Home - API
$router->any('/api/HA/auth', 'Oauth');
$router->any('/api/HA', 'GoogleHomeApi@response');
//Endpoints API
$router->post('/api/endpoint/', 'EndpointsApi@default');
$router->any('/api/update/', 'UpdatesApi@default');
$router->any('/api/users/status', 'UsersApi@status');
$router->any('/api/users/subscribe', 'UsersApi@subscribe');
// examples
$router->any('/api/example', 'ExampleApi@example');
$router->any('/example', 'ExampleController@index');
$router->any('/example/subpage', 'ExampleController@subpage');
//module routes
//$router->any('/plugins/spotify/callback', 'Spotify@callback');
$router->run($_SERVER['REQUEST_METHOD'], '/'.(isset($_GET['url']) ? $_GET['url'] : ''));

View File

@ -1,25 +0,0 @@
<?php
class AuthApi extends ApiController {
public function login(){
$token = (new AuthManager)->getToken($this->input['username'],$this->input['password']);
if (!$token) {
throw new Exception("Auth failed", 401);
}
$this->response(['token' => $token]);
}
public function logout(){
$authenticationBearrer = $_SERVER['HTTP_AUTHORIZATION'];
if (!(new AuthManager)->deleteToken($authenticationBearrer)) {
throw new Exception("logout Failed", 401);
}
}
public function registration(){
}
public function restartPassword(){
}
}

View File

@ -1,63 +0,0 @@
<?php
class CronApi extends ApiController
{
public function clean()
{
//Log Cleaning
$logKeeper = new LogMaintainer();
$logKeeper->purge(LOGTIMOUT);
//Database Backup Cleanup
$backupWorker = new DatabaseBackup();
$backupWorker->purge(5);
//Old Records Cleanup
foreach (SubDeviceManager::getAllSubDevices() as $key => $value) {
RecordManager::setHistory($value['subdevice_id']);
}
$this->response(['Value' => 'OK']);
}
public function fetch()
{
//Run Plugins
$result = [];
$dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/';
$pluginsFiles = array_diff(scandir($dir), ['..', '.']);
foreach ($pluginsFiles as $key => $pluginFile) {
if (strpos($pluginFile, "!") === false) {
$className = str_replace(".php", "", $pluginFile);
if (strpos($pluginFile, '_') === true) {
continue;
}
if (!class_exists($className)) {
continue;
}
$pluginMakeClass = new $className;
if (!method_exists($pluginMakeClass, 'make')) {
continue;
}
$result[$className] = $pluginMakeClass->make();
} else {
$className = str_replace("!", "", str_replace(".php", "", $pluginFile));
if (strpos($pluginFile, '_') === true) {
continue;
}
if (!class_exists($className)) {
continue;
}
$pluginMakeClass = new $className;
if (!method_exists($pluginMakeClass, 'disable')) {
continue;
}
$result[$className] = $pluginMakeClass->disable();
}
}
//Print Result
$this->response($result);
}
}

View File

@ -1,15 +0,0 @@
<?php
class DevicesApi extends ApiController{
public function default(){
$this->requireAuth();
$response = [];
// TODO: process the request
$this->response($response);
}
public function getDevicesByRoom($roomId){
}
}

View File

@ -1,194 +0,0 @@
<?php
class EndpointsApi extends ApiController{
public function default(){
// $this->requireAuth();
$obj = $this->input;
//variables Definition
$command = "null";
//Log
$logManager = new LogManager('../logs/api/'. date("Y-m-d").'.log');
$logManager->setLevel(LOGLEVEL);
//Token Checks
if ($obj['token'] == null || !isset($obj['token'])) {
$this->response([
'state' => 'unsuccess',
'errorMSG' => "Missing Value Token in JSON payload",
], 401);
die();
}
//Vstupní Checky
if (!DeviceManager::registeret($obj['token'])) {
//Notification data setup
$notificationMng = new NotificationManager;
$notificationData = [
'title' => 'Info',
'body' => 'New device Detected Found',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
//Subdevice Registration
$device = DeviceManager::create($obj['token'], $obj['token']);
foreach ($obj['values'] as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($device['device_id'], $key)) {
SubDeviceManager::create($device['device_id'], $key, UNITS[$key]);
}
}
//Notification for newly added Device
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordTypes::INFO);
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
$logManager->write("[API] Registering Device", LogRecordTypes::INFO);
$this->response([
'state' => 'unsuccess',
'errorMSG' => "Device not registeret",
], 401);
}
if (!DeviceManager::approved($obj['token'])) {
$this->response([
'state' => 'unsuccess',
'errorMSG' => "Unaproved Device",
], 401);
}
$device = DeviceManager::getDeviceByToken($obj['token']);
DeviceManager::setHeartbeat($device['device_id']);
//Diagnostic
if (isset($obj['settings'])){
$data = ['mac' => $obj['settings']["network"]["mac"], 'ip_address' => $obj['settings']["network"]["ip"]];
if (array_key_exists("firmware_hash", $obj['settings'])) {
$data['firmware_hash'] = $obj['settings']["firmware_hash"];
}
DeviceManager::editByToken($obj['token'], $data);
}
//Log Data Save
if (isset($obj['logs'])){
foreach ($obj['logs'] as $log) {
$deviceLogManager = new LogManager('../logs/devices/'. date("Y-m-d").'.log');
$deviceLogManager->setLevel(LOGLEVEL);
$deviceLogManager->write("[Device Log Msg] Device_ID " . $device['device_id'] . "->" . $log, LogRecordTypes::ERROR);
unset($deviceLogManager);
}
$this->response([
'state' => 'succes',
'command' => $command,
], 200);
die();
}
// Issuing command
if ($command == "null"){
$deviceCommand = $device["command"];
if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null")
{
$command = $deviceCommand;
$data = [
'command'=>'null'
];
DeviceManager::editByToken($obj['token'], $data);
$logManager->write("[API] Device_ID " . $device['device_id'] . " executing command " . $command, LogRecordTypes::INFO);
}
}
$jsonAnswer = [];
$subDeviceLastReordValue = [];
if (isset($obj['values'])) {
//ZAPIS
foreach ($obj['values'] as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($device['device_id'], $key)) {
SubDeviceManager::create($device['device_id'], $key, UNITS[$key]);
}
$subDeviceLastReordValue[$key] = $value['value'];
RecordManager::create($device['device_id'], $key, round($value['value'],3));
$logManager->write("[API] Device_ID " . $device['device_id'] . " writed value " . $key . ' ' . $value['value'], LogRecordTypes::INFO);
//notification
if ($key == 'door' || $key == 'water') {
$notificationMng = new NotificationManager;
$notificationData = [];
switch ($key) {
case 'door':
$notificationData = [
'title' => 'Info',
'body' => 'Someone just open up '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
break;
case 'water':
$notificationData = [
'title' => 'Alert',
'body' => 'Wather leak detected by '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
break;
}
if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordTypes::INFO);
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
}
}
//upravit format na setings-> netvork etc
$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($device['device_id']);
if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
$jsonAnswer['device']['sleepTime'] = $device['sleep_time'];
}
} else {
if (count(SubDeviceManager::getAllSubDevices($device['device_id'])) == 0) {
//SubDeviceManager::create($device['device_id'], 'on/off', UNITS[$key]);
//RecordManager::create($device['device_id'], 'on/off', 0);
}
$subDevicesData = SubDeviceManager::getAllSubDevices($device['device_id']);
foreach ($subDevicesData as $key => $subDeviceData) {
$subDeviceId = $subDeviceData['subdevice_id'];
$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
if (!empty ($subDeviceLastReord)) {
$subDeviceLastReordValue[$subDeviceData['type']] = $subDeviceLastReord['value'];
if ($subDeviceLastReord['execuded'] == 0){
$logManager->write("[API] subDevice_ID " . $subDeviceId . " executed comand with value " . json_encode($subDeviceLastReordValue) . " executed " . $subDeviceLastReord['execuded'], LogRecordTypes::INFO);
RecordManager::setExecuted($subDeviceLastReord['record_id']);
}
}
}
}
$hostname = "";
$hostname = strtolower($device['name']);
$hostname = str_replace(' ', '_', $hostname);
$jsonAnswer['device']['hostname'] = $hostname;
$jsonAnswer['state'] = 'succes';
$jsonAnswer['values'] = $subDeviceLastReordValue;
$jsonAnswer['command'] = $command;
$this->response($jsonAnswer);
// this method returns response as json
//unset($logManager); //TODO: Opravit
die();
}
}

View File

@ -1,24 +0,0 @@
<?php
class ExampleApi extends ApiController{
public function example(){
// if this function should be accessible only for logged users uncomment next line
// $this->requireAuth();
// if user is logged in, next lines will be processed
// otherwise script get terminated with 401 UNAUTHORIZED
// input data are stored in $this->input
// in this example we just copy input to response
$response = $this->input;
// this method returns response as json
$this->response($response);
// you can specify returned http code by second optional parameter
// default value is 200
// $this->response($response, $httpCode);
}
}

View File

@ -1,56 +0,0 @@
<?php
class GoogleHomeApi{
static function response(){
//$this->requireAuth();
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
$apiLogManager->setLevel(LOGLEVEL);
header('Content-Type: application/json');
switch ($obj['inputs'][0]['intent']) {
case 'action.devices.SYNC':
GoogleHome::sync($obj['requestId']);
$apiLogManager->write("[Google Home] action.devices.SYNC", LogRecordTypes::INFO);
break;
case 'action.devices.QUERY':
GoogleHome::query($obj['requestId'], $obj['inputs'][0]['payload']);
$apiLogManager->write("[Google Home] action.devices.QUERY", LogRecordTypes::INFO);
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
break;
case 'action.devices.EXECUTE':
GoogleHome::execute($obj['requestId'], $obj['inputs'][0]['payload']);
$apiLogManager->write("[Google Home] action.devices.EXECUTE", LogRecordTypes::INFO);
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
break;
}
unset($apiLogManager);
}
static function autorize(){
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
$apiLogManager->setLevel(LOGLEVEL);
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
$apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
unset($apiLogManager);
$get = [
"access_token"=>"2222255888", //TODO: FIX
"token_type"=>"Bearer",
"state"=>$_GET["state"],
];
echo $_GET["redirect_uri"] . '#' . http_build_query($get) ;
echo '<a href="'.$_GET["redirect_uri"] . '#' . http_build_query($get) . '">FINISH</a>';
}
}

View File

@ -1,12 +0,0 @@
<?php
class PluginsApi extends ApiController{
public function default(){
$this->requireAuth();
$response = [];
// TODO: process the request
$this->response($response);
}
}

View File

@ -1,26 +0,0 @@
<?php
class RecordApi extends ApiController{
public function default(){
//$this->requireAuth();
$response = [];
$roomIds = [];
$roomsData = RoomManager::getRoomsDefault();
foreach ($roomsData as $roomKey => $room) {
$roomIds[] = $room['room_id'];
}
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds);
foreach ($roomsData as $roomKey => $roomData) {
$response[] = [
'room_id' => $roomData['room_id'],
'name' => $roomData['name'],
'widgets' => isset($subDevicesData[$roomData['room_id']]) ? $subDevicesData[$roomData['room_id']] : [],
];
}
$this->response($response);
}
}

View File

@ -1,74 +0,0 @@
<?php
class RoomsApi extends ApiController
{
public function default()
{
//$this->requireAuth();
$response = [];
$roomIds = [];
$roomsData = RoomManager::getRoomsDefault();
foreach ($roomsData as $roomKey => $room) {
$roomIds[] = $room['room_id'];
}
//Translation Of Numeric Walues
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds);
foreach ($subDevicesData as $subDeviceKey => $subDevice) {
foreach ($subDevice as $key => $value) {
//Type Handling
$type = null;
if (strpos($subDevicesData[$subDeviceKey][$key]['type'], '-') !== false) {
$type = $subDevicesData[$subDeviceKey][$key]['type'];
} else if (strpos(SubDeviceManager::getSubDeviceMaster($subDevicesData[$subDeviceKey][$key]['subdevice_id'])['type'], '-') !== false) {
$type = SubDeviceManager::getSubDeviceMaster($subDevicesData[$subDeviceKey][$key]['subdevice_id'])['type'];
}
//Connection Error Creation
$connectionError = true;
$LastRecordTime = new DateTime($subDevicesData[$subDeviceKey][$key]['time']);
$interval = $LastRecordTime->diff(new DateTime());
$lastSeen = ($interval->format('%h') * 60 + $interval->format('%i'));
if ($subDevicesData[$subDeviceKey][$key]['sleep_time'] == NULL || $subDevicesData[$subDeviceKey][$key]['sleep_time'] == 0 || $lastSeen < $subDevicesData[$subDeviceKey][$key]['sleep_time']) {
$connectionError = false;
}
$subDevicesData[$subDeviceKey][$key]['connection_error'] = $connectionError;
//Record Translation
$cammelCaseClass = "";
foreach (explode('-', $type) as $word) {
$cammelCaseClass .= ucfirst($word);
}
if (class_exists($cammelCaseClass)) {
$deviceClass = new $cammelCaseClass;
if (method_exists($deviceClass, 'translate')) {
$subDevicesData[$subDeviceKey][$key]['value'] = $deviceClass->translate($subDevicesData[$subDeviceKey][$key]['value']);
}
}
}
}
foreach ($roomsData as $roomKey => $roomData) {
if ($roomData['device_count'] == 0) continue;
$subDevicesSorted = isset($subDevicesData[$roomData['room_id']]) ? Utilities::sortArrayByKey($subDevicesData[$roomData['room_id']], 'connection_error', 'asc') : [];
$response[] = [
'room_id' => $roomData['room_id'],
'name' => $roomData['name'],
'widgets' => $subDevicesSorted,
];
}
$this->response($response);
}
public function update($roomId)
{
//$this->requireAuth();
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds([$roomId]);
$this->response($subDevicesData);
}
}

View File

@ -1,43 +0,0 @@
<?php
class ServerApi extends ApiController {
private function getSystemMemInfo()
{
$data = explode("\n", file_get_contents("/proc/meminfo"));
$meminfo = array();
foreach ($data as $line) {
$data = explode(":", $line);
if (count($data)!=2) continue;
$meminfo[$data[0]] = trim($data[1]);
}
return $meminfo;
}
private function getProcessorUsage(){
$loads=sys_getloadavg();
$core_nums=trim(shell_exec("grep -P '^physical id' /proc/cpuinfo|wc -l"));
$load = round($loads[0]/($core_nums + 1)*100, 2);
return $load;
}
public function default(){
//$this->requireAuth();
$response = [
"cpu_load" => $this->getProcessorUsage(),
"uptime" => shell_exec('uptime -p'),
"ramFree" => $this->getSystemMemInfo()["MemFree"],
"ramTotal" => $this->getSystemMemInfo()["MemTotal"],
"diskFree" => disk_free_space("/"),
"diskTotal" => disk_total_space("/"),
"serverTime" => date('m. d. Y H:i:s'),
"serverTimeZone" => date('e'),
];
$this->response($response);
}
public function logStatus()
{
$logKeeper = new LogMaintainer();
$response = $logKeeper::getStats();
$this->response($response);
}
}

View File

@ -1,85 +0,0 @@
<?php
class UpdatesApi {
private function sendFile($path) {
header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK', true, 200);
header('Content-Type: application/octet-stream', true);
header('Content-Disposition: attachment; filename=' . basename($path));
header('Content-Length: ' . filesize($path), true);
header('x-MD5: ' . md5_file($path), true);
readfile($path);
}
private function validateHeader($headers){
if (
isset($_SERVER['HTTP_X_ESP8266_STA_MAC']) &&
isset($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'])
) {
return true;
}
return false;
}
public function default(){
$logManager = new LogManager('../logs/ota/'. date("Y-m-d").'.log');
$logManager->setLevel(LOGLEVEL);
$logManager->write("[Updater] Client Connected", LogRecordTypes::INFO);
// if($this->validateHeader($_SERVER)){
// header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Header");
// die();
// }
header('Content-type: text/plain; charset=utf8', true);
// //Filtrování IP adress
// if (DEBUGMOD != 1) {
// if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
// echo json_encode(array(
// 'state' => 'unsuccess',
// 'errorMSG' => "Using API from your IP insnt alowed!",
// ));
// header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
// $logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordTypes::INFO);
// exit();
// }
// }
$macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC'];
$localBinary = "../updater/" . str_replace(':', '', $macAddress) . ".bin";
$logManager->write("[Updater] url: " . $localBinary, LogRecordTypes::INFO);
$logManager->write("[Updater] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordTypes::INFO);
if (file_exists($localBinary)) {
$logManager->write("[Updater] version PHP: " . md5_file($localBinary), LogRecordTypes::INFO);
if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) {
$this->sendFile($localBinary);
//get device data
$device = DeviceManager::getDeviceByMac($macAddress);
$deviceName = $device['name'];
$deviceId = $device['device_id'];
//logfile write
$logManager->write("[Device] device_ID " . $deviceId . " was just updated to new version", LogRecordTypes::INFO);
$logManager->write("[Device] version hash: " . md5_file($localBinary), LogRecordTypes::INFO);
//notification
$notificationMng = new NotificationManager;
$notificationData = [
'title' => 'Info',
'body' => $deviceName.' was just updated to new version',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
if ($notificationData != []) {
$subscribers = $notificationMng->getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION] SENDING TO " . $subscriber['id'] . " ", LogRecordTypes::INFO);
$answer = $notificationMng->sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
} else {
header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304);
}
} else {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
}
die();
}
}

View File

@ -1,47 +0,0 @@
<?php
class UsersApi extends ApiController{
public function default(){
//$this->requireAuth();
$response = null;
$users = UserManager::getUsers(["user_id", "username", "at_home"]);
foreach ($users as $key => $user) {
$response[] = [
"userName" => $user['username'],
"homeStatus" => ($user['at_home'] == 'true') ? true : false,
"avatarUrl" => UserManager::getAvatarUrl($user['user_id']),
];
}
$this->response($response);
}
public function status(){
//$this->requireAuth();
$response = null;
$obj = $this->input;
$atHome = $obj['atHome'];
$user = UserManager::getUser($obj['user']);
$userAtHome = $user['at_home'];
$userId = $user['user_id'];
if (!empty($user)) {
if($userAtHome != $atHome){
UserManager::atHome($userId, $atHome);
}
}
$this->response(['value'=>'OK']);
}
public function subscribe(){
//$this->requireAuth();
$bearer = $_SERVER['HTTP_AUTHORIZATION'];
$authManager = new AuthManager();
$userId = $authManager->getUserId($bearer);
NotificationManager::addSubscriber($userId, $this->input['pushtoken']);
$this->response(['value'=>'OK']);
}
}

View File

@ -1,137 +0,0 @@
<?php
class WidgetApi extends ApiController
{
public function run($subDeviceId)
{
//$this->requireAuth();
$response = null;
if (RecordManager::getLastRecord($subDeviceId)['execuded'] === 0) {
throw new Exception("Unreachable", 409);
}
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
if ($subDeviceData['type'] == 'on/off') {
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($subDeviceData['device_id'], 'on/off', (int) !$lastValue);
$response = !$lastValue;
} else {
throw new Exception("Bad Request", 403);
}
$i = 0;
$timeout = 20;
while (RecordManager::getLastRecord($subDeviceId)['execuded'] == 0) {
if ($i == $timeout) {
throw new Exception("Timeout", 444);
}
$i++;
usleep(250000);
}
$this->response(['value' => $response]);
}
public function detail($subDeviceId, $period = "day")
{
//$this->requireAuth();
$groupBy = [
"year" => "month",
"month" => "day",
"day" => "hour",
"hout" => "minute",
];
$response = null;
$subDeviceData = SubDeviceManager::getSubdeviceDetailById($subDeviceId);
//TODO: zeptat se @Patrik Je Graf Dobře Seřazený na DESC ?
$events = RecordManager::getAllRecordForGraph($subDeviceId, $period, $groupBy[$period]);
if ( count($events) == 0){
throw new Exception("No Records", 404);
}
//Striping executed value from dataset if pasiv device such as Senzor ETC
if ($subDeviceData['type'] != "on/off") {
foreach ($events as $key => $event) {
unset($events[$key]['execuded']);
}
}
$LastRecordTime = new DateTime(reset($events)['time']);
$niceTime = Utilities::ago($LastRecordTime);
$labels = [];
$values = [];
foreach ($events as $key => $event) {
$recordDatetime = new DateTime($event['time']);
if ($key == 0){
$labels[] = 'now';
} else {
$labels[] = $recordDatetime->format('H:i');
}
$values[] = [
'y' => $event['value'],
't' => $recordDatetime->getTimestamp() * 1000,
];
}
$response = [
'room_id' => $subDeviceData['room_id'],
'device_id' => $subDeviceData['device_id'],
'lastConnectionTime' => (empty($niceTime) ? "00:00" : $niceTime),
'records' => $events,
'graph' => [
'type' => $this->getDeviceConfig($subDeviceData['type'])['graph'],
'data' => [
'labels' => $labels,
'datasets' => [[
//'label' => 'FUCK you',
'data' => $values,
]],
],
'options' => [
'scales' => [
'xAxis' => [[
'type' => 'time',
'distribution' => 'linear',
]],
],
'legend' => [
'display' => false
],
'tooltips' => [
'enabled' => true
],
'hover' => [
'mode' => true
],
],
],
];
//TODO: Make Cleaner
if (isset(RANGES[$subDeviceData['type']])){
$response['graph']['options']['scales']['yAxes'] = [[
'ticks' => [
'min' => RANGES[$subDeviceData['type']]['min'],
'max' => RANGES[$subDeviceData['type']]['max'],
'steps' => RANGES[$subDeviceData['type']]['scale'],
]
]];
}
$this->response($response);
}
private function getDeviceConfig($type){
if (isset(RANGES[$type])){
return RANGES[$type];
}
return RANGES[''];
}
}

View File

@ -1,14 +0,0 @@
<?php
class ExampleController extends Controller{
public function index(){
$this->view->title = 'Example title';
$this->view->render('example.phtml');
}
public function subpage(){
echo 'subpage';
}
}

View File

@ -1,77 +0,0 @@
<?php
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['modalFinal']) && $_POST['action'] == "add") {
$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
$value = $_POST['atSelector'];
if ($_POST['atSelector'] == 'time'){
$value = $_POST['atSelectorValue'];
} else if ($_POST['atSelector'] == 'atDeviceValue') {
$value = json_decode($_POST['atSelectorValue']);
} else if ($_POST['atSelector'] == 'inHome' || $_POST['atSelector'] == 'outHome') {
$value = UserManager::getUserData('user_id');
}
$ifCode = json_encode([
"type" => $_POST['atSelector'],
"value" => $value,
], JSON_PRETTY_PRINT);
$onDays = $_POST['atDays'];
//Debug
// if (DEBUGMOD == 1) {
// echo '<pre>';
// echo $permissionsInJson;
// echo $deviceId;
// var_dump(json_decode ($permissionsInJson));
// echo '</pre>';
// echo '<a href="' . BASEDIR .'">CONTINUE</a>';
// die();
// }
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode);
header('Location: ' . BASEURL . strtolower(basename(__FILE__, '.php')));
die();
} else if (isset($_POST['modalFinal']) && $_POST['action'] == "edit") {
$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
if (isset ($_POST['atDeviceValue'])) {
$subDeviceId = $_POST['atDeviceValue'];
$subDeviceValue = $_POST['atDeviceValueInt'];
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
$subDeviceMaster = SubDeviceManager::getSubDeviceMaster($subDeviceId,$subDevice['type']);
$device = [
'deviceID' => $subDeviceMaster['device_id'],
'type'=> $subDevice['type'],
'value'=> $subDeviceValue,
];
}
$value = $_POST['atSelector'];
if (isset($_POST['atTime'])){
$value = $_POST['atTime'];
} else if (isset($_POST['atDeviceValue'])) {
$value = $device;
} else if ($_POST['atSelector'] == 'inHome' || $_POST['atSelector'] == 'outHome') {
//TODO: opravit edit aby vkládal id původního uživatele
$value = UserManager::getUserData('user_id');
}
$value = (isset($_POST['atTime']) ? $_POST['atTime'] : (isset($_POST['atDeviceValue']) ? $device : $_POST['atSelector']));
$ifCode = json_encode([
"type" => $_POST['atSelector'],
"value" => $value,
], JSON_PRETTY_PRINT);
$onDays = ($_POST['day'] != '' ? json_encode($_POST['day']) : '');
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode, (isset ($_POST['automation_id']) ? $_POST['automation_id'] : ""));
header('Location: ' . BASEURL . strtolower(basename(__FILE__, '.php')));
die();
}
}
?>

View File

@ -1,36 +0,0 @@
<?php
if (!empty ($_POST)){
$deviceManager = new DeviceManager ();
$subDeviceManager = new SubDeviceManager ();
if (!empty ($_FILES['deviceFirmware']) && !empty ($_FILES['deviceFirmware']['tmp_name']) && !empty ($_POST['deviceId'])) {
$file = $_FILES['deviceFirmware'];
$deviceMac = $deviceManager->getDeviceById ($_POST['deviceId'])['mac'];
$fileName = (!empty ($deviceMac) ? str_replace (":", "", $deviceMac) . ".bin" : "");
if ($fileName != "" && file_exists ("../updater/" . $fileName)) {
unlink("../updater/" . $fileName);
}
if ($fileName != "") {
copy ($file['tmp_name'], "../updater/" . $fileName);
}
}
if (isset ($_POST['deviceCommand']) && !empty ($_POST['deviceId'])) {
$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']));
}
if (isset ($_POST['deviceHistory']) && !empty ($_POST['deviceId'])) {
$subDeviceManager->editSubDevicesByDevice($_POST['deviceId'], array ('history' => $_POST['deviceHistory']));
}
header('Location: ' . BASEURL . str_replace(BASEDIR, "", $_SERVER['REQUEST_URI']));
die();
}

View File

@ -1,50 +0,0 @@
<?php
$userManager = new UserManager();
if (
isset($_POST['username']) &&
$_POST['username'] != '' &&
isset($_POST['password']) &&
$_POST['password'] != ''
){
$ota = false;
$userName = $_POST['username'];
$userPassword = $_POST['password'];
$rememberMe = (isset ($_POST['remember']) ? $_POST['remember'] : "");
$ota = $userManager->haveOtaEnabled($userName);
if ($ota == "") {
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
header('Location: ' . BASEURL . $landingPage);
die();
}
$_SESSION['USERNAME'] = $userName;
$_SESSION['PASSWORD'] = $userPassword;
$_SESSION['REMEMBER'] = $rememberMe;
$_SESSION['OTA'] = $ota;
} else if (
isset($_POST['otaCode']) &&
$_POST['otaCode'] != ''
) {
$otaCode = $_POST['otaCode'];
$otaSecret = $_POST['otaSecret'];
$ga = new PHPGangsta_GoogleAuthenticator();
$ota = $_SESSION['OTA'];
$userName = $_SESSION['USERNAME'];
$userPassword = $_SESSION['PASSWORD'];
$rememberMe = $_SESSION['REMEMBER'];
unset($_SESSION['OTA']);
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
header('Location: ' . BASEURL . '/');
echo 'OK';
} else {
echo 'FAILED';
}
//TODO: upravi a ověřit jeslti ja zabezpečené
//TODO:
die();
}

View File

@ -1,75 +0,0 @@
<?php
$userManager = new UserManager();
if (
isset($_POST['username']) &&
$_POST['username'] != '' &&
isset($_POST['password']) &&
$_POST['password'] != ''
){
$ota = false;
$userName = $_POST['username'];
echo $_POST['username'];
$userPassword = $_POST['password'];
$state = $_POST["state"];
$clientId = $_POST["clientId"];
$ota = $userManager->haveOtaEnabled($userName);
if ($ota == "") {
$token = (new AuthManager)->getToken($userName,$userPassword, $clientId);
if (!$token) {
throw new Exception("Auth failed", 401);
}
$get = [
"access_token"=>$token,
"token_type"=>"Bearer",
"state"=>$state,
];
header('Location: ' . $_POST["redirectUrl"] . '#' . http_build_query($get));
die();
}
$_SESSION['USERNAME'] = $userName;
$_SESSION['PASSWORD'] = $userPassword;
$_SESSION['OTA'] = $ota;
$_SESSION['STATE'] = $state;
$_SESSION['REDIRECT'] = $_POST["redirectUrl"];
$_SESSION['CLIENT'] = $clientId;
} else if (
isset($_POST['otaCode']) &&
$_POST['otaCode'] != ''
) {
$otaCode = $_POST['otaCode'];
$otaSecret = $_POST['otaSecret'];
$userName = $_SESSION['USERNAME'];
$userPassword = $_SESSION['PASSWORD'];
$ota = $_SESSION['OTA'];
$oauthState = $_SESSION['STATE'];
$oauthRedirect = $_SESSION['REDIRECT'];
$oauthClientId = $_SESSION['CLIENT'];
$ga = new PHPGangsta_GoogleAuthenticator();
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
$token = (new AuthManager)->getToken($userName,$userPassword, $oauthClientId);
if (!$token) {
throw new Exception("Auth failed", 401);
}
$get = [
"access_token"=>$token,
"token_type"=>"Bearer",
"state"=>$oauthState,
];
header('Location: ' . $oauthRedirect . '#' . http_build_query($get));
echo 'OK';
} else {
echo 'FAILED';
}
die();
}

View File

@ -1,28 +0,0 @@
<?php
if (!empty ($_POST)){
if (
isset ($_POST['name']) &&
$_POST['name'] != '' &&
!isset ($_POST['remove'])
) {
if ($_POST['status'] == "true") {
if (file_exists ($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php")) {
rename($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php", $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php");
}
} else {
if (file_exists ($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php")) {
rename($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php", $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php");
}
}
header('Location: ./plugins');
die();
}
if (
isset ($_POST['name']) &&
$_POST['name'] != '' &&
isset ($_POST['remove'])
) {
//
}
}

View File

@ -1,45 +0,0 @@
<?php
if (isset($_POST) && !empty($_POST)){
$userManager = new UserManager();
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
$oldPassword = $_POST['oldPassword'];
$newPassword = $_POST['newPassword1'];
$newPassword2 = $_POST['newPassword2'];
$userManager->changePassword($oldPassword, $newPassword, $newPassword2);
header('Location: ' . BASEURL . 'logout');
die();
} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
$userName = $_POST['userName'];
$password = $_POST['userPassword'];
$email = $_POST['userEmail'];
$userManager->createUser($userName, $password, $email);
header('Location: ' . BASEURL . 'setting');
die();
} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
$otaCode = $_POST['otaCode'];
$otaSecret = $_POST['otaSecret'];
$ga = new PHPGangsta_GoogleAuthenticator();
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
$userManager->setOta($otaCode, $otaSecret);
}
header('Location: ' . BASEURL . 'setting');
die();
} else if (isset ($_POST['userPermission']) && !empty ($_POST['userID'])) {
$userManager->setUserDataAdmin("permission", $_POST['userPermission'], $_POST['userID']);
header('Location: ' . BASEURL . 'setting');
die();
} else {
foreach ($_POST as $key => $value) {
if ($key == 'submit') continue;
$settingMng = new SettingsManager();
if ($settingMng->getByName($key)) {
$settingMng->update($key, $value);
}
}
header('Location: ' . BASEURL . 'setting');
die();
}
}

View File

@ -1,194 +0,0 @@
<?php
abstract class ChartJS
{
/**
* @var array chart data
*/
protected $_datasets = array();
/**
* @var array chart labels
*/
protected $_labels = array();
/**
* The chart type
* @var string
*/
protected $_type = '';
/**
* @var array Specific options for chart
*/
protected $_options = array();
/**
* @var string Chartjs canvas' ID
*/
protected $_id;
/**
* @var string Canvas width
*/
protected $_width;
/**
* @var string Canvas height
*/
protected $_height;
/**
* @var array Canvas attributes (class,
*/
protected $_attributes = array();
/**
* @var array Default colors
*/
protected static $_defaultColors = array('fill' => 'rgba(220,220,220,0.2)', 'stroke' => 'rgba(220,220,220,1)', 'point' => 'rgba(220,220,220,1)', 'pointStroke' => '#fff');
/**
* Add label(s)
* @param array $labels
* @param bool $reset
*/
public function addLabels(array $labels, $reset = false)
{
if ($reset) {
$this->_labels = array();
}
$this->_labels = $this->_labels + $labels;
}
/**
* Add dataset
* @param $dataset
* @param $reset
*/
public function addDataset($dataset, $reset)
{
if ($reset) {
$this->_datasets = array();
}
$this->_datasets += $dataset;
}
public function __construct($id = null, $width = '', $height = '', $otherAttributes = array())
{
if (!$id) {
$id = uniqid('chartjs_', true);
}
$this->_id = $id;
$this->_width = $width;
$this->_height = $height;
// Always save otherAttributes as array
if ($otherAttributes && !is_array($otherAttributes)) {
$otherAttributes = array($otherAttributes);
}
$this->_attributes = $otherAttributes;
}
/**
* This method allows to echo ChartJS object and directly renders canvas (instead of using ChartJS->render())
*/
public function __toString()
{
return $this->renderCanvas();
}
public function renderCanvas()
{
$data = $this->_renderData();
$options = $this->_renderOptions();
$height = $this->_renderHeight();
$width = $this->_renderWidth();
$attributes = $this->_renderAttributes();
$canvas = '<canvas id="' . $this->_id . '" data-chartjs="' . $this->_type . '"' . $height . $width . $attributes . $data . $options . '></canvas>';
return $canvas;
}
/**
* Prepare canvas' attributes
* @return string
*/
protected function _renderAttributes()
{
$attributes = '';
foreach ($this->_attributes as $attribute => $value) {
$attributes .= ' ' . $attribute . '="' . $value . '"';
}
return $attributes;
}
/**
* Prepare width attribute for canvas
* @return string
*/
protected function _renderWidth()
{
$width = '';
if ($this->_width) {
$width = ' width="' . $this->_width . '"';
}
return $width;
}
/**
* Prepare height attribute for canvas
* @return string
*/
protected function _renderHeight()
{
$height = '';
if ($this->_height) {
$height = ' height="' . $this->_height . '"';
}
return $height;
}
/**
* Render custom options for the chart
* @return string
*/
protected function _renderOptions()
{
if (empty($this->_options)) {
return '';
}
return ' data-options=\'' . json_encode($this->_options) . '\'';
}
/**
* Prepare data (labels and dataset) for the chart
* @return string
*/
protected function _renderData()
{
$array_data = array('labels' => array(), 'datasets' => array());
$i = 0;
foreach ($this->_datasets as $line) {
$this->_completeColors($line['options'], $i);
$array_data['datasets'][] = $line['options'] + array('data' => $line['data']);
$i++;
}
$array_data['labels'] = $this->_labels;
return ' data-data=\'' . json_encode($array_data) . '\'';
}
/**
* Set default colors
* @param array $defaultColors
*/
public static function setDefaultColors(array $defaultColors)
{
self::$_defaultColors = $defaultColors;
}
/**
* @param array $color
*/
public static function addDefaultColor(array $color)
{
if (!empty($color['fill']) && !empty($color['stroke']) && !empty($color['point']) && !empty($color['pointStroke'])) {
self::$_defaultColors[] = $color;
} else {
trigger_error('Color is missing to add this theme (need fill, stroke, point and pointStroke) : color not added', E_USER_WARNING);
}
}
protected function _completeColors(&$options, &$i)
{
if (empty(static::$_defaultColors[$i])) {
$i = 0;
}
$colors = static::$_defaultColors[$i];
foreach (static::$_colorsRequired as $name) {
if (empty($options[$name])) {
$shortName = str_replace('Color', '', $name);
if (empty($colors[$shortName])) {
$shortName = static::$_colorsReplacement[$shortName];
}
$options[$name] = $colors[$shortName];
}
}
}
}

View File

@ -1,21 +0,0 @@
<?php
class ChartJS_Line extends ChartJS
{
protected $_type = 'Line';
protected static $_colorsRequired = array('fillColor', 'strokeColor', 'pointColor', 'pointStrokeColor', 'pointHighlightFill', 'pointHighlightStroke');
protected static $_colorsReplacement = array('pointHighlightFill' => 'point', 'pointHighlightStroke' => 'pointStroke');
/**
* Add a set of data
* @param array $data
* @param array $options
* @param null $name Name cas be use to change data / options later
*/
public function addLine($data = array(), $options = array(), $name = null)
{
if (!$name) {
$name = count($this->_datasets) + 1;
}
$this->_datasets[$name]['data'] = $data;
$this->_datasets[$name]['options'] = $options;
}
}

View File

@ -1,129 +0,0 @@
<?php
class ChartScale{
const HOUR = 'info';
const DAY = 'warning';
const MONTH = 'warning';
const YEAR = 'error';
}
class ChartManager{
function generateChart($data, $min = 0, $max = 100) {
echo '<br>Aktuální Hodnota: '.$data[0]['value'];
echo "<style>
.sloupec {
border-top: solid 2px red;
}
</style>";
echo '<div class=graph>';
echo '<div class="posuv " graf-max="'.$max.'" graf-min='.$min.'>';
for ($valuesRow = 0; $valuesRow < count($data); $valuesRow++) {
$row = $data[$valuesRow];
echo '<div class="sloupec " name="sloupec" value="' . $row['value'] . '" data-toggle="tooltip" title=""></div>';
}
echo '</div>';
echo '</div>';
echo '<script src="./include/js/chartDrwer.js"></script>';
echo 'Poslední Update: ';
echo '<style>
.graph {
width: 100%;
overflow: hidden;
margin-top: auto;
}
.posuv {
display: flex;
height: 200px;
background-image: url(./img/graph.png);
padding: 20px;
background-repeat: repeat;
border-bottom: 1px solid black;
}
.sloupec {
border-top: solid 2px blue;
background-color: grey;
float: left;
margin: auto 0 0;
display: inline-block;
width: 1%;
}
</style>
<script>
var posuvList = document.getElementsByClassName("posuv");
var maxHeight = posuvList[0].clientHeight;
for (i = 0; i < posuvList.length; i++) {
var maxPx = 0;
var grafMax = Number(posuvList[i].getAttribute("graf-max")); //100%
var grafMin = Number(posuvList[i].getAttribute("graf-min")); //0%
if (grafMin == 0 && grafMax == 100) {
var onePercent = 1;
} else {
var stepsBetWene = grafMax;
if (grafMin !== 0) {
if (grafMin < 0) {
stepsBetWene = grafMax + Math.abs(grafMin);
}
if (grafMin > 0) {
stepsBetWene = grafMax - grafMin;
}
}
var onePercent = stepsBetWene / 100;
}
var sloupceList = posuvList[i].querySelectorAll(".sloupec");
for (ai = 0; ai < sloupceList.length; ai++) {
var onePxPercent = maxHeight / 100;
var heightInPercent =
Math.abs(sloupceList[ai].getAttribute("value")) / onePercent;
var outputPx = onePxPercent * heightInPercent;
sloupceList[ai].style.height = outputPx + "px";
}
}
</script>';
}
function generateChartData(int $subDeviceId, string $periode, string $groupBy) {
$chartData = [];
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
$records = RecordManager::getAllRecordForGraph($subDeviceId, $periode, $groupBy);
$array = array_column($records, 'value');
$arrayTime = array_column($records, 'time');
$output = [];
foreach ($array as $key => $value) {
$output[$key]['y'] = $value;
if ($subDevice['type'] == 'light'){
if ($value > 810){
$output[$key]['y'] = 1;
} else {
$output[$key]['y'] = 0;
}
}
$timeStamp = new DateTime($arrayTime[$key]);
$output[$key]['t'] = $timeStamp->format("Y-m-d") . 'T' . $timeStamp->format("H:i:s") . 'Z';
}
$data = json_encode($output);
$data = $output;
$arrayTimeStamps = array_column($records, 'time');
foreach ($arrayTimeStamps as $key => $value) {
$arrayTimeStamps[$key] = (new DateTime($value))->format(TIMEFORMAT);
}
$chartData['graphRange'] = RANGES[$subDevice['type']];
$chartData['graphType'] = RANGES[$subDevice['type']]['graph'];
$chartData['graphData'] = $data;
return $chartData;
}
}
?>

View File

@ -1,121 +0,0 @@
<?php
/**
* [InputTypes datatype for input types]
*/
class InputTypes
{
const TEXT = 'text';
const NUMBER = 'number';
const COLOR = 'color';
const CHECK = 'checkbox';
const BUTTON = 'button';
const DATE = 'date';
const DATETIME = 'datetime';
const SUBMIT = 'submit';
const HIDEN = 'hidden';
const EMAIL = 'email';
}
/**
* [Form Form Generator Class]
*/
class Form {
public $formContent = "";
private $formName;
private $formId;
private $method;
private $action;
/**
* [__construct description]
* @param String $name [description]
* @param String $id [description]
* @param String $method [description]
* @param String $action [description]
*/
function __construct(String $name, String $id, String $method, String $action) {
if ($name != "") {
$this->formName = 'name="'.$name.'"';
}
if ($id != "") {
$this->formId = 'id="'.$id.'"';
}
if ($method != "") {
$this->method = 'method="'.$method.'"';
}
if ($action != "") {
$this->$action = 'action="'.$action.'"';
}
}
/**
* [addInput description]
* @param String $type Type of input element (text, number, color,checkbox, button, date, datetime, submit)
* @param String $name name of element
* @param String $id id of element
* @param String $label label of element
* @param String $value value of element
* @param boolean $require require selector toggle
* @param boolean $enabled enable selector toggle
*/
function addInput(String $type, String $name, String $id, String $label, String $value, Bool $require = false, Bool $enabled = true){
$this->formContent .= '<div class="field">';
if ($label != "") {
$this->formContent .= '<div class="label">'.$label.'</div>';
}
$this->formContent .= '<input class="input" type="'.$type.'" name="'.$name.'" value="'.$value.'" ' . ($enabled ? '' : 'disabled') . ($require ? '' : 'required') .'>';
$this->formContent .= '</div>';
}
//TODO: add Group support
/**
* [addSelect description]
* @param String $name name of element
* @param String $id id of element
* @param String $label label of element
* @param Array $data array of options [value => valueName]
* @param boolean $multiple multiple selector toggle
* @param boolean $enabled enable selector toggle
*/
function addSelect(String $name, String $id, String $label, Array $data, Bool $multiple = false, Bool $require = false, Bool $enabled = true){
$this->formContent .= '<div class="field">';
if ($label != "") {
$this->formContent .= '<div class="label">'.$label.'</div>';
}
$this->formContent .= '<select class="input"' . ($multiple ? '' : 'multiple') . ($enabled ? '' : 'disabled') . ($require ? '' : 'required') .'>';
foreach ($data as $value => $text) {
$this->formContent .= '<option value="' . $value . '">' . $text . '</option>';
}
$this->formContent .= '</select>';
$this->formContent .= '</div>';
}
/**
* [addTextarea description]
* @param String $name name of element
* @param String $id id of element
* @param String $label label of element
* @param String $value value of element
* @param boolean $enabled enable selector toggle
*/
function addTextarea(String $name, String $id, String $label, Array $value, Bool $require = false, Bool $enabled = true){
$this->formContent .= '<div class="field">';
if ($label != "") {
$this->formContent .= '<div class="label">'.$label.'</div>';
}
$this->formContent .= '<textarea class="input"' . ($enabled ? '' : 'disabled') . ($require ? '' : 'required') .'>';
$this->formContent .= $value;
$this->formContent .= '</textarea>';
$this->formContent .= '</div>';
}
/**
* [render function whitch dysplay generated form]
*/
function render(){
self::addInput(InputTypes::SUBMIT, 'formSubmit', '', 'Submit', 'Submit');
$form = '<form '.$this->formName.$this->formId.$this->method.$this->action.'">';
$form .= $this->formContent;
$form .= '</form>';
echo $form;
}
}

View File

@ -1,480 +0,0 @@
<?php
class GoogleHome {
static function sync($requestId){
$devices = [];
$roomsData = RoomManager::getAllRooms();
foreach ($roomsData as $roomKey => $roomData) {
$devicesData = DeviceManager::getAllDevicesInRoom($roomData['room_id']);
foreach ($devicesData as $deviceKey => $deviceData) {
$traids = [];
$attributes = [];
//Google Compatibile Action Type
$actionType = GoogleHomeDeviceTypes::getAction($deviceData['type']);
if ($actionType == "") continue;
$subDevicesData = SubDeviceManager::getAllSubDevices($deviceData['device_id']);
foreach ($subDevicesData as $subDeviceKey => $subDeviceData) {
$deviceTraid = GoogleHomeDeviceTypes::getTraid($subDeviceData['type']);
if ($deviceTraid != "") {
$traids[] = $deviceTraid;
}
$deviceAttributes = GoogleHomeDeviceTypes::getAttribute($subDeviceData['type']);
if ($deviceAttributes != "") {
$attributes += $deviceAttributes;
}
}
if ($traids < 1){
continue;
}
$tempDevice = [
'id' => (string) $deviceData['device_id'],
'type' => $actionType,
'traits' => $traids,
'attributes' => $attributes,
'name' => [
'name' => $deviceData['name'],
],
'willReportState' => false,
'roomHint' => $roomData['name']
];
if ($tempDevice['attributes'] == null) unset($tempDevice['attributes']);
//traids & Attributes
$devices[] = $tempDevice;
}
}
$response = [
'requestId' => $requestId,
'payload' => [
'agentUserId'=>'651351531531',
'devices' => array_values( $devices ),
],
];
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
$apiLogManager->setLevel(LOGLEVEL);
$apiLogManager->write("[API][$requestId] request response\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
echo json_encode($response);
}
static function query($requestId, $payload){
$devices = [];
$num = 0;
foreach ($payload['devices'] as $deviceId) {
$subDevicesData = SubDeviceManager::getAllSubDevices($deviceId['id']);
$tempDevice[$deviceId['id']] = [
'online' => false,
'status' => 'OFFLINE',
];
foreach ($subDevicesData as $key => $subDeviceData) {
$lastRecord = RecordManager::getLastRecord($subDeviceData['subdevice_id']);
if ($lastRecord['execuded'] == 1){
$tempDevice[$deviceId['id']]['online'] = true;
$tempDevice[$deviceId['id']]['status'] = "SUCCESS";
} else {
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$tempDevice[$deviceId['id']]['online'] = true;
}
}
switch ($subDeviceData['type']) {
case 'temp_cont':
$tempDevice[$deviceId['id']]['thermostatMode'] = 'off';
if ($lastRecord['value'] != 0) {
$tempDevice[$deviceId['id']]['thermostatMode'] = 'heat';
}
$tempDevice[$deviceId['id']]['thermostatTemperatureAmbient'] = $lastRecord['value'];
$tempDevice[$deviceId['id']]['thermostatTemperatureSetpoint'] = $lastRecord['value'];
break;
case 'vol_cont':
$tempDevice[$deviceId['id']]['currentVolume'] = $lastRecord['value'];
break;
case 'media_apps':
$tempDevice[$deviceId['id']]['currentApplication'] = "kodi";
break;
case 'media_input':
$tempDevice[$deviceId['id']]['currentInput'] = "pc";
break;
case 'media_status':
$tempDevice[$deviceId['id']]['activityState'] = "ACTIVE";
$tempDevice[$deviceId['id']]['playbackState'] = "PLAYING";
break;
case 'on/off':
$tempDevice[$deviceId['id']]['on'] = ($lastRecord['value'] == 1 ? true : false);
break;
}
}
if ($lastRecord['execuded'] == 1){
$online = true;
$status = 'SUCCESS';
} else {
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;
}
}
$devices = $tempDevice;
/*if (count($devices)> 1){
$devices[] = $tempDevice;
}*/
}
$response = [
'requestId' => $requestId,
'payload' => [
'devices' => $devices,
],
];
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
$apiLogManager->write("[API][$requestId] request response\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
$apiLogManager->setLevel(LOGLEVEL);
echo json_encode($response);
}
static function execute($requestId, $payload){
$commands = [];
foreach ($payload['commands'] as $key => $command) {
foreach ($command['devices'] as $key2 => $device) {
$executionCommand = $command['execution'][0];
if (isset($command['execution'][$key])) {
$executionCommand = $command['execution'][$key];
}
$deviceType = GoogleHomeDeviceTypes::getType($executionCommand['command']);
$subDeviceId = SubDeviceManager::getSubDeviceByMasterAndType($device['id'], $deviceType)['subdevice_id'];
switch ($executionCommand['command']) {
case 'action.devices.commands.OnOff':
$commands[] = self::executeSwitch($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.ThermostatTemperatureSetpoint':
$commands[] = self::executeTermostatValue($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.ThermostatSetMode':
$commands[] = self::executeTermostatMode($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.setVolume':
$commands[] = self::executeVolume($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.appSelect':
$commands[] = self::executeApp($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.SetInput':
$commands[] = self::executeInput($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.mediaNext':
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.mediaPrevious':
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.mediaPause':
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.mediaResume':
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
break;
case 'action.devices.commands.mediaStop':
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
break;
}
}
}
$response = [
'requestId' => $requestId,
'payload' => [
'commands' => $commands,
],
];
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
$apiLogManager->setLevel(LOGLEVEL);
$apiLogManager->write("[API][EXECUTE][$requestId]\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
echo json_encode($response);
}
static function executeSwitch($subDeviceId, $executionCommand){
$value = 0;
$status = 'OFFLINE';
$online = false;
if ($executionCommand['params']['on']) $value = 1;
RecordManager::createWithSubId($subDeviceId, $value);
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;
}
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
$commandTemp = [
'ids' => [(string) $deviceId],
'status' => $status,
'states' => [
'on' => $executionCommand['params']['on'],
'online' => $online,
],
];
return $commandTemp;
}
static function executeTermostatValue($subDeviceId, $executionCommand){
$value = 0;
$status = 'OFFLINE';
$online = false;
if (isset($executionCommand['params']['thermostatTemperatureSetpoint'])) {
$value = $executionCommand['params']['thermostatTemperatureSetpoint'];
}
RecordManager::createWithSubId($subDeviceId, $value);
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $lastValue) {
if ($lastValue['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;;
}
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
$commandTemp = [
'ids' => [(string) $deviceId],
'status' => $status,
'states' => [
'thermostatMode' => 'heat',
'thermostatTemperatureSetpoint' => $value,
'thermostatTemperatureAmbient' => $value,
'online' => $online,
//ambient z dalšího zenzoru v roomu
],
];
return $commandTemp;
}
static function executeTermostatMode($subDeviceId, $executionCommand){
$mode = "off";
$value = 0;
$status = 'OFFLINE';
$online = false;
if (isset($executionCommand['params']['thermostatMode']) && $executionCommand['params']['thermostatMode'] != 'off') {
$mode = $executionCommand['params']['thermostatMode'];
$value = RecordManager::getLastRecordNotNull($subDeviceId)['value'];
}
RecordManager::createWithSubId($subDeviceId, $value);
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;
}
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
$commandTemp = [
'ids' => [(string) $deviceId],
'status' => $status,
'states' => [
'thermostatMode' => $mode,
'online' => $online,
],
];
return $commandTemp;
}
static function executeVolume($subDeviceId, $executionCommand){
//echo $executionCommand['params']['volumeLevel'];
$status = 'OFFLINE';
$online = false;
$currentVolume = RecordManager::getLastRecord($subDeviceId)['value'];
if (isset($executionCommand['params']['volumeLevel'])) {
RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['volumeLevel']);
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;
$currentVolume = $executionCommand['params']['volumeLevel'];
}
}
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
$commandTemp = [
'ids' => [(string) $deviceId],
'status' => $status,
'states' => [
'currentVolume' => $currentVolume,
'online' => $online,
],
];
return $commandTemp;
}
static function executeApp($subDeviceId, $executionCommand){
//echo $executionCommand['params']['newApplication'];
$status = 'OFFLINE';
$online = false;
$currentApplication = RecordManager::getLastRecord($subDeviceId)['value'];
if (isset($executionCommand['params']['newApplication'])) {
RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['newApplication']);
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;
$currentApplication = $executionCommand['params']['newApplication'];
}
}
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
$commandTemp = [
'ids' => [(string) $deviceId],
'status' => $status,
'states' => [
'currentApplication' => $currentApplication,
'online' => $online,
],
];
return $commandTemp;
}
static function executeInput($subDeviceId, $executionCommand){
//echo $executionCommand['params']['newInput'];
$status = 'OFFLINE';
$online = false;
$currentInput = RecordManager::getLastRecord($subDeviceId)['value'];
if (isset($executionCommand['params']['newInput'])) {
RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['newInput']);
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {
$waiting++;
}
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;
$currentInput = $executionCommand['params']['newInput'];
}
}
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
$commandTemp = [
'ids' => [(string) $deviceId],
'status' => $status,
'states' => [
'currentInput' => $currentInput,
'online' => $online,
],
];
return $commandTemp;
}
static function executeMediaCont($subDeviceId, $executionCommand){
$status = 'SUCCESS';
$online = true;
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
$commandTemp = [
'ids' => [(string) $deviceId],
'status' => $status,
'states' => [
'online' => $online,
],
];
return $commandTemp;
}
}

View File

@ -1,34 +0,0 @@
<?php
class Partial{
private $assignedValues = [];
private $partBuffer;
private $path;
private $debug;
function __construct($path = "", $debug = false) {
$this->debug = $debug;
if (!empty('../app/views/templates/part/' . $path . '.phtml') && file_exists('../app/views/templates/part/' . $path . '.phtml')) {
$this->path = $path;
} else {
echo '<pre>';
echo 'PHTML: Parial File ' . $path . ' not found';
echo '</pre>';
die();
}
}
function prepare($searchS, $repleaceS) {
if (!empty($searchS)) {
$this->assignedValues[strtoupper($searchS)] = $repleaceS;
}
echo ($this->debug == true ? var_dump($this->assignedValues) : '');
}
function render() {
if (!empty($this->assignedValues)){
extract($this->assignedValues);
}
require('../app/views/templates/part/' . $this->path . '.phtml');
}
}

View File

@ -1,217 +0,0 @@
<?php
/**
*
*/
class Utilities
{
static function cleanString($text)
{
$utf8 = array(
'/[áàâãªä]/u' => 'a',
'/[ÁÀÂÃÄ]/u' => 'A',
'/[ÍÌÎÏ]/u' => 'I',
'/[íìîï]/u' => 'i',
'/[ěéèêë]/u' => 'e',
'/[ĚÉÈÊË]/u' => 'E',
'/[óòôõºö]/u' => 'o',
'/[ÓÒÔÕÖ]/u' => 'O',
'/[úùûü]/u' => 'u',
'/[ÚÙÛÜ]/u' => 'U',
'/Š/' => 'S',
'/š/' => 's',
'/Č/' => 'C',
'/č/' => 'c',
'/ř/' => 'r',
'/Ř/' => 'R',
'/Ý/' => 'Y',
'/ý/' => 'y',
'/ç/' => 'c',
'/Ç/' => 'C',
'/ñ/' => 'n',
'/Ñ/' => 'N',
'//' => '-', // UTF-8 hyphen to "normal" hyphen
'/[]/u' => ' ', // Literally a single quote
'/[“”«»„]/u' => ' ', // Double quote
'/ /' => ' ', // nonbreaking space (equiv. to 0x160)
);
return preg_replace(array_keys($utf8), array_values($utf8), $text);
}
static function stringInsert($str, $insertstr, $pos)
{
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
return $str;
}
/**
* [generateGraphJson description]
* @param string $type [line/bar]
* @param array $data [description]
* @param array $options [description]
* @return [type] [description]
*/
static function generateGraphJson(string $type = 'line', array $data = [], array $options = [])
{
$array = [
'type' => $type,
'data' => [
'datasets' => [
[
'data' => $data,
'borderColor' => "#d4def7",
'backgroundColor' => "#d4def7"
]
]
],
'options' => [
'scales' => [
'xAxes' => [
[
'type' => 'time',
'distribution' => 'linear',
]
],
'yAxes' => [
[
'ticks' => [
'min' => $options['min'],
'max' => $options['max'],
'steps' => $options['scale']
]
]
]
],
'legend' => [
'display' => false
],
'tooltips' => [
'enabled' => true
],
'hover' => [
'mode' => true
]
]
];
return json_encode($array, JSON_PRETTY_PRINT);
}
static function ago($datetime)
{
$interval = date_create('now')->diff($datetime);
$suffix = ($interval->invert ? ' ago' : '');
if ($v = $interval->y >= 1) return self::pluralize($interval->m, 'month') . $suffix;
if ($v = $interval->d >= 1) return self::pluralize($interval->d, 'day') . $suffix;
if ($v = $interval->h >= 1) return self::pluralize($interval->h, 'hour') . $suffix;
if ($v = $interval->i >= 1) return self::pluralize($interval->i, 'minute') . $suffix;
return self::pluralize($interval->s, 'second') . $suffix;
}
static function pluralize($count, $text)
{
return $count . (($count == 1) ? (" $text") : (" ${text}s"));
}
static function checkOperator($value1, $operator, $value2)
{
switch ($operator) {
case '<': // Less than
return $value1 < $value2;
case '<=': // Less than or equal to
return $value1 <= $value2;
case '>': // Greater than
return $value1 > $value2;
case '>=': // Greater than or equal to
return $value1 >= $value2;
case '==': // Equal
return ($value1 == $value2);
case '===': // Identical
return $value1 === $value2;
case '!==': // Not Identical
return $value1 !== $value2;
case '!=': // Not equal
case '<>': // Not equal
return $value1 != $value2;
case '||': // Or
case 'or': // Or
return $value1 || $value2;
case '&&': // And
case 'and': // And
return $value1 && $value2;
case 'xor': // Or
return $value1 xor $value2;
default:
return FALSE;
} // end switch
}
static function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
/**
* Sort Array by keys
*
* @param array $data
* @param [type] $key
* @param string $operator ('asc'/'desc')
* @return void
*/
static function sortArrayByKey($data = [], $key, $operator = "asc")
{
if ($operator == "asc") {
uasort($data, function ($a, $b) use ($key) {
$SortA = $a[$key];
$SortB = $b[$key];
if ($key == "room_id") {
$SortA = RoomManager::getRoomName($SortA);
$SortB = RoomManager::getRoomName($SortB);
}
if ($SortA == $SortB) return 0;
return ($SortA < $SortB) ? -1 : 1;
});
} else {
uasort($data, function ($a, $b) use ($key) {
$SortA = $a[$key];
$SortB = $b[$key];
if ($key == "room_id") {
$SortA = RoomManager::getRoomName($SortA);
$SortB = RoomManager::getRoomName($SortB);
}
if ($SortA == $SortB) return 0;
return ($SortA > $SortB) ? -1 : 1;
});
}
return $data;
}
}

View File

@ -1,70 +0,0 @@
<?php
class AuthManager {
public function getToken($username, $password, $userAgent = null){
if ($userAgent == null) {
$userAgent = $_SERVER['HTTP_USER_AGENT'];
}
$userManager = new UserManager();
if ($username != '' || $password != ''){
$userLogedIn = $userManager->loginNew($username, $password);
if ($userLogedIn != false){
// Create token header as a JSON string
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
// Create token payload as a JSON string
$payload = json_encode([
'user_id' => $userLogedIn,
'exp' => date('Y-m-d H:i:s',strtotime("+90 Days")),
'iat' => date('Y-m-d H:i:s',time()),
]);
// Encode Header to Base64Url String
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
// Create Signature Hash
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true);
// Encode Signature to Base64Url String
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
// Create JWT
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
$token = [
'user_id' => $userLogedIn,
'user_agent' => $userAgent,
'token' => $jwt,
'expire' => date('Y-m-d H:i:s',strtotime("+90 Days")),
'issued' => date('Y-m-d H:i:s',time()),
];
if (Db::add ('tokens', $token)){
return $jwt;
}
}
}
return false;
}
public function deleteToken($token){
Db::command ('DELETE FROM tokens WHERE token=?', array ($token));
return true;
}
public function validateToken($token){
list($type, $hash) = explode(' ', $token);
$tokens = Db::loadAll('SELECT * FROM tokens WHERE token = ? AND expire >= CURRENT_TIMESTAMP AND blocked = 0;', array($hash));
if ($type == 'Bearer' && count($tokens) == 1) {
return true;
} else if (count($tokens) == 0) {
return false;
};
return false;
}
public function getUserId($bearer){
$token = explode(' ', $bearer)[1];
$userid = Db::loadOne('SELECT user_id FROM tokens WHERE token = ? AND expire >= CURRENT_TIMESTAMP AND blocked = 0;', array($token))['user_id'];
return $userid;
}
}

View File

@ -1,175 +0,0 @@
<?php
class AutomationManager{
public static $automation;
public static function remove($automationId) {
return Db::command ('DELETE FROM automation WHERE automation_id=?', array ($automationId));
}
public static function deactive($automationId) {
$automation = Db::loadOne ("SELECT * FROM automation WHERE automation_id=?" , array ($automationId));
$flipedValue = ($automation['active'] == 1 ? 0 : 1);
return Db::command ('UPDATE automation SET active = ? WHERE automation_id=?', array ($flipedValue,$automationId));
}
public static function restart($automationId) {
return Db::command ('UPDATE automation SET executed = 0 WHERE automation_id=?', array ($automationId));
}
public static function create ($name, $onDays, $doCode, $ifCode, $automationId = "") {
$userId = UserManager::getUserData('user_id');
$scene = array (
'name' => $name,
'owner_id' => $userId,
'on_days' => $onDays,
'if_something' => $ifCode,
'do_something' => $doCode,
);
try {
if ($automationId == "") {
Db::add ('automation', $scene);
} else {
Db::edit ('automation', $scene, 'WHERE automation_id = ?', array ($automationId));
}
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getAll(){
return Db::loadAll ("SELECT * FROM automation");
}
public static function executeAll(){
global $logManager;
$automations = Db::loadAll ("SELECT * FROM automation");
$dayNameNow = strtolower (date('D', time()));
foreach ($automations as $automation) {
$onValue = json_decode($automation['if_something'], true);
$sceneDoJson = $automation['do_something'];
$actionDays = json_decode($automation['on_days'], true);
$value = time();
$run = false;
$restart = false;
if ($automation['active'] == 1 && $automation['locked'] != 1){
Db::edit('automation', array('locked' => 1), 'WHERE automation_id = ?', array($automation['automation_id']));
if (in_array($dayNameNow, $actionDays)){
if (in_array($onValue['type'], ['sunSet', 'sunRise', 'time','now'])) {
if ($onValue['type'] == 'sunSet') {
$value = date_sunset($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90);
} else if ($onValue['type'] == 'sunRise') {
$value = date_sunrise($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90);
} else if ($onValue['type'] == 'time') {
$onValue = explode(':',$onValue['value']);
$today = date_create('now');
$onValue = $today->setTime($onValue[0], $onValue[1]);
$value = $today->getTimestamp();
}
if (time() > $value && $automation['executed'] == 0){
$run = true;
} else if (time() < $value && $automation['executed'] == 1) { //recovery realowing of automation
$restart = true;
}
} else if ($onValue['type'] == 'outHome') {
//TODO: Add Ovner to automation
$userHomeStatus = UserManager::getUserData('at_home', $onValue['value']);
if ($userHomeStatus == 'false' && $automation['executed'] == 0) {
$run = true;
} else if ($userHomeStatus == 'true' && $automation['executed'] == 1) {
$restart = true;
}
} else if ($onValue['type'] == 'inHome') {
//TODO: Add Ovner to automation
$userHomeStatus = UserManager::getUserData('at_home', $onValue['value']);
if ($userHomeStatus == 'true' && $automation['executed'] == 0) {
$run = true;
} else if ($userHomeStatus == 'false' && $automation['executed'] == 1) {
$restart = true;
}
} else if ($onValue['type'] == 'noOneHome') {
$users = UserManager::getUsers();
$membersHome = 0;
foreach ($users as $key => $user) {
if ($user['at_home'] == 'true'){
$membersHome++;
}
}
if ($membersHome == 0 && $automation['executed'] == 0) {
$run = true;
} else if ($membersHome > 0 && $automation['executed'] == 1){
$restart = true;
}
} else if ($onValue['type'] == 'someOneHome') {
$users = UserManager::getUsers();
$membersHome = 0;
foreach ($users as $key => $user) {
if ($user['at_home'] == 'true'){
$membersHome++;
}
}
if ($membersHome == 0 && $automation['executed'] == 1) {
$restart = true;
} else if ($membersHome > 0 && $automation['executed'] == 0){
$run = true;
}
} else if ($onValue['type'] == 'atDeviceValue') {
$subDeviceId = SubDeviceManager::getSubDeviceByMaster($onValue['value']['deviceID'], $onValue['value']['type'])["subdevice_id"];
$lastValue = RecordManager::getLastRecord($subDeviceId);
if ($lastValue['value'] == $onValue['value']['value'] && $automation['executed'] == 0) {
$run = true;
} else if ($lastValue['value'] != $onValue['value']['value'] && $automation['executed'] == 1){
$restart = true;
}
}
//finalization
if ($run) {
$body = '';
$sceneDoArray = json_decode($sceneDoJson);
foreach ($sceneDoArray as $deviceId => $deviceState) {
RecordManager::create($deviceId, 'on/off', $deviceState);
}
$subscribers = NotificationManager::getSubscription();
$i = 0;
$notificationMng = new NotificationManager;
$notificationData = [
'title' => 'Automatization',
'body' => 'Automatization '.$automation['name']." was just executed",
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION/AUTOOMATION] SENDING TO" . $subscriber['id'] . " ");
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was executed");
Db::edit('automation', array('executed' => 1, 'execution_time' => date("Y-m-d H:i:s")), 'WHERE automation_id = ?', array($automation['automation_id']));
} else if ($restart) {
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was restarted");
Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
}
Db::edit('automation', array('locked' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
}
}
}
}
}

View File

@ -1,129 +0,0 @@
<?php
class ChartScale{
const HOUR = 'info';
const DAY = 'warning';
const MONTH = 'warning';
const YEAR = 'error';
}
class ChartManager{
function generateChart($data, $min = 0, $max = 100) {
echo '<br>Aktuální Hodnota: '.$data[0]['value'];
echo "<style>
.sloupec {
border-top: solid 2px red;
}
</style>";
echo '<div class=graph>';
echo '<div class="posuv " graf-max="'.$max.'" graf-min='.$min.'>';
for ($valuesRow = 0; $valuesRow < count($data); $valuesRow++) {
$row = $data[$valuesRow];
echo '<div class="sloupec " name="sloupec" value="' . $row['value'] . '" data-toggle="tooltip" title=""></div>';
}
echo '</div>';
echo '</div>';
echo '<script src="./include/js/chartDrwer.js"></script>';
echo 'Poslední Update: ';
echo '<style>
.graph {
width: 100%;
overflow: hidden;
margin-top: auto;
}
.posuv {
display: flex;
height: 200px;
background-image: url(./img/graph.png);
padding: 20px;
background-repeat: repeat;
border-bottom: 1px solid black;
}
.sloupec {
border-top: solid 2px blue;
background-color: grey;
float: left;
margin: auto 0 0;
display: inline-block;
width: 1%;
}
</style>
<script>
var posuvList = document.getElementsByClassName("posuv");
var maxHeight = posuvList[0].clientHeight;
for (i = 0; i < posuvList.length; i++) {
var maxPx = 0;
var grafMax = Number(posuvList[i].getAttribute("graf-max")); //100%
var grafMin = Number(posuvList[i].getAttribute("graf-min")); //0%
if (grafMin == 0 && grafMax == 100) {
var onePercent = 1;
} else {
var stepsBetWene = grafMax;
if (grafMin !== 0) {
if (grafMin < 0) {
stepsBetWene = grafMax + Math.abs(grafMin);
}
if (grafMin > 0) {
stepsBetWene = grafMax - grafMin;
}
}
var onePercent = stepsBetWene / 100;
}
var sloupceList = posuvList[i].querySelectorAll(".sloupec");
for (ai = 0; ai < sloupceList.length; ai++) {
var onePxPercent = maxHeight / 100;
var heightInPercent =
Math.abs(sloupceList[ai].getAttribute("value")) / onePercent;
var outputPx = onePxPercent * heightInPercent;
sloupceList[ai].style.height = outputPx + "px";
}
}
</script>';
}
function generateChartData(int $subDeviceId, string $periode, string $groupBy) {
$chartData = [];
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
$records = RecordManager::getAllRecordForGraph($subDeviceId, $periode, $groupBy);
$array = array_column($records, 'value');
$arrayTime = array_column($records, 'time');
$output = [];
foreach ($array as $key => $value) {
$output[$key]['y'] = $value;
if ($subDevice['type'] == 'light'){
if ($value > 810){
$output[$key]['y'] = 1;
} else {
$output[$key]['y'] = 0;
}
}
$timeStamp = new DateTime($arrayTime[$key]);
$output[$key]['t'] = $timeStamp->format("Y-m-d") . 'T' . $timeStamp->format("H:i:s") . 'Z';
}
$data = json_encode($output);
$data = $output;
$arrayTimeStamps = array_column($records, 'time');
foreach ($arrayTimeStamps as $key => $value) {
$arrayTimeStamps[$key] = (new DateTime($value))->format(TIMEFORMAT);
}
$chartData['graphRange'] = RANGES[$subDevice['type']];
$chartData['graphType'] = RANGES[$subDevice['type']]['graph'];
$chartData['graphData'] = $data;
return $chartData;
}
}
?>

View File

@ -1,41 +0,0 @@
<?php
class DashboardManager{
public static $devices;
static function getAllDashboards ($userId) {
return Db::loadAll ("SELECT * FROM dashboard WHERE user_id=?", array($userId));
}
static function getAllSubDevices ($userId) {
return Db::loadAll ("SELECT * FROM subdevices WHERE subdevice_id IN (SELECT subdevice_id FROM dashboard WHERE user_id=?)", array($userId));
}
static function getSubDevice ($userId, $subDeviceId) {
return Db::loadOne ("SELECT * FROM subdevices WHERE subdevice_id = (SELECT subdevice_id FROM dashboard WHERE user_id=? AND subdevice_id = ? )", array($userId, $subDeviceId));
}
static function Add ($subDeviceId) {
if (self::getSubDevice(UserManager::getUserData('user_id'), $subDeviceId) == null){
// to do: pokud existuje nepridej
//
//
$dashboardItem = array (
'user_id' => UserManager::getUserData('user_id'),
'subdevice_id' => $subDeviceId,
);
try {
Db::add ('dashboard', $dashboardItem);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
}
static function Remove ($subDeviceId){
$userId = UserManager::getUserData('user_id');
Db::command ('DELETE FROM dashboard WHERE subdevice_id=? AND user_id = ?', array ($subDeviceId, $userId));
}
}

View File

@ -1,110 +0,0 @@
<?php
class DeviceManager{
public static $devices;
static function getAllDevices () {
return Db::loadAll ("SELECT * FROM devices
WHERE approved != ?", Array(2));
}
static function setHeartbeat($deviceId){
self::edit($deviceId, ['heartbeat' => date("Y-m-d H:i:s", time())]);
}
static function getAllDevicesInRoom ($roomId = "") {
return Db::loadAll ("SELECT * FROM devices WHERE room_id = ? AND approved != ?", Array($roomId, 2));
}
static function getOtherDevices(){
return Db::loadAll ("SELECT * FROM devices WHERE room_id IS NULL ");
}
static function getDeviceByToken($deviceToken) {
return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken));
}
static function getDeviceByMac($deviceMac) {
return Db::loadOne("SELECT * FROM devices WHERE mac = ?", array($deviceMac));
}
static function getDeviceById($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, $type = "") {
$defaultRoom = RoomManager::getDefaultRoomId();
$device = array (
'name' => $name,
'token' => $token,
'room_id' => $defaultRoom,
);
if (!empty($type)) {
$device['type'] = $type;
}
try {
Db::add ('devices', $device);
return Db::loadOne("SELECT device_id FROM devices WHERE token = ?", array($token))['device_id'];
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function edit ($deviceId, $values = []) {
try {
Db::edit ('devices', $values, 'WHERE device_id = ?', array($deviceId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function editByToken ($token, $values = []) {
try {
Db::edit ('devices', $values, 'WHERE token = ?', array($token));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
/**
* [assignRoom Přiřazení zařízení do třídy]
* @param [type] $roomId [číslo místnosti do kter se zařízení přiřadit]
* @param [type] $deviceId [Číslo zařízení které chcete přiřadit do místnosti]
*/
public static function assignRoom ($roomId, $deviceId) {
$device = array (
'room_id' => $roomId,
);
try {
Db::edit ('devices', $device, 'WHERE device_id = ?', array($deviceId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
/**
* [delete Smazání zařízení]
* @param [type] $deviceId [Id zařízení ke smazání]
*/
public static function delete ($deviceId) {
Db::command ('DELETE FROM devices WHERE device_id=?', array ($deviceId));
}
public static function registeret ($deviceToken) {
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=?", array($deviceToken))) == 1 ? true : false);
}
public static function approved ($deviceToken) {
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=? AND approved = ?", array($deviceToken, 1))) == 1 ? true : false);
}
}
?>

View File

@ -1,11 +0,0 @@
<?php
class EmailManager {
public function SendTo ($pro, $predmet, $zprava) {
$email = "From: EnergyCounter@steelants.cz";
$email .= "\nMIME-Version: 1.0\n";
$email .= "Content-Type: text/html; charset=\"utf-8\"\n";
if (!mb_send_mail ($pro, $predmet, $zprava, $email)) {
throw new PDOException("!Email se nepodařilo odeslat!");
}
}
}

View File

@ -1,44 +0,0 @@
<?php
/**
*
*/
class FallbackManager
{
public $deviceDefinitions = "";
function __construct($deviceDefinition)
{
$this->deviceDefinitions = $deviceDefinition;
}
function check(){
//TODO: FIX IT
$allDevicesData = DeviceManager::getAllDevices();
foreach ($allDevicesData as $deviceKey => $deviceValue) {
$allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) {
if (!isset($this->deviceDefinitions[$subDeviceValue['type']]["fallBack"])) {
continue;
}
if (!isset($this->deviceDefinitions[$subDeviceValue['type']]["fallBackTime"])) {
continue;
}
$lastRecord = RecordManager::getLastRecord($subDeviceValue['subdevice_id']);
if ($lastRecord["value"] == $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]) {
continue;
}
$minutes = (time() - strtotime($lastRecord['time'])) / 60;
if ( $minutes > $this->deviceDefinitions[$subDeviceValue['type']]["fallBackTime"]){
RecordManager::create($deviceValue['device_id'], $subDeviceValue['type'], $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]);
}
}
}
}
}

View File

@ -1,60 +0,0 @@
<?php
/**
* Language Manager
*/
class LanguageManager
{
private $lngCode = 'en';
private $lngDatabase = [];
private $debug = false;
function __construct(string $lngCode, bool $debug = false)
{
$this->lngCode = $lngCode;
$this->debug = $debug;
}
function load()
{
$file = '../lang/en.php';
if (!file_exists($file)){
echo 'ERROR: en.php not found';
die();
//TODO add lng EXEPTIONS
}
$arrayFirst = include($file);
$file = '../lang/' . $this->lngCode . '.php';
$arraySecond = [];
if (file_exists($file)){
$arraySecond = include($file);
}
$this->lngDatabase = array_merge($arrayFirst, $arraySecond);
return true;
}
function get(string $stringKey)
{
if ($this->debug) {
return $stringKey;
}
if (isset($this->lngDatabase[$stringKey])) {
return $this->lngDatabase[$stringKey];
}
return $stringKey;
}
function echo(string $stringKey)
{
if ($this->debug) {
echo $stringKey;
return;
}
if (isset($this->lngDatabase[$stringKey])) {
echo $this->lngDatabase[$stringKey];
return;
}
echo $stringKey;
return;
}
}

View File

@ -1,78 +0,0 @@
<?php
class LogMaintainer
{
private function cleaningDir ($dir, $seconds) {
$todayFileName = date ("Y-m-d").'.log';
$logFiles = scandir ($dir);
foreach ($logFiles as $key => $file) {
if (in_array ($file,array (".", "..", ".gitkeep", $todayFileName)))
{
continue;
}
if (!is_dir($dir . $file)) {
if (strtotime(str_replace(".log", "", $file)) < (strtotime("now") - $seconds)) {
unlink ($dir . $file);
}
} else {
$this->cleaningDir ($dir . $file . "/", $seconds);
}
}
}
public function purge ($days) {
$seconds = $days * 86400;
$this->cleaningDir ('../logs/', $seconds);
}
public static function getStats(){
$stats = array(
'ERROR' => 0,
'WARNING' => 0,
'EXEPTION' => 0,
'INFO' => 0,
);
$result = array();
$result = self::logFinder ('../logs/', $result);
foreach ($result as $path => $files) {
foreach ($files as $file) {
# code...
$matches = array();
$re = '/\[(?:warning|error|info)\]/';
$str = file_get_contents($path . $file);
preg_match_all($re, $str, $matches);
if (count($matches[0]) == 0) continue;
foreach ($matches[0] as $match) {
switch($match){
case '[error]': $stats['ERROR']++; break;
case '[warning]': $stats['WARNING']++; break;
case '[exeption]': $stats['EXEPTION']++; break;
default: $stats['INFO']++; break;
}
}
}
}
return $stats;
}
private static function logFinder ($dir, $result) {
$logFiles = scandir ($dir);
foreach ($logFiles as $key => $file) {
if (in_array ($file,array (".", "..", ".gitkeep")))
{
continue;
}
if (!is_dir($dir . $file)) {
$result[$dir][] = $file;
} else {
$result = self::logFinder ($dir . $file . "/", $result);
}
}
return $result;
}
}

View File

@ -1,42 +0,0 @@
<?php
/**
*
*/
class LogManager
{
private $logFile;
private $logLevel = 1;
public function __construct($fileName = "")
{
if ($fileName == ""){
$fileName = '../logs/'. date("Y-m-d").'.log';
}
if(!is_dir("../logs/"))
{
mkdir("../logs/");
}
$this->logFile = fopen($fileName, "a") or die("Unable to open file!");
}
public function setLevel($type = LogRecordTypess::WARNING){
$this->logLevel = $type['level'];
}
public function write($value, $type = LogRecordTypess::ERROR){
if ($type['level'] <= $this->logLevel) {
$record = "[".date("H:m:s")."][".$type['identifier']."]" . $value . "\n";
fwrite($this->logFile, $record);
}
}
public function __destruct(){
if (isset($this->logFile) && $this->logFile != "Unable to open file!") {
fclose($this->logFile);
}
}
}

View File

@ -1,18 +0,0 @@
<?php
/**
*
*/
class NetvorkManager
{
function __construct()
{
// code...
}
function validateIp($ip = '0.0.0.0'){
if (!filter_var($ip, FILTER_VALIDATE_IP)){
return false;
}
}
}

View File

@ -1,109 +0,0 @@
<?php
/**
* Notification Manager
*/
//TODO: Working timestamp to $title
class NotificationManager
{
public static function addSubscriber($userID, $token){
if (!empty($userID) && !empty($token)) {
$notificationSubscriber = $subDeviceId = Db::loadOne('SELECT id FROM notifications WHERE token = ?;', array($token));
if ($notificationSubscriber == ''){
$notification = array (
'user_id' => $userID,
'token' => $token,
);
Db::add ('notifications', $notification);
}
}
}
public static function getSubscription () {
return Db::loadAll ("SELECT * FROM notifications");
}
public static function sendSimpleNotification(string $serverKey, string $to, array $data, bool $timeStamp = false){
$dataTemplate = [
'title' => '',
'body' => '',
'icon' => '',
];
if (array_diff_key ($dataTemplate , $data)){
return;
}
if ($timeStamp) {
$data['title'] = $data['title'] . date();
}
$notification = new Notification($serverKey);
$notification->to($to);
$notification->notification($data['title'], date("h:i") . " - " . $data['body'], $data['icon'], '');
$answer = $notification->send();
$notification = null;
return $answer;
}
}
class Notification
{
public $server_key = '';
public $jsonPayload = [
"to" => '',
"data" => [
"notification" => [
"body" => '',
"title" => '',
"icon" => '',
"click_action" => '',
]
]
];
function __construct($serverKey = '')
{
$this->server_key = $serverKey;
}
function to($to = ''){
$this->jsonPayload["to"] = $to;
}
function notification($title = '', $body = '', $icon = '', $action = '', bool $timeStamp = false)
{
if ($timeStamp) {
$data['title'] = $data['title'] . date();
}
$this->jsonPayload["data"]["notification"]["title"] = $title;
$this->jsonPayload["data"]["notification"]["body"] = $body;
$this->jsonPayload["data"]["notification"]["icon"] = $icon;
$this->jsonPayload["data"]["notification"]["click_action"] = $action;
}
function send(){
$data = json_encode($this->jsonPayload);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$this->server_key,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result === FALSE) {
die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
}

View File

@ -1,119 +0,0 @@
<?php
class RecordManager{
public static $records;
public static function createWithSubId ($subDeviceId, $value) {
try {
$record = [
'execuded' => 1,
];
Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
$record = array (
'subdevice_id' => $subDeviceId,
'value' => $value,
);
return Db::add ('records', $record);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function create ($deviceId, $type, $value) {
$subDeviceId = Db::loadOne('SELECT * FROM subdevices WHERE device_id = ? AND type = ?;', array($deviceId, $type))['subdevice_id'];
if ($subDeviceId == '') {
return false;
};
//Ochrana proti duplicitním hodnotám zapisují se jen změny
$lastRecord = self::getLastRecord($subDeviceId, 1);
if ($lastRecord['value'] == $value){
return false;
}
try {
$record = [
'execuded' => 1,
];
Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
$record = array (
'subdevice_id' => $subDeviceId,
'value' => $value,
);
return Db::add ('records', $record);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function setExecuted($recordId) {
try {
Db::edit ('records', ['execuded' => 1], 'WHERE record_id = ?', array($recordId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getRecordById($recordId) {
return Db::loadOne('SELECT * FROM records WHERE record_id = ?;', array($recordId));
}
public static function getLastInsertedRecordId() {
return Db::insertId();
}
public static function getLastRecord($subDeviceId, $num = 1) {
if ($num == 1)
return Db::loadOne('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC;', array($subDeviceId, 999));
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC LIMIT ?;', array($subDeviceId, 999, $num));
}
public static function getLastRecordNotNull($subDeviceId) {
return Db::loadOne('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC;', array($subDeviceId, 0));
}
public static function getAllRecord($subDeviceId, $timeFrom, $timeTo) {
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND time >= ? AND time <= ? AND value != ? ORDER BY time;', array($subDeviceId, $timeFrom, $timeTo, 999));
}
//TODO: Zeptat se @Patrik jestli je secure pak používat periodu přímo do SQL a pak pře url SQL Injection
public static function getAllRecordForGraph($subDeviceId, $period = "day", $groupBy = "hour") {
$periodLocal = '- 1' . strtoupper($period);
$dateTime = new DateTime();
$dateTime = $dateTime->modify($periodLocal);
$dateTime = $dateTime->format('Y-m-d H:i:s');
$groupBy = strtoupper($groupBy).'(time)';
$sql = 'SELECT value, time, execuded FROM records
WHERE
subdevice_id = ?
AND
value != 999
AND
time > ?
GROUP BY '.$groupBy.'
ORDER BY time Desc';
//TODO: Prasárna Opravit
return Db::loadAll($sql, array($subDeviceId, $dateTime));
}
public static function clean ($day) {
if (isset($day)) {
Db::command ('DELETE FROM records WHERE `time` < ADDDATE(NOW(), INTERVAL ? DAY);', array($day));
}
}
//TODO: zkontrolovat jestli neco nezbilo po smazaní
public static function cleanSubdeviceRecords ($subDeviceId) {
Db::command ('DELETE FROM records WHERE subdevice_id = ?);', array($subDeviceId));
}
public static function setHistory($subDeviceId){
$history = SubDeviceManager::getSubDevice($subDeviceId)['history'];
if ($history > 0) self::clean(-abs($history));
}
}
?>

View File

@ -1,44 +0,0 @@
<?php
class RoomManager{
public static $rooms;
static function getDefaultRoomId() {
$defaultRoom = Db::loadOne("SELECT `room_id` FROM `rooms` WHERE `default` = 1");
return $defaultRoom['room_id'];
}
static function getAllRooms () {
//TODO: ignore Widgets withoud data
$allRoom = Db::loadAll ("SELECT rooms.*, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id");
return $allRoom;
}
static function getRoomsDefault () {
//TODO: ignore Widgets withoud data
$allRoom = Db::loadAll ("SELECT rooms.room_id, rooms.name, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id;");
return $allRoom;
}
public static function getRoomName ($room_id) {
//TODO: ignore Widgets withoud data
$allRoom = Db::loadAlone ("SELECT name FROM rooms WHERE room_id=?", array ($room_id));
return $allRoom;
}
public static function create ($name) {
$room = array (
'name' => $name,
);
try {
Db::add ('rooms', $room);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function delete ($roomId) {
Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId));
}
}
?>

View File

@ -1,41 +0,0 @@
<?php
class SceneManager{
public static $scenes;
public static function create ($icon, $name, $doCode) {
$scene = array (
'icon' => $icon,
'name' => $name,
'do_something' => $doCode,
);
try {
Db::add ('scenes', $scene);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getAllScenes () {
return Db::loadAll ("SELECT * FROM scenes");
}
public static function getScene ($sceneId) {
return Db::loadOne("SELECT * FROM scenes WHERE scene_id = ?", array($sceneId));
}
public static function execScene ($sceneId) {
$sceneData = SceneManager::getScene($sceneId);
$sceneDoJson = $sceneData['do_something'];
$sceneDoArray = json_decode($sceneDoJson);
foreach ($sceneDoArray as $deviceId => $deviceState) {
RecordManager::create($deviceId, 'on/off', $deviceState);
}
return true;
}
public static function delete($sceneId){
Db::command ('DELETE FROM scenes WHERE scene_id=?', array ($sceneId));
}
}
?>

View File

@ -1,47 +0,0 @@
<?php
class SettingsManager{
static function getAllValues () {
return Db::loadAll ("SELECT * FROM settings");
}
static function getByName($settingName, $type = '') {
if ($type != '') return Db::loadOne("SELECT * FROM settings WHERE name = ? AND type = ?", array($settingName, $type));
return Db::loadOne("SELECT * FROM settings WHERE name = ?", array($settingName));
}
static function getSettingGroup($type) {
return Db::loadAll("SELECT * FROM settings WHERE type=?", array($type));
}
public static function create ($name, $value, $type = '') {
if (!self::getByName($name)){
$setting = array (
'name' => $name,
'value' => $value,
'type' => $type,
);
try {
Db::add ('settings', $setting);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
}
public static function update ($name, $value, $type = '') {
if (!self::getByName($name)){
self::create($name, $value, $type);
} else {
try {
Db::edit ('settings', [
'value' => $value
], 'WHERE name = ?', array($name));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
}
}
?>

View File

@ -1,117 +0,0 @@
<?php
class SubDeviceManager
{
public static $devices;
public static function getAllSubDevices($deviceId = null)
{
if ($deviceId == null) {
return Db::loadAll("SELECT * FROM subdevices");
}
return Db::loadAll("SELECT * FROM subdevices WHERE device_id = ?", array($deviceId));
}
public static function getSubDeviceMaster($subDeviceId)
{
return Db::loadOne("SELECT * FROM devices WHERE device_id = (SELECT device_id FROM subdevices WHERE subdevice_id = ?)", array($subDeviceId));
}
public static function getSubDeviceByMaster($deviceId, $subDeviceType = null)
{
if ($subDeviceType == null) {
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
} else {
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
}
}
public static function getSubDeviceByMasterAndType($deviceId, $subDeviceType = '')
{
if ($subDeviceType == '') {
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
} else {
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
}
}
public static function getSubDevice($subDeviceId)
{
return Db::loadOne("SELECT * FROM subdevices WHERE subdevice_id = ?;", array($subDeviceId));
}
public static function getSubDevicesTypeForMater($deviceId)
{
$parsedTypes = [];
$types = Db::loadAll("SELECT type FROM subdevices WHERE device_id = ?;", array($deviceId));
foreach ($types as $orderNum => $type) {
$parsedTypes[$orderNum] = $type['type'];
}
return $parsedTypes;
}
//check if dubdevice exist
//Add History to be set in Creation
public static function create($deviceId, $type, $unit)
{
$record = array(
'device_id' => $deviceId,
'type' => $type,
'unit' => $unit,
);
try {
Db::add('subdevices', $record);
} catch (PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function editSubDevicesByDevice ($deviceId, $subDeviceParameters) {
DB::edit('subdevices', $subDeviceParameters, 'WHERE device_id=?', array ($deviceId));
}
public static function remove($subDeviceId)
{
RecordManager::cleanSubdeviceRecords($subDeviceId);
return Db::loadAll("DELETE FROM subdevices WHERE subdevice_id = ?", array($subDeviceId));
}
public static function getSubdevicesByRoomIds($roomIds = NULL)
{
if (empty($roomIds)) return NULL;
//TODO: @Patrik Check line 89
$rows = Db::loadAll("
SELECT d.room_id, d.sleep_time, sd.subdevice_id, sd.device_id, d.icon, d.name, sd.type, sd.unit, r.value, r.time FROM subdevices sd
JOIN devices d ON sd.device_id = d.device_id
JOIN records r ON r.subdevice_id = sd.subdevice_id
WHERE d.room_id IN (" . str_repeat("?,", count($roomIds) - 1) . "?)
/*AND value != '999'*/
AND r.record_id IN (
SELECT MAX(record_id)
FROM records
GROUP BY subdevice_id
)
GROUP BY subdevice_id
ORDER BY d.name DESC
", $roomIds);
$ret = [];
foreach ($rows as $row) {
$ret[$row['room_id']][] = $row;
}
return $ret;
}
public static function getSubdeviceDetailById($subDeviceId){
if (empty($subDeviceId)) return NULL;
$rows = Db::loadOne("SELECT d.room_id, d.sleep_time, sd.subdevice_id, sd.type, sd.device_id FROM subdevices sd
JOIN devices d ON sd.device_id = d.device_id
WHERE sd.subdevice_id = ? ", [$subDeviceId]);
return $rows;
}
}

View File

@ -1,225 +0,0 @@
<?php
class UserManager
{
public static function getUsers ($filtr = ['*']) {
try {
$allUsers = Db::loadAll ("SELECT " . implode(",", $filtr) . " FROM users");
return $allUsers;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getUser ($userName) {
try {
$user = Db::loadOne ("SELECT * FROM users WHERE username = ?", [$userName]);
return $user;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getUserId ($userId) {
try {
$user = Db::loadOne ("SELECT * FROM users WHERE user_id = ?", [$userId]);
return $user;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getAvatarUrl($userId = null){
if ($userId == null) {
$email = self::getUserData('email');
}
else if ($userId != null){
$email = self::getUserData('email',$userId);
}
return 'https://secure.gravatar.com/avatar/' . md5( strtolower( trim( $email ) ) );
}
public static function login ($username, $password, $rememberMe) {
try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE (LOWER(username)=LOWER(?) OR LOWER(email)=LOWER(?))', array ($username, $username))) {
if ($user['password'] == UserManager::getHashPassword($password)) {
if (isset($rememberMe) && $rememberMe == 'true') {
setcookie ("rememberMe", self::setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
}
$_SESSION['user']['id'] = $user['user_id'];
unset($_POST['login']);
return "";
} else {
throw new PDOException("Heslo není správné!");
}
} else {
throw new PDOException("Uživatel s tím to jménem neexistuje!");
}
} catch(PDOException $error) {
$_SESSION['msg'] = $error->getMessage();
unset($_POST);
header('Location: ' . BASEURL . 'login');
die();
}
}
public static function loginNew ($username, $password) {
try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?) OR LOWER(email)=LOWER(?)', array ($username, $username))) {
if ($user['password'] == UserManager::getHashPassword($password)) {
return $user['user_id'];
} else {
return false;
}
} else {
return false;
}
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function isLogin () {
if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) {
return true;
} else {
if (isset ($_COOKIE['rememberMe'])){
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array (self::getDecryptedCookie($_COOKIE['rememberMe'])))) {
$_SESSION['user']['id'] = $user['user_id'];
return true;
}
}
}
return false;
}
public static function logout () {
unset($_SESSION['user']);
unset($_COOKIE['rememberMe']);
setcookie("rememberMe", 'false', 0 - time(), BASEDIR, $_SERVER['HTTP_HOST']);
session_destroy();
}
public static function setEncryptedCookie($value){
$first_key = base64_decode(FIRSTKEY);
$second_key = base64_decode(SECONDKEY);
$method = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivlen);
$newvalue_raw = openssl_encrypt($value, $method, $first_key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $newvalue_raw, $second_key, TRUE);
$newvalue = base64_encode ($iv.$hmac.$newvalue_raw);
return $newvalue;
}
public static function getDecryptedCookie($value){
$first_key = base64_decode(FIRSTKEY);
$second_key = base64_decode(SECONDKEY);
$c = base64_decode($value);
$method = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($method);
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, 32);
$newValue_raw = substr($c, $ivlen+32);
$newValue = openssl_decrypt($newValue_raw, $method, $first_key, OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $newValue_raw, $second_key, TRUE);
if (hash_equals ($hmac, $calcmac)) {
return $newValue;
}
return false;
}
public static function getUserData ($type, $userId = '') {
if ($userId == '') {
$userId = $_SESSION['user']['id'];
}
$user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($userId));
return $user[$type];
}
public static function setUserData ($type, $value) {
if (isset ($_SESSION['user']['id'])) {
Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $_SESSION['user']['id']));
}
}
public static function setUserDataAdmin ($type, $value, $id) {
if ($id) {
Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $id));
}
}
public static function getHashPassword ($password) {
$salt = "s0mRIdlKvI";
$hashPassword = hash('sha512', ($password . $salt));
return $hashPassword;
}
public static function atHome($userId, $atHome){
try {
Db::edit ('users', ['at_home' => $atHome], 'WHERE user_id = ?', array($userId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function changePassword($oldPassword, $newPassword, $newPassword2){
if ($newPassword == $newPassword2) {
//Password Criteria
$oldPasswordSaved = self::getUserData('password');
if (self::getHashPassword($oldPassword) == $oldPasswordSaved) {
self::setUserData('password', self::getHashPassword($newPassword));
} else {
throw new Exception ("old password did not match");
}
} else {
throw new Exception ("new password arent same");
}
}
public static function createUser ($userName, $password, $email) {
$email = strtolower ($email);
$userId = Db::loadOne ('SELECT * FROM users WHERE LOWER (username) = LOWER (?) OR LOWER (email) = LOWER (?);', array ($userName, $email))['user_id'];
if ($userId != null) {
return false;
};
try {
$user = [
'username' => $userName,
'password' => self::getHashPassword($password),
'email' => $email,
];
return Db::add ('users', $user);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function haveOtaEnabled($userName){
$ota = self::getUser($userName)['ota'];
if ($ota != ''){
return ($ota != '' ? $ota : false);
} else {
return false;
}
}
public static function setOta($otaCode, $otaSecret){
$ga = new PHPGangsta_GoogleAuthenticator();
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
self::setUserData('ota', $otaSecret);
return true;
}
return false;
}
}
?>

View File

@ -1,19 +0,0 @@
<?php
class VirtualDeviceManager
{
public function fetchEnabled($deviceId = null, $subDeviceId = null){
$sleepTime = DeviceManager::getDeviceById($deviceId)['sleep_time'];
$LastRecordTime = new DateTime(RecordManager::getLastRecord($subDeviceId, 1)['time']);
$interval = $LastRecordTime->diff(new DateTime());
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$lastSeen = ($hours * 60 + $minutes);
if ($lastSeen > $sleepTime || $sleepTime == 0) {
return true;
}
return false;
}
}

View File

@ -1,185 +0,0 @@
<?php
class GoogleHomeDeviceTypes {
/*const AirConditioningUnit = 'action.devices.types.AC_UNIT';
const AirFreshener = 'action.devices.types.AIRFRESHENER';
const AirPurifier = 'action.devices.types.AIRPURIFIER';
const Awning = 'action.devices.types.AWNING';
const Bathtub = 'action.devices.types.BATHTUB';
const Bed = 'action.devices.types.BED';
const Blender = 'action.devices.types.BLENDER';
const Blinds = 'action.devices.types.BLINDS';
const Boiler = 'action.devices.types.BOILER';
const Camera = 'action.devices.types.CAMERA';
const CarbonMonoxideDetector = 'action.devices.types.CARBON_MONOXIDE_DETECTOR';
const Charger = 'action.devices.types.CHARGER';
const Closet = 'action.devices.types.CLOSET';
const CoffeeMaker = 'action.devices.types.COFFEE_MAKER';
const Cooktop = 'action.devices.types.COOKTOP';
const Curtain = 'action.devices.types.CURTAIN';
const Dehumidifier = 'action.devices.types.DEHUMIDIFIER';
const Dehydrator = 'action.devices.types.DEHYDRATOR';
const Dishwasher = 'action.devices.types.DISHWASHER';
const Door = 'action.devices.types.DOOR';
const Drawer = 'action.devices.types.DRAWER';
const Dryer = 'action.devices.types.DRYER';
const Fan = 'action.devices.types.FAN';
const Faucet = 'action.devices.types.FAUCET';
const Fireplace = 'action.devices.types.FIREPLACE';
const Fryer = 'action.devices.types.FRYER';
const GarageDoor = 'action.devices.types.GARAGE';
const Gate = 'action.devices.types.GATE';
const Grill = 'action.devices.types.GRILL';
const Heater = 'action.devices.types.HEATER';
const Hood = 'action.devices.types.HOOD';
const Humidifier = 'action.devices.types.HUMIDIFIER';
const Kettle = 'action.devices.types.KETTLE';
const Light = 'action.devices.types.LIGHT';
const Lock = 'action.devices.types.LOCK';
const MediaRemote = 'action.devices.types.REMOTECONTROL';
const Mop = 'action.devices.types.MOP';
const Mower = 'action.devices.types.MOWER';
const Microwave = 'action.devices.types.MICROWAVE';
const Multicooker = 'action.devices.types.MULTICOOKER';
const Network = 'action.devices.types.NETWORK';
const Oven = 'action.devices.types.OVEN';
const Pergola = 'action.devices.types.PERGOLA';
const PetFeeder = 'action.devices.types.PETFEEDER';
const PressureCooker = 'action.devices.types.PRESSURECOOKER';
const Radiator = 'action.devices.types.RADIATOR';
const Refrigerator = 'action.devices.types.REFRIGERATOR';
const Router = 'action.devices.types.ROUTER';
const Scene = 'action.devices.types.SCENE';
const Sensor = 'action.devices.types.SENSOR';
const SecuritySystem = 'action.devices.types.SECURITYSYSTEM';
const SettopBox = 'action.devices.types.SETTOP';
const Shutter = 'action.devices.types.SHUTTER';
const Shower = 'action.devices.types.SHOWER';
const SmokeDetector = 'action.devices.types.SMOKE_DETECTOR';
const SousVide = 'action.devices.types.SOUSVIDE';
const Sprinkler = 'action.devices.types.SPRINKLER';
const StandMixer = 'action.devices.types.STANDMIXER';
const Switch = 'action.devices.types.SWITCH';
const Television = 'action.devices.types.TV';
const Thermostat = 'action.devices.types.THERMOSTAT';
const Vacuum = 'action.devices.types.VACUUM';
const Valve = 'action.devices.types.VALVE';
const Washer = 'action.devices.types.WASHER';
const WaterHeater = 'action.devices.types.WATERHEATER';
const WaterPurifier = 'action.devices.types.WATERPURIFIER';
const WaterSoftener = 'action.devices.types.WATERSOFTENER';
const Window = 'action.devices.types.WINDOW';
const YogurtMaker = 'action.devices.types.YOGURTMAKER';*/
private static $actionWordBook = [
'control-light' => 'action.devices.types.LIGHT',
'control-socket' => 'action.devices.types.OUTLET',
'control-temp' => 'action.devices.types.THERMOSTAT',
'control-media' => 'action.devices.types.REMOTECONTROL',
];
private static $traidWordBook = [
'on/off' => 'action.devices.traits.OnOff',
'temp_cont' => 'action.devices.traits.TemperatureSetting',
'vol_cont' => 'action.devices.traits.Volume',
'media_cont' => 'action.devices.traits.TransportControl',
'media_status' => 'action.devices.traits.MediaState',
'media_apps' => 'action.devices.traits.AppSelector',
'media_input' => 'action.devices.traits.InputSelector',
];
private static $commandWordBook = [
'action.devices.commands.OnOff' => 'on/off',
'action.devices.commands.ThermostatTemperatureSetpoint' => 'temp_cont',
'action.devices.commands.ThermostatSetMode' => 'temp_cont',
'action.devices.commands.setVolume' => 'vol_cont',
'action.devices.commands.mediaNext' => 'media_status',
'action.devices.commands.mediaPause' => 'media_status',
'action.devices.commands.mediaPrevious' => 'media_status',
'action.devices.commands.mediaResume' => 'media_status',
'action.devices.commands.mediaStop' => 'media_status',
'action.devices.commands.appSelect' => 'media_apps',
'action.devices.commands.SetInput' => 'media_input',
];
private static $attributeWordBook = [
'on/off' => [
'commandOnlyOnOff' => false,
],
'temp_cont' => [
'availableThermostatModes' => 'off,heat',
'thermostatTemperatureUnit' => 'C',
],
'vol_cont' => [
'volumeCanMuteAndUnmute' => false,
'volumeDefaultPercentage' => 6,
'volumeMaxLevel' => 100,
'levelStepSize' => 2,
'commandOnlyVolume' => false,
],
'media_cont'=> [
'transportControlSupportedCommands' => [
"NEXT",
"PREVIOUS",
"PAUSE",
"STOP",
"RESUME",
"CAPTION_CONTROL"
],
],
'media_status'=> [
'supportActivityState' => true,
'supportPlaybackState' => true,
],
'media_apps' => [
"availableApplications" => [
[
"key" => "kodi",
"names" => [
"name_synonym" => [
"Kodi",
],
"lang" => "en",
],
],
],
],
'media_input' => [
"availableInputs" => [
[
"key" => "pc",
"names" => [
"name_synonym" => [
"PC",
],
"lang" => "en",
],
],
]
],
];
static function getAction($deviceType){
if (!isset(self::$actionWordBook[$deviceType])) return;
return self::$actionWordBook[$deviceType];
}
static function getTraid($subDeviceType){
if (!isset(self::$traidWordBook[$subDeviceType])) return;
return self::$traidWordBook[$subDeviceType];
}
static function getType($subDeviceCommand){
if (!isset(self::$commandWordBook[$subDeviceCommand])) return;
return self::$commandWordBook[$subDeviceCommand];
}
static function getAttribute($subDeviceType){
if (!isset(self::$attributeWordBook[$subDeviceType])) return;
return self::$attributeWordBook[$subDeviceType];
}
static function getQueryJson($deviceType, $type){
return self::$wordBook[$type];
}
}

View File

@ -1,19 +0,0 @@
<?php
class LogRecordTypes{
const ERROR = [
'level' => 0,
'identifier' => 'error',
];
const WARNING = [
'level' => 1,
'identifier' =>'warning',
];
const EXEPTION = [
'level' => 2,
'identifier' => 'exeption',
];
const INFO = [
'level' => 3,
'identifier' => 'info',
];
}

View File

@ -1,45 +0,0 @@
<?php
class WidgetTypes {
const VALUE = 0;
const ICON = 1;
const BUTTON = 2;
const SWITH = 3;
const RANGE = 4;
const CUSTOM = 5;
private $types = [
self::VALUE => [
'name' => 'value',
'active' => false
],
self::ICON => [
'name' => 'icon',
'active' => false
],
self::BUTTON => [
'name' => 'button',
'active' => true
],
self::SWITH => [
'name' => 'switch',
'active' => true
],
self::RANGE => [
'name' => 'range',
'active' => true
],
self::CUSTOM => [
'name' => 'custom',
'active' => true
],
];
public static function getName($type){
return self::$types[$type];
}
public static function isActive($type){
return isset(self::$types[$type]) && self::$types[$type]['active'];
}
}

View File

@ -1,52 +0,0 @@
<?php
class AirQuality extends VirtualDeviceManager
{
private $city_sluig = "prague";
private $app_id = "53ccbc353bb0bd0b05515169a593b96c38d57c48";
private $api_uri = 'http://api.waqi.info/feed/%s/?token=%s'; // Your redirect uri
private $virtual_device_name = "Air Quality";
private $subdevice_type = "air-quality";
function make()
{
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) {
SubDeviceManager::create($deviceId, $this->subdevice_type, '');
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
}
//if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die();
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']);
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch(Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
function translate($value){
if ($value < 50) {
return 'Good';
} else if ($value > 51 && $value < 100) {
return 'Moderate';
} else if ($value > 101 && $value < 150) {
return 'Normal';
} else if ($value > 151 && $value < 200) {
return 'Unhealthy';
} else if ($value > 201 && $value < 300) {
return 'Very Unhealthy';
} else if ($value > 301 ) {
return 'Hazardous';
}
return '';
}
}

View File

@ -1,60 +0,0 @@
<?php
class AirQuality extends VirtualDeviceManager
{
private $city_sluig = "prague";
private $app_id = "53ccbc353bb0bd0b05515169a593b96c38d57c48";
private $api_uri = 'http://api.waqi.info/feed/%s/?token=%s'; // Your redirect uri
private $virtual_device_name = "Air Quality";
private $subdevice_type = "air-quality";
function make()
{
//Register the settings
$settingMng = new SettingsManager();
if (!($settingField = $settingMng->getByName("airquality"))) {
$settingMng->create("token", "", "airquality");
} else {
$app_id = $settingField['value'];
}
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) {
SubDeviceManager::create($deviceId, $this->subdevice_type, '');
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
}
//if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die();
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']);
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch(Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
function translate($value){
if ($value < 50) {
return 'Good';
} else if ($value > 51 && $value < 100) {
return 'Moderate';
} else if ($value > 101 && $value < 150) {
return 'Normal';
} else if ($value > 151 && $value < 200) {
return 'Unhealthy';
} else if ($value > 201 && $value < 300) {
return 'Very Unhealthy';
} else if ($value > 301 ) {
return 'Hazardous';
}
return '';
}
}

View File

@ -1,53 +0,0 @@
<?php
class CovidV2 extends VirtualDeviceManager
{
private $api_uri = 'https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/nakazeni-vyleceni-umrti-testy.json'; // Your redirect uri
private $virtual_device_name = "Covid-V2";
private $name_index = [
"Active" => "kumulativni_pocet_nakazenych",
"Recovered" => "kumulativni_pocet_vylecenych",
"Tested" => "kumulativni_pocet_testu",
"Deaths" => "kumulativni_pocet_umrti",
];
public function make()
{
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
$dataItems = ['Tested', 'Deaths', 'Recovered', 'Active'];
foreach ($dataItems as $dataItem) {
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) {
SubDeviceManager::create($deviceId, strtolower($dataItem), $dataItem);
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem));
}
}
if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die();
$finalUrl = $this->api_uri;
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true)['data'];
foreach ($dataItems as $dataItem) {
RecordManager::create($deviceId, strtolower($dataItem), end($json)[$this->name_index[$dataItem]]);
}
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, strtolower($this->virtual_device_name));
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch (Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
public function translate($value){
$outcome = $value / 1000;
if ($outcome < 1){
return $value;
}
return round($outcome) . 'K';
}
}

View File

@ -1,78 +0,0 @@
<?php
class DatabaseBackup
{
public function make()
{
try {
$filenames = [];
$backupWorker = new DatabaseBackup;
$filenames[] = $backupWorker->scheme(); //Backup Database scheme
$filenames[] = $backupWorker->data(); //Backup Database Data
//$filenames[] = $_SERVER['DOCUMENT_ROOT'] . '/config/config.php'; //Backup Configuration File
$backupWorker->compress($_SERVER['DOCUMENT_ROOT'] . BASEDIR . '/backup/' . date("Y-m-d", time()) . '.zip', $filenames);
return 'sucessful';
} catch (Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
private function data()
{
$backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_data_' . date("Y-m-d", time()) . '.sql';
$command = "mysqldump --skip-comments --no-create-info -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1";
$this->executeCommand($command);
return $backupfile;
}
private function scheme()
{
$backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_scheme_' . date("Y-m-d", time()) . '.sql';
$command = "mysqldump --skip-comments --no-data -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1";
$this->executeCommand($command);
return $backupfile;
}
private function executeCommand($command)
{
ini_set('date.timezone', 'Europe/Prague');
exec($command);
}
private function compress($filename, $files = [])
{
$zip = new ZipArchive();
if ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
foreach ($files as $file) {
unlink($file);
}
}
}
private function cleaningDir($dir, $seconds)
{
$todayFileName = date("Y-m-d") . '.zip';
$logFiles = scandir($dir);
foreach ($logFiles as $key => $file) {
if (in_array($file, array(".", "..", ".gitkeep", $todayFileName))) {
continue;
}
if (!is_dir($dir . $file)) {
if (strtotime(str_replace(".zip", "", $file)) < (strtotime("now") - $seconds)) {
unlink($dir . $file);
}
} else {
$this->cleaningDir($dir . $file . "/", $seconds);
}
}
}
public function purge($days)
{
$seconds = $days * 86400;
$this->cleaningDir('../backup/', $seconds);
}
}

View File

@ -1,11 +0,0 @@
<?php
class ExamplePlugin extends VirtualDeviceManager
{
function make(){
//Getting Data
}
function translate($value){
//Translation of numeric values
}
}

View File

@ -1,42 +0,0 @@
<?php
class N7Day extends VirtualDeviceManager
{
private $virtual_device_name = "N7 Day";
private $device_type = "day-count";
private $subdevice_type = "day-count";
function make()
{
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) {
SubDeviceManager::create($deviceId, $this->subdevice_type, 'days');
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
}
//if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die();
//Days Until N7 day
$now = time(); // or your date as well
if (strtotime(date("Y") . "-11-07") < $now){
$your_date = strtotime((date("Y") + 1) . "-11-07");
} else {
$your_date = strtotime(date("Y") . "-11-07");
}
$datediff = $now - $your_date;
$daysUntilN7Day = round($datediff / (60 * 60 * 24));
RecordManager::create($deviceId, $this->subdevice_type, $daysUntilN7Day);
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, $this->device_type);
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch(Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
}

View File

@ -1,72 +0,0 @@
<?php
class OpenWeatherMap extends VirtualDeviceManager
{
private $city_sluig = "prague";
private $app_id = "1ee609f2fcf8048e84f1d2fb1d1d72b5";
private $api_uri = 'api.openweathermap.org/data/2.5/weather?q=%s&appid=%s'; // Your redirect uri
private $virtual_device_name = "Weather";
private $subdevice_type = "weather";
function make()
{
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) {
SubDeviceManager::create($deviceId, $this->subdevice_type, '');
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
}
if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die();
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
//Notification data setup
$notificationMng = new NotificationManager;
if ($json['weather'][0]['id'] >= 500 && $json['weather'][0]['id'] < 600) {
// $notificationData = [
// 'title' => 'Weather',
// 'body' => 'It Will be rainy outhere, Take Umbrela :)',
// 'icon' => 'http://dev.steelants.cz/projekty/simplehome-client/img/icons/favicon-16x16.png',
// ];
// //Notification for newly added Device
// if ($notificationData != []) {
// $subscribers = $notificationMng::getSubscription();
// foreach ($subscribers as $key => $subscriber) {
// $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
// }
// }
} else if ($json['weather'][0]['id'] >= 600 && $json['weather'][0]['id'] < 700) {
// $notificationData = [
// 'title' => 'Weather',
// 'body' => 'It is white out there :)',
// 'icon' => 'http://dev.steelants.cz/projekty/simplehome-client/img/icons/favicon-16x16.png',
// ];
// //Notification for newly added Device
// if ($notificationData != []) {
// $subscribers = $notificationMng::getSubscription();
// foreach ($subscribers as $key => $subscriber) {
// $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
// }
// }
}
RecordManager::create($deviceId, $this->subdevice_type, $json['weather'][0]['id']);
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch (Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
function enable(){
(new SettingsManager)->create('open_weather_api_token', '', 'open_weather');
}
}

View File

@ -1,66 +0,0 @@
<?php
class Spotify extends VirtualDeviceManager
{
private $token = "";
private $client_id = '76840e2199e34dcd903d19877bd726dd'; // Your client id
private $redirect_uri = 'https://dev.steelants.cz/vasek/home-update/plugins/spotify/callback'; // Your redirect uri
public function oAuth()
{
$client_secret = 'CLIENT_SECRET'; // Your secret
$scopes = 'user-read-private user-read-email';
header('Location: https://accounts.spotify.com/authorize?client_id=' . $this->client_id . '&response_type=token&redirect_uri=' . urlencode($this->redirect_uri) . '&scope=user-read-playback-state');
}
private function setToken($token)
{
$this->token = $token;
}
public function callback()
{
var_dump($_REQUEST);
(new SettingsManager)->create('spotify_token', $token);
}
public function autorize()
{
$client_secret = '0f94ed2c0bd64bf791ea13b7e6310ba3';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials&scope=user-read-playback-state');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode($this->client_id . ':' . $client_secret)));
$result = curl_exec($ch);
$this->setToken(json_decode($result, true)['access_token']);
echo $result;
}
private function getPlayerData()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.spotify.com/v1/me/player');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . (new SettingsManager)->getByName('spotify_token')['value']));
$result = curl_exec($ch);
echo $result;
}
// function make()
// {
// try {
// //$this->autorize();d
// //$this->getPlayerData();
// return 'sucessful';
// } catch (Exception $e) {
// return 'exception: ' . $e->getMessage();
// }
// }
}

View File

@ -1,66 +0,0 @@
<?php
class UsaElection extends VirtualDeviceManager
{
private $api_uri = 'https://ft-ig-content-prod.s3.eu-west-1.amazonaws.com/v2/Financial-Times/ig-rcp-polls-backend/2020-presidential/latest/presidential-races.json'; // Your redirect uri
private $virtual_device_name = "Election";
private $subdevice_type = "election";
function make()
{
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
$dataItems = ['Trump', 'Biden', 'Unknown'];
foreach ($dataItems as $dataItem) {
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) {
SubDeviceManager::create($deviceId, strtolower($dataItem), '% ' . $dataItem);
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
}
}
if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die();
$finalUrl = $this->api_uri;
$json = json_decode(Utilities::CallAPI('GET', $finalUrl), true);
$voteSpectrum = [
'republican' => [
'solid' => 0,
'leaning' => 0,
],
'democrat' => [
'solid' => 0,
'leaning' => 0,
],
'tossup' => 0
];
foreach ($json as $state) {
if ($state['raceCategory'] != 'tossup') {
$raceCategory = explode('-', $state['raceCategory']);
$voteSpectrum[$raceCategory[0]][$raceCategory[1]] = $voteSpectrum[$raceCategory[0]][$raceCategory[1]] + $state['raceDelegates'];
} else {
$voteSpectrum['tossup'] = $voteSpectrum['tossup'] + $state['raceDelegates'];
}
}
$Trump = $voteSpectrum['republican']['solid'] + $voteSpectrum['republican']['leaning'];
$Biden = $voteSpectrum['democrat']['solid'] + $voteSpectrum['democrat']['leaning'];
$Unknown = $voteSpectrum['tossup'];
$OnePercent = ($Trump + $Biden + $Unknown) / 100;
foreach ($dataItems as $Category) {
RecordManager::create($deviceId, strtolower($Category), round(($$Category / $OnePercent)));
}
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch (Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
}

View File

@ -1,39 +0,0 @@
<?php
class Covid extends VirtualDeviceManager
{
private $country_sluig = "czech-republic";
private $api_uri = 'https://api.covid19api.com/live/country/%s/status/confirmed'; // Your redirect uri
private $virtual_device_name = "Covid";
function make()
{
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
$dataItems = ['Confirmed', 'Deaths', 'Recovered', 'Active'];
foreach ($dataItems as $dataItem) {
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) {
SubDeviceManager::create($deviceId, strtolower($dataItem), $dataItem);
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem));
}
}
if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die();
$finalUrl = sprintf($this->api_uri, $this->country_sluig);
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
foreach ($dataItems as $dataItem) {
RecordManager::create($deviceId, strtolower($dataItem), end($json)[$dataItem]);
}
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch (Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
}

View File

@ -1,223 +0,0 @@
<?php
class Ajax extends Template
{
function __construct()
{
$userManager = new UserManager();
global $lang;
if (!$userManager->isLogin()){
header('Location: ' . BASEURL);
}
$is_ajax = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
if (!$is_ajax){
header('Location: ' . BASEURL);
}
if (
isset($_POST['automation_id']) &&
$_POST['automation_id'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$automationId = $_POST['automation_id'];
//Automation Editation of Automations from Buttons/Details
switch ($_POST['action']) {
case 'delete':
AutomationManager::remove($automationId);
die();
break;
case 'deactive':
AutomationManager::deactive($automationId);
die();
break;
case 'restart':
AutomationManager::restart($automationId);
die();
break;
default:
echo 'no action detected';
break;
}
} else if (
isset($_POST['subDevice_id']) &&
$_POST['subDevice_id'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$subDeviceId = $_POST['subDevice_id'];
switch ($_POST['action']) {
case 'chart':
$period = $_POST['period'];
$groupBy = $_POST['group'];
header('Content-Type: application/json');
$graphData = ChartManager::generateChartData($subDeviceId, $period, $groupBy);
echo Utilities::generateGraphJson($graphData['graphType'], $graphData['graphData'], $graphData['graphRange']);
die();
break;
//Change On/Off Device State of Device Button
case 'change':
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
if ($subDeviceData['type'] == 'on/off'){
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($deviceId, 'on/off', !$lastValue);
echo (!$lastValue ? 'ON' : 'OFF');
}
die();
break;
//Waitin for execution of Changet walue for Device Button
case 'executed':
echo RecordManager::getLastRecord($subDeviceId)['execuded'];
die();
break;
case 'set':
$value = $_POST['value'];
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
RecordManager::create($subDevice['device_id'], $subDevice['type'], $value);
echo 'test id' . $subDevice['device_id'] .$subDevice['type'] . $value ;
die();
break;
default:
echo 'no action detected';
break;
}
} else if (
isset($_POST['scene_id']) &&
$_POST['scene_id'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$sceneId = $_POST['scene_id'];
switch ($_POST['action']) {
case 'delete':
SceneManager::delete($sceneId);
die();
break;
case 'execute':
echo SceneManager::execScene($sceneId);
die();
break;
default:
echo 'no action detected';
break;
}
} else if (
isset($_POST['notification']) &&
$_POST['notification'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
switch ($_POST['action']) {
//add suscription to database
case 'subscribe':
$subscriptionToken = $_POST['token'];
NotificationManager::addSubscriber($_SESSION['user']['id'], $subscriptionToken);
die();
break;
case 'sendTest':
$notificationData = [
'title' => 'Alert',
'body' => 'test notification',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
$notificationMng = new NotificationManager;
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
echo $subscriber['user_id'];
if ($subscriber['user_id'] != $_SESSION['user']['id']) continue;
echo $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
die();
break;
default:
echo 'no action detected';
break;
}
} else if (
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$updateData = [];
$allDevicesData = DeviceManager::getAllDevices();
foreach ($allDevicesData as $deviceKey => $deviceValue) {
$allSubDevices = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
foreach ($allSubDevices as $key => $subDevicesData) {
$lastRecord = RecordManager::getLastRecord($subDevicesData['subdevice_id']);
$parsedValue = $lastRecord['value'] . $subDevicesData['unit'];
//TODO: udělat parser a ten použít jak v houmu tak zde
switch ($subDevicesData['type']) {
case 'on/off':
$replacementTrue = 'On';
$replacementFalse = 'Off';
$operator = '==';
$breakValue = 1;
break;
case 'door':
$replacementTrue = 'Closed';
$replacementFalse = 'Open';
$operator = '==';
$breakValue = 1;
break;
case 'light':
$replacementTrue = 'Light';
$replacementFalse = 'Dark';
$operator = '==';
$breakValue = 1;
if ($lastRecord['value'] != 1 && $lastRecord['value'] != 0) { //Digital Light Senzor
$operator = '<';
$breakValue = 810;
}
break;
case 'water':
$replacementTrue = 'Wet';
$replacementFalse = 'Dry';
$operator = '==';
$breakValue = 1;
break;
default:
$replacementTrue = '';
$replacementFalse = '';
break;
}
if ($replacementTrue != '' && $replacementFalse != '') {
//parsing last values
$parsedValue = $replacementFalse;
if (Utilities::checkOperator($lastRecord['value'], $operator, $breakValue)) {
$parsedValue = $replacementTrue;
}
}
$updateData[$subDevicesData['subdevice_id']] = [
'time' => $lastRecord['time'],
'value' => $parsedValue,
];
}
}
//TODO: PRO JS VRACET DATA
echo json_encode($updateData, JSON_PRETTY_PRINT);
}
}
}

View File

@ -1,67 +0,0 @@
<?php
class Automation extends Template
{
function __construct()
{
$userManager = new UserManager();
$langMng = new LanguageManager('en');
if (!$userManager->isLogin()){
header('Location: ' . BASEURL . 'login');
}
$automations = [];
$automationsData = AutomationManager::getAll();
foreach ($automationsData as $automationKey => $automationData) {
$doSomething = [];
foreach (json_decode($automationData['do_something']) as $deviceId => $subDeviceState) {
$subDeviceMasterDeviceData = DeviceManager::getDeviceById($deviceId);
$doSomething[$deviceId] = [
'name' => $subDeviceMasterDeviceData['name'],
'state' => $subDeviceState,
];
}
//TODO: Transaltion add
$executionTime = 'never';
if ($automationData['execution_time'] != '0000-00-00 00:00:00') {
$executionTime = date(DATEFORMAT,strtotime($automationData['execution_time']));
}
$automations[$automationData['automation_id']] = [
'name' => $automationData['name'],
'owner_name' => $userManager->getUserId($automationData['owner_id'])['username'],
'onDays' => json_decode($automationData['on_days']),
'ifSomething' => $automationData['if_something'],
'doSomething' => $doSomething,
'active' => $automationData['active'],
'execution_time' => $executionTime,
];
}
$approvedSubDevices = [];
$allDevicesData = DeviceManager::getAllDevices();
foreach ($allDevicesData as $deviceKey => $deviceValue) {
if (!$deviceValue['approved']) continue;
$allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) {
$approvedSubDevices[$subDeviceValue['subdevice_id']] = [
'name' => $allDevicesData[$deviceKey]['name'],
'type' => $subDeviceValue['type'],
'masterDevice' => $subDeviceValue['device_id'],
];
}
}
$template = new Template('automation');
$template->prepare('baseDir', BASEDIR);
$template->prepare('baseUrl', BASEURL);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Automation');
$template->prepare('langMng', $langMng);
$template->prepare('userManager', $userManager);
$template->prepare('automations', $automations);
$template->prepare('subDevices', $approvedSubDevices);
$template->render();
}
}

View File

@ -1,120 +0,0 @@
<?php
class Device extends Template
{
function __construct($sortBy = null, $sortType = null)
{
// //Notification data setup
// $notificationMng = new NotificationManager;
// $notificationData = [
// 'title' => 'Info',
// 'body' => 'New device Detected Found',
// 'icon' => 'http://dev.steelants.cz/projekty/simplehome-client/img/icons/favicon-16x16.png',
// ];
// //Notification for newly added Device
// if ($notificationData != []) {
// $subscribers = $notificationMng::getSubscription();
// foreach ($subscribers as $key => $subscriber) {
// $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
// }
// }
$userManager = new UserManager();
$deviceManager = new DeviceManager();
$subDeviceManager = new SubDeviceManager();
$recordManager = new RecordManager();
$roomManager = new RoomManager();
$langMng = new LanguageManager('en');
if (!$userManager->isLogin()) {
header('Location: ' . BASEURL . 'login');
}
$template = new Template('device');
$template->prepare('title', $langMng->get("m_devices"));
$sortWordBook = [
"id" => "device_id",
"name" => "name",
"room" => "room_id",
"ip" => "ip_address",
"mac" => "mac",
"token" => "token",
"signal" => "signal",
"firmware" => "firmware_hash",
"icon" => "icon",
"history" => "history",
];
$sortIcons = [
"ASC" => "&#xf0de",
"DESC" => "&#xf0dd",
];
$nextSort = [
"ASC" => "DESC",
"DESC" => "ASC",
];
$devices = $deviceManager->getAllDevices();
if (empty($sortBy) && empty($sortType)) {
$sortBy = "id";
$sortType = "DESC";
}
$template->prepare('sortIcon', [$sortBy => $sortIcons[$sortType]]);
foreach ($devices as $key => $device) {
//Signal Stenght
$subdevice = $subDeviceManager->getSubDeviceByMasterAndType($device['device_id'], "wifi");
$subdeviceLocal = $subDeviceManager->getSubDeviceByMaster($device['device_id']);
if (!empty($subdeviceLocal)) {
$devices[$key]['history'] = (!empty($subdeviceLocal['history']) ? $subdeviceLocal['history'] : 0);
} else {
$devices[$key]['history'] = "null";
}
$devices[$key]['signal'] = "";
if (!empty($subdevice['subdevice_id'])) {
$record = $recordManager->getLastRecord($subdevice['subdevice_id']);
if (!empty($record)) {
$devices[$key]['signal'] = $record['value'] . " " . $subdevice['unit'];
}
}
//Firmware Status
if (empty($devices[$key]['mac'])) {
$devices[$key]['firmware_hash'] = "";
continue;
}
$localBinary = "../updater/" . str_replace(':', '', $device['mac']) . ".bin";
$devices[$key]['firmware_hash'] = "";
if (file_exists($localBinary)) {
$hash = md5_file($localBinary);
if ($hash == $device['firmware_hash']) {
$devices[$key]['firmware_hash'] = "true";
} else {
$devices[$key]['firmware_hash'] = "need";
}
} else {
$devices[$key]['firmware_hash'] = "false";
}
}
$devices = Utilities::sortArrayByKey($devices, $sortWordBook[$sortBy], strtolower($sortType));
$rooms = $roomManager->getAllRooms();
$template->prepare('baseUrl', BASEURL);
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('logToLiveTime', LOGTIMOUT);
$template->prepare('rooms', $rooms);
$template->prepare('sortType', $nextSort[$sortType]);
$template->prepare('devices', $devices);
$template->prepare('langMng', $langMng);
$template->render();
}
}

View File

@ -1,48 +0,0 @@
<?php
class Log extends Template
{
function __construct()
{
$userManager = new UserManager();
$langMng = new LanguageManager('en');
if (!$userManager->isLogin()){
header('Location: ' . BASEURL . 'login');
}
$template = new Template('log');
$template->prepare('title', 'Log');
$result = array();
$result = $this->logFinder ('../logs/', $result);
$template->prepare('baseDir', BASEDIR);
$template->prepare('baseUrl', BASEURL);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('logToLiveTime', LOGTIMOUT);
$template->prepare('title', 'Logy');
$template->prepare('logStats', LogMaintainer::getStats());
$template->prepare('logsFiles', $result);
$template->prepare('langMng', $langMng);
$template->render();
}
private function logFinder ($dir, $result) {
$logFiles = scandir ($dir);
foreach ($logFiles as $key => $file) {
if (in_array ($file,array (".", "..", ".gitkeep")))
{
continue;
}
if (!is_dir($dir . $file)) {
$result[$dir][] = $file;
} else {
$result = $this->logFinder ($dir . $file . "/", $result);
}
}
return $result;
}
}

View File

@ -1,22 +0,0 @@
<?php
class Login extends Template
{
function __construct()
{
$userManager = new UserManager();
if ($userManager->isLogin()){
header('Location: ' . BASEURL);
}
$template = new Template('login');
$template->prepare('baseDir', BASEDIR);
$template->prepare('baseUrl', BASEURL);
$template->prepare('title', 'Home');
$template->render();
}
}

View File

@ -1,11 +0,0 @@
<?php
class Logout extends Template
{
function __construct()
{
$userManager = new UserManager ();
$userManager->logout();
header('Location: ' . BASEURL . 'login');
die();
}
}

View File

@ -1,28 +0,0 @@
<?php
class Oauth extends Template
{
function __construct()
{
$userManager = new UserManager ();
$langMng = new LanguageManager('en');
$template = new Template('oauth');
$template->prepare('baseDir', BASEDIR);
$template->prepare('baseUrl', BASEURL);
$template->prepare('title', 'Simple Home - Oauth');
if (isset($_GET['redirect_uri'])) {
$template->prepare('responseType', $_GET['response_type']);
$template->prepare('redirectUrl', $_GET['redirect_uri']);
$template->prepare('clientId', $_GET['client_id']);
$template->prepare('state', $_GET['state']);
} else {
$template->prepare('responseType', $_POST['responseType']);
$template->prepare('redirectUrl', $_POST['redirectUrl']);
$template->prepare('clientId', $_POST['clientId']);
$template->prepare('state', $_POST['state']);
}
$template->render();
}
}

View File

@ -1,38 +0,0 @@
<?php
class Plugins extends Template
{
function __construct()
{
$userManager = new UserManager();
$langMng = new LanguageManager('en');
if (!$userManager->isLogin()){
header('Location: ' . BASEURL . 'login');
}
$dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/';
$pluginsFiles = array_diff(scandir($dir), ['..', '.']);
$plugins = array();
foreach ($pluginsFiles as $key => $pluginFile) {
$status = (strpos($pluginFile, "!") !== false ? false : true);
$plugins[$key]['name'] = str_replace("!", "", str_replace(".php", "", $pluginFile));
$plugins[$key]['status'] = $status;
}
$plugins = Utilities::sortArrayByKey($plugins, 'status', "desc");
$template = new Template('plugins');
$template->prepare('baseDir', BASEDIR);
$template->prepare('baseUrl', BASEURL);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Plugins');
$template->prepare('langMng', $langMng);
$template->prepare('plugins', $plugins);
$template->render();
}
}

View File

@ -1,56 +0,0 @@
<?php
class Server extends Template
{
//TODO: to server manager
private function getSystemMemInfo()
{
$data = explode("\n", file_get_contents("/proc/meminfo"));
$meminfo = array();
foreach ($data as $line) {
$data = explode(":", $line);
if (count($data)!=2) continue;
$meminfo[$data[0]] = trim($data[1]);
}
return $meminfo;
}
private function getProcessorUsage(){
$loads=sys_getloadavg();
$core_nums=trim(shell_exec("grep -P '^physical id' /proc/cpuinfo|wc -l"));
$load = round($loads[0]/($core_nums + 1)*100, 2);
return $load;
}
function __construct()
{
$userManager = new UserManager();
$langMng = new LanguageManager('en');
if (!$userManager->isLogin()){
header('Location: ' . BASEURL . 'login');
}
$template = new Template('server');
$template->prepare('title', 'Server');
$template->prepare('baseDir', BASEDIR);
$template->prepare('baseUrl', BASEURL);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('langMng', $langMng);
$template->prepare('UPTIME', shell_exec('uptime -p'));
$template->prepare('serverTime', date('m. d. Y H:i:s - e'));
$template->prepare('ip', $_SERVER['SERVER_ADDR']);
$template->prepare('name', $_SERVER['SERVER_NAME']);
$template->prepare('CPU', $this->getProcessorUsage());
$template->prepare('ramFree', $this->getSystemMemInfo()["MemFree"]);
$template->prepare('ramTotal', $this->getSystemMemInfo()["MemTotal"]);
$template->prepare('diskFree', disk_free_space("/"));
$template->prepare('diskTotal', disk_total_space("/"));
$template->render();
}
}

View File

@ -1,85 +0,0 @@
<?php
class Setting extends Template
{
function __construct()
{
$userManager = new UserManager();
$langMng = new LanguageManager('en');
if (!$userManager->isLogin()){
header('Location: ' . BASEURL . 'login');
}
$automations = [];
$automationsData = AutomationManager::getAll();
foreach ($automationsData as $automationKey => $automationData) {
$automations[$automationData['automation_id']] = [
'name' => '',
'onDays' => $automationData['on_days'],
'ifSomething' => $automationData['if_something'],
'doSomething' => $automationData['do_something'],
];
}
$template = new Template('setting');
$template->prepare('baseDir', BASEDIR);
$template->prepare('baseUrl', BASEURL);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Automation');
$template->prepare('langMng', $langMng);
$template->prepare('automations', $automations);
$users = $userManager->getUsers();
foreach ($users as $key => $value) {
$users[$key]['gavatar_url'] = $userManager->getAvatarUrl($value['user_id']);
}
$template->prepare('users', $users);
$template->prepare('userName', $userManager->getUserData('username'));
$template->prepare('userEmail', $userManager->getUserData('email'));
$template->prepare('userAvatarUrl', $userManager->getAvatarUrl());
if ($userManager->getUserData('ota') == ''){
$ga = new PHPGangsta_GoogleAuthenticator();
$otaSecret = $ga->createSecret();
$qrCodeUrl = $ga->getQRCodeGoogleUrl('Smart Home', $otaSecret);
$oneCode = $ga->getCode($otaSecret);
$template->prepare('qrUrl', $qrCodeUrl);
$template->prepare('otaSecret', $otaSecret);
$template->prepare('otaCode', $oneCode);
// echo "Secret is: ".$secret."\n\n";
// echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."\n\n";
// echo "Checking Code '$oneCode' and Secret '$otaSecret':\n";
}
$rooms = RoomManager::getAllRooms();
$template->prepare('rooms', $rooms);
$settingsManager = new SettingsManager();
$dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/';
$pluginsFiles = array_diff (scandir ($dir), ['..', '.']);
$plugins = array ();
foreach ($pluginsFiles as $key => $pluginFile) {
$status = (strpos ($pluginFile, "!") !== false ? false : true);
if ($status) {
$plugins[$key]['name'] = str_replace ("!", "", str_replace (".php", "", $pluginFile));
$plugins[$key]['slug'] = strtolower ($plugins[$key]['name']);
$result = $settingsManager->getSettingGroup($plugins[$key]['slug']);
if (count ($result) > 0) {
$plugins[$key]['settings'] = $result;
} else {
unset($plugins[$key]);
}
}
}
$plugins = Utilities::sortArrayByKey($plugins, 'slug', "desc");
$template->prepare('pluginsSettings', $plugins);
$template->render();
}
}

View File

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $this->title ?></title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<header>
{HEADER}
</header>
<?php echo $this->content(); ?>
<footer>
{FOOTER}
</footer>
</body>
</html>

View File

@ -1,68 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$partial = new Partial('head');
$partial->prepare('baseDir', $BASEDIR);
$partial->prepare('baseUrl', $BASEURL);
$partial->render();
?>
<title><?php echo $TITLE ?></title>
</head>
<body class="no-transitions">
<div class="row no-gutters main">
<div class="col-md-3 d-sm-none"></div>
<div class="col-md-3 nav-container">
<?php
$partial = new Partial('menu');
$partial->prepare('item','automation');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>
<div class="col-md-9 main-body">
<a class="button is-primary m-1" onClick="$('#modal').removeClass('modal-container-hiden').show();"><?php $LANGMNG->echo('t_createAutomation'); ?></a>
<div class="row no-gutters">
<?php foreach ($AUTOMATIONS as $automationId => $automationData) {
//BUTTON
$partial = new Partial('automationButton');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('automationId',$automationId);
$partial->prepare('automationData',$automationData);
$partial->render();
//EDIT
$partial = new Partial('automationEdit');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('userManager',$USERMANAGER);
$partial->prepare('automationId',$automationId);
$partial->prepare('automation',$automationData);
$partial->prepare('subDevices',$SUBDEVICES);
$partial->render();
} ?>
</div>
</div>
</div>
<?php
if (isset($_POST['modalNext'])) {
$partial = new Partial('automationCreateFinal');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('userManager',$USERMANAGER);
$partial->prepare('subDevices',$SUBDEVICES);
$partial->render();
} else {
$partial = new Partial('automationCreate');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('subDevices',$SUBDEVICES);
$partial->render();
}?>
<script src="./app/templates/js/automation.js"></script>
<?php
$partial = new Partial('footer');
$partial->prepare('baseDir', $BASEDIR);
$partial->render();
?>
</body>
</html>

View File

@ -1,136 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$partial = new Partial('head');
$partial->prepare('baseDir', $BASEDIR);
$partial->prepare('baseUrl', $BASEURL);
$partial->render();
?>
<title><?php echo $TITLE ?></title>
</head>
<body class="no-transitions">
<div class="row no-gutters main">
<div class="col-md-3 d-sm-none"></div>
<div class="col-md-3 nav-container">
<?php
$partial = new Partial('menu');
$partial->prepare('item', 'device');
$partial->prepare('langMng', $LANGMNG);
$partial->prepare('debugMod', $DEBUGMOD);
$partial->render();
?>
</div>
<div class="col-md-9 main-body">
<table class="table is-fluid">
<tr>
<th><a href="device/icon/<?php echo $SORTTYPE; ?>">#</a><i class="fa"><?php echo (!empty($SORTICON['icon']) ? $SORTICON['icon'] : ""); ?></i></th>
<th><a href="device/name/<?php echo $SORTTYPE; ?>">Name</a><i class="fa"><?php echo (!empty($SORTICON['name']) ? $SORTICON['name'] : ""); ?></i></th>
<th><a href="device/room/<?php echo $SORTTYPE; ?>">Room</a><i class="fa"><?php echo (!empty($SORTICON['room']) ? $SORTICON['room'] : ""); ?></i></th>
<th><a href="device/signal/<?php echo $SORTTYPE; ?>">Signal</a><i class="fa"><?php echo (!empty($SORTICON['signal']) ? $SORTICON['signal'] : ""); ?></i></th>
<th><a href="device/firmware/<?php echo $SORTTYPE; ?>">Firmware</a><i class="fa"><?php echo (!empty($SORTICON['firmware']) ? $SORTICON['firmware'] : ""); ?></i></th>
<th>
<a href="device/ip/<?php echo $SORTTYPE; ?>">IP Address</a><i class="fa"><?php echo (!empty($SORTICON['ip']) ? $SORTICON['ip'] : ""); ?></i><br>
<a href="device/mac/<?php echo $SORTTYPE; ?>">(Mac)</a><i class="fa"><?php echo (!empty($SORTICON['mac']) ? $SORTICON['mac'] : ""); ?></i><br>
<a href="device/token/<?php echo $SORTTYPE; ?>">Token</a><i class="fa"><?php echo (!empty($SORTICON['token']) ? $SORTICON['token'] : ""); ?></i>
</th>
<th><a href="device/history/<?php echo $SORTTYPE; ?>">Historie</a><i class="fa"><?php echo (!empty($SORTICON['history']) ? $SORTICON['history'] : ""); ?></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>
<?php if (!empty($DEVICES)) : ?>
<?php foreach ($DEVICES as $device) : ?>
<tr>
<td><i class="fa <?php echo (!empty($device['icon']) ? $device['icon'] : ""); ?>"></i></td>
<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>
<?php if (!empty($device['mac'])) : ?>
<?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>
<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">
<input type="hidden" name="deviceId" value="<?php echo (!empty($device['device_id']) ? $device['device_id'] : ""); ?>">
<input type="file" onchange="this.form.submit();" name="deviceFirmware" id="deviceFirmware-<?php echo $device['device_id'] ?>" value="">
</form>
<!--<button class="fa custom-file-input" type="button" onclick="document.getElementById('deviceFirmware-<?php //echo $device['device_id'] ?>').click();">&#xf1f8;</button>-->
<?php endif; ?>
<div type="float: clear;"></div>
</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>
<?php if (isset($device['history']) && $device['history'] != "null"): ?>
<form method="post" action="">
<input type="hidden" name="deviceId" value="<?php echo (!empty($device['device_id']) ? $device['device_id'] : ""); ?>">
<input class="input" type="number" onchange="this.form.submit();" name="deviceHistory" value="<?php echo (!empty($device['history']) ? $device['history'] : 0); ?>">
</form>
<?php endif; ?>
</td>
<td>
<?php if (!empty($device['mac'])) : ?>
<form method="post" action="">
<input type="hidden" name="deviceId" value="<?php echo (!empty($device['device_id']) ? $device['device_id'] : ""); ?>">
<button class="fa custom-file-input" <?php echo (!empty($device['command']) && $device['command'] == "reset" ? "style=\"color:red;\"" : ""); ?> type="submit" name="deviceCommand" value="reset" title="Reset">&#xf01e;</button>
<button class="fa custom-file-input" <?php echo (!empty($device['command']) && $device['command'] == "config" ? "style=\"color:red;\"" : ""); ?> type="submit" name="deviceCommand" value="config" title="Config">&#xf013;</button>
<div style="float: clear;"></div>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</table>
</div>
<?php
$partial = new Partial('footer');
$partial->prepare('baseDir', BASEDIR);
$partial->render();
//TODO js do main.js
?>
</body>
</html>

View File

@ -1 +0,0 @@
Example template

View File

@ -1,20 +0,0 @@
.loader {
border: 16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid #3498db;
width: 120px;
height: 120px;
-webkit-animation: spin 2s linear infinite; /* Safari */
animation: spin 2s linear infinite;
}
/* Safari */
@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

View File

@ -1,93 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$partial = new Partial('head');
$partial->prepare('baseDir', $BASEDIR);
$partial->prepare('baseUrl', $BASEURL);
$partial->render();
?>
<title><?php echo $TITLE ?></title>
</head>
<body class="no-transitions">
<div class="row no-gutters main">
<div class="col-md-3 d-sm-none"></div>
<div class="col-md-3 nav-container">
<?php
$partial = new Partial('menu');
$partial->prepare('item', 'log');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>
<div class="col-md-9 main-body">
<div class="col-12 col-sm-9 mx-auto mt-4">
<h1><?php echo $LANGMNG->get('t_Logs'); ?></h1>
<div class="row mb-4">
<div class="col-6 col-lg-3">
<div class="panel alert alert-danger p-4 is-danger">
<h5><?php $LANGMNG->echo('error'); ?></h5>
<?php echo $LOGSTATS['ERROR'];?>
</div>
</div>
<div class="col-6 col-lg-3">
<div class="panel alert alert-warning p-4">
<h5><?php $LANGMNG->echo('warning'); ?></h5>
<?php echo $LOGSTATS['WARNING'];?>
</div>
</div>
<div class="col-6 col-lg-3">
<div class="panel alert alert-warning p-4">
<h5 ><?php $LANGMNG->echo('exeption'); ?></h5>
<?php echo $LOGSTATS['EXEPTION'];?>
</div>
</div>
<div class="col-6 col-lg-3">
<div class="panel alert p-4">
<h5><?php $LANGMNG->echo('log'); ?></h5>
<?php echo $LOGSTATS['INFO'];?>
</div>
</div>
</div>
<label><?php echo $LANGMNG->get('l_logMaxLiveTime') . " " . $LOGTOLIVETIME . " days";?></label></br>
<form method="post" action="">
<div class="field">
<select class="input" name="LogFile">
<?php foreach ($LOGSFILES as $key => $value) { ?>
<optgroup label="<?php echo str_replace("../", "", $key); ?>">
<?php foreach ($value as $valueSub) { ?>
<option value="<?php echo $key . $valueSub; ?>"><?php echo $valueSub; ?></option>
<?php } ?>
</optgroup>
<?php } ?>
</select>
</div>
<div class="field">
<input type="submit" class="button" name="selectFile" value="<?php $LANGMNG->echo('b_select');?>"/>
</div>
</form>
<?php
if (isset($_POST['LogFile'])) {
$file_lines = file($_POST['LogFile']);
echo '<pre style="overflow: auto;">';
foreach ($file_lines as $line) {
echo $line;
}
echo '</pre>';
}
?>
</div>
</div>
<?php
$partial = new Partial('footer');
$partial->prepare('baseDir', BASEDIR);
$partial->render();
//TODO js do main.js
?>
</body>
</html>

View File

@ -1,31 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$partial = new Partial('head');
$partial->prepare('baseDir',$BASEDIR);
$partial->prepare('baseUrl',$BASEURL);
$partial->render();
?>
<title><?php echo $TITLE ?></title>
</head>
<body class="no-transitions">
<?php
if (isset($ota) && $ota != '') {
$partial = new Partial('loginOta');
$partial->prepare('ota',$ota);
$partial->render();
} else {
$partial = new Partial('loginForm');
$partial->render();
}
?>
<?php
$partial = new Partial('footer');
$partial->prepare('baseDir', BASEDIR);
$partial->render();
?>
</body>
</html>

View File

@ -1,34 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$partial = new Partial('head');
$partial->prepare('baseDir',$BASEDIR);
$partial->render();
?>
<title><?php echo $TITLE ?></title>
</head>
<body class="no-transitions">
<?php
if (isset($ota) && $ota != '') {
$partial = new Partial('oauthLoginOta');
$partial->prepare('ota',$ota);
$partial->render();
} else {
$partial = new Partial('oauthLoginForm');
$partial->prepare('responseType',$RESPONSETYPE);
$partial->prepare('redirectUrl',$REDIRECTURL);
$partial->prepare('clientId',$CLIENTID);
$partial->prepare('state',$STATE);
$partial->render();
}
?>
<?php
$partial = new Partial('footer');
$partial->prepare('baseDir', BASEDIR);
$partial->render();
?>
</body>
</html>

View File

@ -1,70 +0,0 @@
<div class="col-12 col-md-6 col-xl-4 square-wrap">
<div class="rectangle-2">
<div class="square-content double <?php echo ($AUTOMATIONDATA['active'] == 0 ? 'is-inactive' : ''); ?>" id="automation-<?php echo $AUTOMATIONID; ?>">
<div class="row">
<div class="col-1">
<h5 class="fa">
<?php
//echo $AUTOMATIONDATA['ifSomething'];
$ifCode = json_decode($AUTOMATIONDATA['ifSomething']);
switch ($ifCode->type) {
case 'sunSet':
echo'&#xf186';
break;
case 'sunRise':
echo'&#xf185 ';
break;
case 'inHome':
echo'&#xf090';
break;
case 'outHome':
echo'&#xf08b';
break;
case 'outDevice':
echo'&#xf2db';
break;
default:
echo'&#xf017';
break;
}
?>
</h5>
</div>
<div class="col">
<h5 class="text-right break-all">
<?php
/*if (!in_array($AUTOMATIONDATA['ifSomething'], ["sunRise", "sunSet"])) {
echo $AUTOMATIONDATA['ifSomething'];
}*/
echo $AUTOMATIONDATA['name'];
?>
</h5>
</div>
</div>
<div class="row">
<div class="col">
<?php echo implode(', ',$AUTOMATIONDATA['onDays']);?>
</div>
<div class="col">
<?php echo $AUTOMATIONDATA['owner_name'];?>
</div>
<div class="col">
<?php echo $AUTOMATIONDATA['execution_time'];?>
</div>
</div>
<div class="row">
<div class="col">
<a class="button is-primary m-1" onClick="restartAutomation(<?php echo $AUTOMATIONID; ?>);"><?php $LANGMNG->echo('b_restart')?></a>
</div>
<div class="col">
<a class="button is-primary m-1" onClick="toggleAutomation(<?php echo $AUTOMATIONID; ?>);"><?php $LANGMNG->echo('b_disable')?></a>
</div>
</div>
</div>
</div>
</div>

View File

@ -1,69 +0,0 @@
<div class="modal-container modal-container-hiden" id="modal">
<div class="modal">
<a href=""><i class="fa fa-times close"></i></a>
<h4 class="mb-4"><?php $LANGMNG->echo('t_createAutomation')?></h4>
<form method="post" action="" >
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_nameAt')?></div>
<div class="field">
<input class="input" type="text" name="name" required/>
</div>
<div class="label"><?php $LANGMNG->echo('l_runAt')?></div>
<div class="field">
<select class="input" name="atSelector" id="valueSelector" required>
<option value="sunSet"><?php $LANGMNG->echo('l_sunSet')?></option>
<option value="sunRise"><?php $LANGMNG->echo('l_sunRice')?></option>
<option value="inHome"><?php $LANGMNG->echo('l_inHome')?></option>
<option value="outHome"><?php $LANGMNG->echo('l_outHome')?></option>
<option value="time"><?php $LANGMNG->echo('l_time')?></option>
<option value="atDeviceValue"><?php $LANGMNG->echo('l_deviceValue');?></option>
<option value="noOneHome"><?php $LANGMNG->echo('w_noOne') . ' ' . $LANGMNG->get('w_neni') . ' ' . $LANGMNG->get('w_home');?></option>
<option value="someOneHome"><?php $LANGMNG->echo('w_someOne') . ' ' . $LANGMNG->get('w_is') . ' ' . $LANGMNG->get('w_home');?></option>
</select>
<input class="input" type="time" name="atTime" id="atTime" disabled/>
<select class="input" name="atDeviceValue" id="atDeviceValue" disabled>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){ ?>
<option value="<?php echo $subDeviceKey; ?>"><?php echo $subDeviceValue['name']; ?>[<?php echo $subDeviceValue['type']; ?>]</option>
<?php } ?>
</select>
=
<input class="input" type="num" name="atDeviceValueInt" id="atDeviceValueInt" required disabled/>
</div>
<div class="label"><?php $LANGMNG->echo('l_affectedDevices')?></div>
<div class="field">
<select class="input" name="devices[]" multiple>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){
if ($subDeviceValue['type'] != 'on/off') continue;?>
<option value="<?php echo $subDeviceValue['masterDevice']; ?>"><?php echo $subDeviceValue['name']; ?></option>
<?php } ?>
</select>
</div>
<div class="label"><?php $LANGMNG->echo('l_atDays')?></div>
<div class="field">
<input type="checkbox" name="day[]" value="mon"/> <?php $LANGMNG->echo('d_monday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="tue"/> <?php $LANGMNG->echo('d_tuesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="wed"/> <?php $LANGMNG->echo('d_wednesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="thu"/> <?php $LANGMNG->echo('d_thursday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="fri"/> <?php $LANGMNG->echo('d_friday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sat"/> <?php $LANGMNG->echo('d_saturday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sun"/> <?php $LANGMNG->echo('d_sunday'); ?>
</div>
</div>
<input type="submit" class="button" name="modalNext" value="<?php $LANGMNG->echo('b_next')?>"/>
</form>
</div>
</div>

View File

@ -1,44 +0,0 @@
<div class="modal-container" id="modal">
<div class="modal" action="" >
<a href=""><i class="fa fa-times close"></i></a>
<h4 class="mb-4"><?php $LANGMNG->echo('t_createAutomation'); ?></h4>
<form method="post">
<div class="field">
<input type="hidden" name="action" value="add" required/>
<input type="hidden" name="atSelector" value="<?php echo $_POST['atSelector']; ?>" required/>
<input type="hidden" name="name" value="<?php echo $_POST['name']; ?>" required/>
<input type="hidden" name="atSelectorValue" value="<?php if (isset($_POST['atTime'])) {
echo $_POST['atTime'];
} else if (isset($_POST['atDeviceValue'])) {
$subDeviceId = $_POST['atDeviceValue'];
$subDeviceValue = $_POST['atDeviceValueInt'];
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
$subDeviceMaster = SubDeviceManager::getSubDeviceMaster($subDeviceId,$subDevice['type']);
$json = json_encode([
'deviceID' => $subDeviceMaster['device_id'],
'type'=> htmlspecialchars($subDevice['type']),
'value'=> $subDeviceValue,
]);
echo htmlspecialchars($json);
} else {
if ($_POST['atSelector'] == "inHome" || $_POST['atSelector'] == "outHome") {
echo $USERMANAGER->getUserData('user_id');
} else {
echo $_POST['atSelector'];
}
} ?>" required/>
<input type="hidden" name="atDays" value="<?php echo htmlspecialchars(($_POST['day'] != '' ? json_encode($_POST['day']) : '')); ?>" required/>
<?php foreach ($_POST['devices'] as $value) { ?>
<?php $deviceData = DeviceManager::getDeviceById($value); ?>
<div class="label"><?php echo $deviceData['name'];?></div>
<select class="input" name="device[<?php echo $deviceData['device_id'];?>]">
<option value="1">ON</option>
<option value="0">OFF</option>
</select>
<?php } ?>
</div>
<input type="submit" class="button" name="modalFinal" value="<?php $LANGMNG->echo('b_finish'); ?>"/>
</form>
</div>
</div>

View File

@ -1,85 +0,0 @@
<div class="modal-container modal-container-hiden" id="modal-setting-<?php echo $AUTOMATIONID; ?>">
<div class="modal">
<div class="close">
<i class="fa fa-times"></i>
</div>
<h4 class="mb-4"><?php $LANGMNG->echo('t_createAutomation');?></h4>
<form method="post">
<input type="hidden" name="action" value="edit" required/>
<input name="automation_id" type="hidden" value="<?php echo $AUTOMATIONID; ?>">
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_nameAt');?></div>
<div class="field">
<input class="input" type="text" name="name" value="<?php echo (isset ($AUTOMATION['name']) ? $AUTOMATION['name'] : ""); ?>" required/>
</div>
<div class="label"><?php $LANGMNG->echo('l_runAt');?></div>
<div class="field">
<?php //TODO Dodělat identifikaci pro Selctor události a selector času zařízení hodnoty ?>
<select class="input" name="atSelector" id="valueSelector" required>
<option value="sunSet" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "sunSet" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('l_sunSet');?></option>
<option value="sunRise" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "sunRise" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('l_sunRice');?></option>
<option value="inHome" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "inHome" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('l_inHome');?></option>
<option value="outHome" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "outHome" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('l_outHome');?></option>
<option value="time" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "time" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('l_time');?></option>
<option value="atDeviceValue" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "atDeviceValue" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('l_deviceValue');;?></option>
<option value="noOneHome" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "noOneHome" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('w_noOne'); echo ' ' . $LANGMNG->get('w_neni') . ' ' . $LANGMNG->get('w_home');?></option>
<option value="someOneHome" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "someOneHome" ? 'selected="selected"' : ''); ?>><?php $LANGMNG->echo('w_someOne'); echo ' ' . $LANGMNG->get('w_is') . ' ' . $LANGMNG->get('w_home');?></option>
</select>
<input class="input" type="time" name="atTime" id="atTime" value="<?php echo (json_decode($AUTOMATION['ifSomething'], true)['type'] == "time" ? json_decode($AUTOMATION['ifSomething'], true)['value'] : ""); ?>" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "time" ? '' : 'disabled'); ?>/>
<select class="input" name="atDeviceValue" id="atDeviceValue" <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "atDeviceValue" ? '' : 'disabled'); ?>>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){ ?>
<option value="<?php echo $subDeviceKey; ?>"><?php echo $subDeviceValue['name']; ?>[<?php echo $subDeviceValue['type']; ?>]</option>
<?php } ?>
</select>
=
<input class="input" type="text" name="atDeviceValueInt" id="atDeviceValueInt" required <?php ECHO (json_decode($AUTOMATION['ifSomething'], true)['type'] == "atDeviceValue" ? '' : 'disabled'); ?>/>
</div>
<div class="label"><?php $LANGMNG->echo('l_affectedDevices'); ?></div>
<div class="field">
<div class="field px-2">
<?php
$i = 0;
foreach($AUTOMATION['doSomething'] as $subDeviceId => $subDeviceData){ ?>
<div id="automation-<?php echo $AUTOMATIONID; ?>-content">
<div class="label"><?php echo $subDeviceData['name']; ?></div>
<select class="input" name="device[<?php echo $subDeviceId; ?>]">
<option value="0" <?php echo ($subDeviceData['state'] == "0" ? 'selected="selected"' : ''); ?>>off</option>
<option value="1" <?php echo ($subDeviceData['state'] == "1" ? 'selected="selected"' : ''); ?>>on</option>
</select>
<button name="remove" type="button" class="button is-danger fa" data-automation-id="<?php echo $AUTOMATIONID; ?>">&#xf1f8;</button>
</div>
<?php
$i++;
} ?>
</div>
</div>
<div class="label"><?php $LANGMNG->echo('l_atDays');?></div>
<div class="field">
<input type="checkbox" name="day[]" value="mon" <?php ECHO (in_array("mon", $AUTOMATION['onDays']) ? 'checked' : ''); ?>/> <?php $LANGMNG->echo('d_monday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="tue" <?php ECHO (in_array("tue", $AUTOMATION['onDays']) ? 'checked' : ''); ?>/> <?php $LANGMNG->echo('d_tuesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="wed" <?php ECHO (in_array("wed", $AUTOMATION['onDays']) ? 'checked' : ''); ?>/> <?php $LANGMNG->echo('d_wednesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="thu" <?php ECHO (in_array("thu", $AUTOMATION['onDays']) ? 'checked' : ''); ?>/> <?php $LANGMNG->echo('d_thursday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="fri" <?php ECHO (in_array("fri", $AUTOMATION['onDays']) ? 'checked' : ''); ?>/> <?php $LANGMNG->echo('d_friday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sat" <?php ECHO (in_array("sat", $AUTOMATION['onDays']) ? 'checked' : ''); ?>/> <?php $LANGMNG->echo('d_saturday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sun" <?php ECHO (in_array("sun", $AUTOMATION['onDays']) ? 'checked' : ''); ?>/> <?php $LANGMNG->echo('d_sunday'); ?>
</div>
</div>
<input type="submit" class="button" name="modalFinal" value="<?php $LANGMNG->echo('b_edit'); ?>"/>
<input type="submit" class="button is-danger" onClick="ajaxPostSimple('ajax',{automation_id: '<?php echo $AUTOMATIONID ?>', action:'delete'}, true);" name="remove" value="<?php $LANGMNG->echo('b_remove');?>"/>
</form>
</div>
</div>

View File

@ -1,5 +0,0 @@
<script src="<?php echo $BASEDIR; ?>/js/jquery.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-messaging.js"></script>
<script src="<?php echo $BASEDIR; ?>/js/script.js"></script>
<script src="<?php echo $BASEDIR; ?>/js/post.js"></script>

View File

@ -1,29 +0,0 @@
<link rel="manifest" href="manifest.json">
<base href="<?php echo $BASEURL; ?>">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="application-name" content="Home">
<meta name="apple-mobile-web-app-title" content="Home">
<meta name="theme-color" content="#182239">
<meta name="msapplication-navbutton-color" content="#182239">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="msapplication-starturl" content="<?php echo $BASEDIR; ?>">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="icon" sizes="192x192" href="<?php echo $BASEDIR; ?>images/icon-192x192.png">
<link rel="apple-touch-icon" sizes="192x192" href="<?php echo $BASEDIR; ?>images/icon-192x192.png">
<link rel="icon" sizes="512x512" href="<?php echo $BASEDIR; ?>images/icon-512x512.png">
<link rel="apple-touch-icon" sizes="512x512" href="<?php echo $BASEDIR; ?>images/icon-512x512.png">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="<?php echo $BASEDIR; ?>css/main.css?v2">
<link rel="stylesheet" href="<?php echo $BASEDIR; ?>css/font-awesome.min.css">
<link rel="stylesheet" href="<?php echo $BASEDIR; ?>css/modal.css">
<link rel="stylesheet" href="<?php echo $BASEDIR; ?>css/pre.css">
<link rel="stylesheet" href="<?php echo $BASEDIR; ?>css/loading.css">
<link rel="stylesheet" href="<?php echo $BASEDIR; ?>css/override.css">

View File

@ -1,24 +0,0 @@
<div class="modal-container">
<div class="modal">
<h4 class="mb-4">Login</h4>
<form method="post">
<div class="field">
<div class="label">Name:</div>
<input class="input" type="text" name="username" placeholder="Jméno.."/>
</div>
<div class="field">
<div class="label">Password:</div>
<input class="input" type="password" name="password" placeholder="Heslo.."/>
</div>
<div class="field">
<div class="label">Remember me:</div>
<input class="" type="checkbox" name="remember" value="true"/>
</div>
<?php if (!empty ($_SESSION['msg'])): ?>
<label class="alert"><?php echo $_SESSION['msg']; ?></label><br/><br/>
<?php unset ($_SESSION['msg']); ?>
<?php endif; ?>
<input type="submit" class="button" name="login" value="Login"/>
</form>
</div>
</div>

View File

@ -1,13 +0,0 @@
<div class="modal-container">
<div class="modal">
<h4 class="mb-4">OTA</h4>
<form method="post">
<input type="hidden" name="otaSecret" value="<?php echo $OTA; ?>" autocomplete="off"/>
<div class="field">
<div class="label">Code:</div>
<input class="input" type="text" name="otaCode" placeholder=""/>
</div>
<input type="submit" class="button" name="login" value="Login"/>
</form>
</div>
</div>

View File

@ -1,47 +0,0 @@
<div class="nav">
<?php
$menuItems = [
'fa-podcast' => [
'slug' => 'device',
'lngKey' => 'devices',
'path' => 'device',
],
'fas fa-plug' => [
'slug' => 'plugins',
'lngKey' => 'plugins',
'path' => 'plugins',
],
'fa-wrench' => [
'slug' => 'setting',
'lngKey' => 'settings',
'path' => 'setting',
],
'fa-calendar-o' => [
'slug' => 'automation',
'lngKey' => 'automatization',
'path' => 'automation',
],
'fa-bug' =>[
'slug' => 'log',
'lngKey' => 'log',
'path' => 'log',
],
'fa-server' =>[
'slug' => 'server',
'lngKey' => 'server',
'path' => 'server',
],
];
foreach ( $menuItems as $key => $value) {
?>
<div class="nav-item <?php echo ($ITEM == $value ? 'is-active' : ''); ?>">
<a href="<?php echo $value['path']?>">
<i class="fa <?php echo $key ?>"></i>
<span>
<?php $LANGMNG->echo('m_'.$value['lngKey']); ?>
</span>
</a>
</div>
<?php }?>
</div>

View File

@ -1,22 +0,0 @@
<div class="modal-container">
<div class="modal">
<h4 class="mb-4">OAuth</h4>
<form method="post">
<div class="field">
<div class="label">Name:</div>
<input class="input" type="text" name="username" placeholder="Jméno.."/>
</div>
<div class="field">
<div class="label">Password:</div>
<input class="input" type="password" name="password" placeholder="Heslo.."/>
</div>
<input type="hidden" name="responseType" value="<?php echo $RESPONSETYPE; ?>"/>
<input type="hidden" name="redirectUrl" value="<?php echo $REDIRECTURL; ?>"/>
<input type="hidden" name="clientId" value="<?php echo $CLIENTID; ?>"/>
<input type="hidden" name="state" value="<?php echo $STATE; ?>"/>
<input type="submit" class="button" name="login" value="Login"/>
</form>
</div>
</div>

View File

@ -1,16 +0,0 @@
<div class="modal-container">
<div class="modal">
<h4 class="mb-4">OTA</h4>
<form method="post">
<input type="hidden" name="otaSecret" value="<?php echo $OTA; ?>" autocomplete="off"/>
<div class="field">
<div class="label">Code:</div>
<?php
?>
<input class="input" type="text" name="otaCode" placeholder=""/>
</div>
<input type="submit" class="button" name="login" value="Login"/>
</form>
</div>
</div>

Some files were not shown because too many files have changed in this diff Show More