Compare commits

..

4 Commits
3.0 ... master

Author SHA1 Message Date
Haitem 599ef47cd9 Repair room creation 2020-06-11 21:36:15 +02:00
JonatanRek c68c051777 Notification Date Fix 2020-05-20 09:13:17 +02:00
JonatanRek c381261a01 Notification time fix 2020-05-20 08:57:20 +02:00
JonatanRek e39efd9176 Quick Fixes 2020-04-24 18:37:43 +02:00
217 changed files with 13465 additions and 10895 deletions

View File

@ -1,15 +1,31 @@
# https://editorconfig.org/
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
tab_width = 4
[*.{php,phpt,inc}]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = tab
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
charset = utf-8
end_of_line = lf
indent_style = tab
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 80
[*.{yml,yaml}]
indent_size = 2
[COMMIT_EDITMSG]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = tab
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 80

View File

@ -1,49 +0,0 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:xVtSpoWE/jaVTqvkBLSMsqTmkLc6GXTZ/1Hu5t2tIww=
APP_DEBUG=true
APP_URL=http://example-app.test
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=simple_home
DB_USERNAME=root
DB_PASSWORD=toor
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=memcached
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

View File

@ -1,49 +0,0 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:xVtSpoWE/jaVTqvkBLSMsqTmkLc6GXTZ/1Hu5t2tIww=
APP_DEBUG=true
APP_URL=http://example-app.test
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=simple_home
DB_USERNAME=root
DB_PASSWORD=toor
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=memcached
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

View File

@ -1,49 +0,0 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=example_app
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=memcached
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

6
.ftpignore Normal file
View File

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

5
.gitattributes vendored
View File

@ -1,5 +0,0 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore

30
.gitignore vendored
View File

@ -1,19 +1,13 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
docker-compose.override.yml
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
.idea/
.ftpconfig
.ftpconfig2
config.php
_nemazat/index.html
_nemazat/css/main.css.map
_nemazat/css/main.css
_nemazat/css/font-awesome.min.css
app/logs/*.log
.vscode/
.vscode/sftp.json
app/updater/*.bin
logs/*
.vscode

18
.htaccess Normal file
View File

@ -0,0 +1,18 @@
Options -Indexes
Options -MultiViews -Indexes
RewriteEngine On
RewriteBase /vasek/home/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !.css
RewriteCond %{REQUEST_FILENAME} !.js
RewriteRule (.*) index.php?url=$1 [QSA,L]
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_FILENAME} !api.php
RewriteCond %{REQUEST_FILENAME} !apiFront.php
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
AddType application/x-httpd-php .php .phtml

View File

@ -1,13 +0,0 @@
php:
preset: laravel
disabled:
- no_unused_imports
finder:
not-name:
- index.php
- server.php
js:
finder:
not-name:
- webpack.mix.js
css: true

13
.todo Normal file
View File

@ -0,0 +1,13 @@
//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

4
Docs_api.md Normal file
View File

@ -0,0 +1,4 @@
Login
https://dev.steelants.cz/vasek/home/apiFront.php
```json
{"username":"username","password":"password"}```

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
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

@ -135,37 +135,3 @@ Distributed under the MIT License. See `LICENSE` for more information.
Project Link: [https://github.com/GamerClassN7/Smart_Home/](https://github.com/GamerClassN7/Smart_Home/) <br> <br>
<sup><sub>Tags (ignore): ESP32 ESP12 ESP08 ESP01 ESP Smart Home Automation System PWA PHP HTML JS DHT11 DHT22
## Folder structure
```
- /app # app specific files
- /controllers
- UserController.php
- /library # helpers etc.
- /models
- /types
- Units.php
- UserModal.php
- /views
- /layouts
- default.phtml
- /templates
- /components
- /pages
- Bootstrap.php
- Db.php
- Routes.php
- /library # framework, 3rd libraries etc.
- /vendor
- Controller.php
- Db.php
- Router.php
- config
- config.php /
- public
- /css
- /images
- /js
- .htaccess
- index.php
```

View File

@ -0,0 +1,298 @@
-- phpMyAdmin SQL Dump
-- version 4.6.6deb4
-- https://www.phpmyadmin.net/
--
-- Počítač: localhost:3306
-- Vytvořeno: Úte 08. říj 2019, 18:05
-- Verze serveru: 10.1.41-MariaDB-0+deb9u1
-- Verze PHP: 7.0.33-0+deb9u5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Databáze: `smart-home`
--
-- --------------------------------------------------------
--
-- Struktura tabulky `automation`
--
CREATE TABLE `automation` (
`automation_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`on_days` varchar(255) NOT NULL,
`if_something` varchar(255) NOT NULL,
`do_something` varchar(255) NOT NULL,
`executed` tinyint(4) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
`locked` tinyint(4) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `dashboard`
--
CREATE TABLE `dashboard` (
`dashboard_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`subdevice_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `devices`
--
CREATE TABLE `devices` (
`device_id` int(11) NOT NULL,
`room_id` int(11) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`token` varchar(255) NOT NULL,
`sleep_time` int(13) NOT NULL,
`owner` int(13) NOT NULL,
`permission` varchar(255) NOT NULL,
`approved` int(11) NOT NULL,
`icon` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `notifications`
--
CREATE TABLE `notifications` (
`id` int(13) NOT NULL,
`user_id` varchar(255) NOT NULL,
`token` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `records`
--
CREATE TABLE `records` (
`record_id` int(11) NOT NULL,
`subdevice_id` int(11) NOT NULL,
`value` smallint(6) NOT NULL,
`time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`execuded` tinyint(4) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `rooms`
--
CREATE TABLE `rooms` (
`room_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `scenes`
--
CREATE TABLE `scenes` (
`scene_id` int(11) NOT NULL,
`icon` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`do_something` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `subdevices`
--
CREATE TABLE `subdevices` (
`subdevice_id` int(11) NOT NULL,
`device_id` int(11) NOT NULL,
`type` varchar(255) NOT NULL,
`unit` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktura tabulky `users`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`startPage` int(11) NOT NULL,
`at_home` varchar(255) NOT NULL DEFAULT 'false'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Vypisuji data pro tabulku `users`
--
INSERT INTO `users` (`user_id`, `username`, `password`, `startPage`) VALUES
(2, 'Admin', '08abb3ff83dfae60fb4591125fc49dc80cf7ef28224c2d5df86e2d0d037c553bc7f30e859348fd745c9c07a4edde4863e866a7d45356cf08a22e5e1eafa13406', 1);
--
-- Klíče pro exportované tabulky
--
--
-- Klíče pro tabulku `automation`
--
ALTER TABLE `automation`
ADD PRIMARY KEY (`automation_id`);
--
-- Klíče pro tabulku `dashboard`
--
ALTER TABLE `dashboard`
ADD PRIMARY KEY (`dashboard_id`),
ADD KEY `user_id` (`user_id`),
ADD KEY `subdevice_id` (`subdevice_id`);
--
-- Klíče pro tabulku `devices`
--
ALTER TABLE `devices`
ADD PRIMARY KEY (`device_id`),
ADD KEY `room_id` (`room_id`);
--
-- Klíče pro tabulku `notifications`
--
ALTER TABLE `notifications`
ADD PRIMARY KEY (`id`);
--
-- Klíče pro tabulku `records`
--
ALTER TABLE `records`
ADD PRIMARY KEY (`record_id`),
ADD KEY `device_id` (`subdevice_id`);
--
-- Klíče pro tabulku `rooms`
--
ALTER TABLE `rooms`
ADD PRIMARY KEY (`room_id`);
--
-- Klíče pro tabulku `scenes`
--
ALTER TABLE `scenes`
ADD PRIMARY KEY (`scene_id`);
--
-- Klíče pro tabulku `subdevices`
--
ALTER TABLE `subdevices`
ADD PRIMARY KEY (`subdevice_id`),
ADD KEY `device_id` (`device_id`);
--
-- Klíče pro tabulku `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT pro tabulky
--
--
-- AUTO_INCREMENT pro tabulku `automation`
--
ALTER TABLE `automation`
MODIFY `automation_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=58;
--
-- AUTO_INCREMENT pro tabulku `dashboard`
--
ALTER TABLE `dashboard`
MODIFY `dashboard_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
--
-- AUTO_INCREMENT pro tabulku `devices`
--
ALTER TABLE `devices`
MODIFY `device_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
--
-- AUTO_INCREMENT pro tabulku `notifications`
--
ALTER TABLE `notifications`
MODIFY `id` int(13) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT pro tabulku `records`
--
ALTER TABLE `records`
MODIFY `record_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=352338;
--
-- AUTO_INCREMENT pro tabulku `rooms`
--
ALTER TABLE `rooms`
MODIFY `room_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
--
-- AUTO_INCREMENT pro tabulku `scenes`
--
ALTER TABLE `scenes`
MODIFY `scene_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT pro tabulku `subdevices`
--
ALTER TABLE `subdevices`
MODIFY `subdevice_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
--
-- AUTO_INCREMENT pro tabulku `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- Omezení pro exportované tabulky
--
--
-- Omezení pro tabulku `dashboard`
--
ALTER TABLE `dashboard`
ADD CONSTRAINT `dashboard_ibfk_2` FOREIGN KEY (`subdevice_id`) REFERENCES `subdevices` (`subdevice_id`) ON DELETE CASCADE ON UPDATE NO ACTION,
ADD CONSTRAINT `dashboard_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
--
-- Omezení pro tabulku `devices`
--
ALTER TABLE `devices`
ADD CONSTRAINT `devices_ibfk_1` FOREIGN KEY (`room_id`) REFERENCES `rooms` (`room_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Omezení pro tabulku `records`
--
ALTER TABLE `records`
ADD CONSTRAINT `records_ibfk_1` FOREIGN KEY (`subdevice_id`) REFERENCES `subdevices` (`subdevice_id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Omezení pro tabulku `subdevices`
--
ALTER TABLE `subdevices`
ADD CONSTRAINT `subdevices_ibfk_1` FOREIGN KEY (`device_id`) REFERENCES `devices` (`device_id`);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

BIN
_README_IMG/desktop1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

BIN
_README_IMG/desktop2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

BIN
_README_IMG/desktop3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

BIN
_README_IMG/mobile1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

BIN
_README_IMG/mobile2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

BIN
_README_IMG/mobile3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

326
api.php Normal file
View File

@ -0,0 +1,326 @@
<?php
/** Includes **/
include_once('./config.php');
//Autoloader
$files = scandir('./app/class/');
$files = array_diff($files, array(
'.',
'..',
'app',
'ChartJS.php',
'ChartJS_Line.php',
'ChartManager.php',
'DashboardManager.php',
'Partial.php',
'Form.php',
'Route.php',
'Template.php',
'Ajax.php',
));
foreach($files as $file) {
include './app/class/'. $file;
}
//Allow acces only wia Curl, Ajax ETC
/*$restAcess = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
if (!$restAcess){
header('Location: ./');
}*/
//Log
$logManager = new LogManager();
$apiLogManager = new LogManager('./app/logs/api/'. date("Y-m-d").'.log');
//DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
//Read API data
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
//Log RAW api request
if (API_DEBUGMOD == 1) {
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO);
}
//zabespecit proti Ddosu
if (isset($obj['user']) && $obj['user'] != ''){
//user at home
$user = UserManager::getUser($obj['user']);
$userAtHome = $user['at_home'];
if (!empty($user)) {
$userId = $user['user_id'];
$atHome = $obj['atHome'];
if($userAtHome != $atHome){
UserManager::atHome($userId, $atHome);
$logManager->write("[USER] user " . $userId . " changet his home state to " . $atHome , LogRecordType::INFO);
}
echo 'Saved: ' . $atHome;
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
die();
}
}
//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!",
), JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
$logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
exit();
}
}
//automationExecution
try {
AutomationManager::executeAll();
$fallbackManager = new FallbackManager(RANGES);
$fallbackManager->check();
//LogKeeper::purge(LOGTIMOUT);
} catch (\Exception $e) {
$logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR);
}
//Record Cleaning
try {
RecordManager::clean(RECORDTIMOUT);
} catch (\Exception $e) {
$logManager->write("[Record] cleaning record older that " . RECORDTIMOUT , LogRecordType::ERROR);
}
//Variables
$token = $obj['token'];
$values = null;
$settings = null;
$deviceLogs = null;
$command = "null";
if (isset($obj['values'])) {
$values = $obj['values'];
}
if (isset($obj['settings'])) {
$settings = $obj['settings'];
}
if (isset($obj['logs'])) {
$deviceLogs = $obj['logs'];
}
//Checks
if ($token == null || $token == "") {
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Missing Value Token in JSON payload",
), JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
die();
}
//Vstupní Checky
if (!DeviceManager::registeret($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
$deviceId = DeviceManager::create($token, $token);
foreach ($values as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
SubDeviceManager::create($deviceId, $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'] . " ", LogRecordType::INFO);
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Device not registeret",
), JSON_PRETTY_PRINT);
$logManager->write("[API] Registering Device", LogRecordType::INFO);
exit();
}
if (!DeviceManager::approved($token)) {
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Unaproved Device",
), JSON_PRETTY_PRINT);
exit();
}
// Diagnostic Data Write to DB
if ($settings != null && $settings != ""){
$data = ['mac' => $settings["network"]["mac"], 'ip_address' => $settings["network"]["ip"]];
if (array_key_exists("firmware_hash", $settings)) {
$data['firmware_hash'] = $settings["firmware_hash"];
}
DeviceManager::editByToken($token, $data);
$jsonAnswer = [
'state' => 'succes',
'command' => $command,
];
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
die();
}
// Issuing command
if ($command == "null"){
$device = DeviceManager::getDeviceByToken($token);
$deviceId = $device['device_id'];
$deviceCommand = $device["command"];
if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null")
{
$command = $deviceCommand;
$data = [
'command'=>'null'
];
DeviceManager::editByToken($token, $data);
$logManager->write("[API] Device_ID " . $deviceId . " executing command " . $command, LogRecordType::INFO);
}
}
// Diagnostic Logs Write To log File
if ($deviceLogs != null && $deviceLogs != ""){
foreach ($deviceLogs as $log) {
$logManager->write("[Device Log Msg] Device_ID " . $deviceId . "->" . $log, LogRecordType::ERROR);
}
$jsonAnswer = [
'state' => 'succes',
'command' => $command,
];
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
die();
}
//
if (count($values) == 1){
unset($values["wifi"]);
}
// Subdevices first data!
if ($values != null && $values != "") {
//ZAPIS
$device = DeviceManager::getDeviceByToken($token);
$deviceId = $device['device_id'];
foreach ($values as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
SubDeviceManager::create($deviceId, $key, UNITS[$key]);
}
RecordManager::create($deviceId, $key, round($value['value'],3));
$logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::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'] . " ", LogRecordType::INFO);
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
}
}
$hostname = strtolower($device['name']);
$hostname = str_replace(' ', '_', $hostname);
//upravit format na setings-> netvork etc
$jsonAnswer = [
'device' => [
'hostname' => $hostname,
'ipAddress' => $device['ip_address'],
'subnet' => $device['subnet'],
'gateway' => $device['gateway'],
],
'state' => 'succes',
'command' => $command,
];
$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId);
if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
$jsonAnswer['device']['sleepTime'] = $device['sleep_time'];
}
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
} else {
//Vypis
$device = DeviceManager::getDeviceByToken($token);
$deviceId = $device['device_id'];
if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) {
SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]);
//RecordManager::create($deviceId, 'on/off', 0);
}
$subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id'];
$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
$subDeviceLastReordValue = $subDeviceLastReord['value'];
if ($subDeviceLastReord['execuded'] == 0){
$logManager->write("[API] subDevice_ID ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded'], LogRecordType::INFO);
RecordManager::setExecuted($subDeviceLastReord['record_id']);
}
echo json_encode(array(
'device' => [
'hostname' => $device['name'],
'ipAddress' => $device['ip_address'],
'subnet' => $device['subnet'],
'gateway' => $device['gateway'],
],
'state' => 'succes',
'value' => $subDeviceLastReordValue,
'command' => $command,
), JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
}
unset($logManager);
Db::disconect();
die();

98
apiFront.php Normal file
View File

@ -0,0 +1,98 @@
<?php
/** Includes **/
include_once('./config.php');
//Autoloader
$files = scandir('./app/class/');
$files = array_diff($files, array(
'.',
'..',
'app',
'ChartJS.php',
'ChartJS_Line.php',
'ChartManager.php',
'DashboardManager.php',
'Partial.php',
'Form.php',
'Route.php',
'Template.php',
'Ajax.php',
));
foreach($files as $file) {
include './app/class/'. $file;
}
//Log
$apiLogManager = new LogManager('./app/logs/apiFront/'. date("Y-m-d").'.log');
//DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
//Read API data
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
//Log RAW api request
if (API_DEBUGMOD == 1) {
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO);
}
$apiManager = new ApiManager();
echo $apiManager->generateToken($obj['username'],$obj['password']);
die();
/*
if (
isset($obj['username']) &&
$obj['username'] != '' &&
isset($obj['password']) &&
$obj['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: ' . BASEDIR . $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: ' . BASEDIR . $landingPage);
echo 'OK';
} else {
echo 'FAILED';
}
//TODO: upravi a ověřit jeslti ja zabezpečené
//TODO:
die();
}
*/
/*unset($logManager);
Db::disconect();
die();*/

View File

@ -1,41 +0,0 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Domain\Device\Factories;
use App\Models\Device;
/**
* Class DeviceFactory
* @package App\Domain\Device\Factories
*/
class DeviceFactory
{
public function create(string $name, ?string $description = null): Device
{
return Device::create([
'name' => $name,
'description' => $description
]);
}
}

View File

@ -1,12 +0,0 @@
<?php
namespace App\Domain\Device\Repositories;
/**
* Class DeviceRepository
* @package App\Domain\Device\Repositories
*/
class DeviceRepository
{
}

View File

@ -1,35 +0,0 @@
<?php
namespace App\Domain\Legacy\Transformers;
use App\Models\Device;
use Illuminate\Database\Eloquent\Collection;
class DeviceTransformer
{
public function index(Collection $devices): array
{
return $devices->map(function (Device $device) {
return [
"device" => [
"hostname" => "2",
"sleepTime" => 0,
],
"state" => "success",
"value" => "0"
];
})->toArray();
}
public function show(Device $device): array
{
return [
"device" => [
"hostname" => "2",
"sleepTime" => 0,
],
"state" => "success",
"value" => "0"
];
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Domain\Room\Factories;
use App\Models\Room;
/**
* Class RoomFactory
* @package App\Domain\Room\Factories
*/
class RoomFactory
{
public function create(string $name): Room
{
return Room::create([
'name' => $name
]);
}
}

View File

@ -1,17 +0,0 @@
<?php
namespace App\Domain\Room\Repositories;
use App\Models\Room;
/**
* Class RoomRepository
* @package App\Domain\Room\Repositories
*/
class RoomRepository
{
public function all()
{
return Room::all();
}
}

View File

@ -1,40 +0,0 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

View File

@ -1,43 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Room\Factories\RoomFactory;
use App\Domain\Room\Repositories\RoomRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class RoomController extends Controller
{
private RoomRepository $roomRepository;
public function __construct(RoomRepository $roomRepository)
{
$this->roomRepository = $roomRepository;
}
public function index(): JsonResponse
{
$rooms = $this->roomRepository->all();
return response()->json(
$rooms->toArray()
);
}
public function store(RoomFactory $roomFactory): JsonResponse
{
$this->validate(request(), [
'name' => 'required|string|unique:rooms,name'
]);
$room = $roomFactory->create(
request()->post('name')
);
return response()->json(
$room->toArray()
);
}
}

View File

@ -1,66 +0,0 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}

View File

@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -1,32 +0,0 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}

View File

@ -1,20 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace App\Http\Middleware;
use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

View File

@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Device extends Model
{
use HasFactory;
protected $fillable = ['name', 'description'];
}

View File

@ -1,15 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Room extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
}

View File

@ -1,43 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

View File

@ -1,28 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}

View File

@ -1,63 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/home';
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* @var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
}

30
app/class/ApiManager.php Normal file
View File

@ -0,0 +1,30 @@
<?php
class ApiManager {
public function generateToken($username, $password){
$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]);
// 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;
return $jwt;
}
}
return false;
}
}

View File

@ -0,0 +1,175 @@
<?php
class AutomationManager{
public static $automation;
public function remove($automationId) {
return Db::command ('DELETE FROM automation WHERE automation_id=?', array ($automationId));
}
public 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 function restart($automationId) {
return Db::command ('UPDATE automation SET executed = 0 WHERE automation_id=?', array ($automationId));
}
public 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 function getAll(){
return Db::loadAll ("SELECT * FROM automation");
}
public 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']));
}
}
}
}
}

194
app/class/ChartJS.php Normal file
View File

@ -0,0 +1,194 @@
<?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

@ -0,0 +1,21 @@
<?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;
}
}

129
app/class/ChartManager.php Normal file
View File

@ -0,0 +1,129 @@
<?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;
}
}
?>

100
app/class/DB.php Normal file
View File

@ -0,0 +1,100 @@
<?php
class Db{
private static $join;
private static $commandDatabase = array (
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_EMULATE_PREPARES => false
);
public static function connect ($host, $user, $password, $database) {
if (!isset (self::$join)) {
self::$join = @new PDO(
"mysql:host=$host;dbname=$database;charset=utf8",
$user,
$password,
self::$commandDatabase
);
self::$join->exec ("set names utf8");
}
}
public static function disconect(){
self::$join = null;
}
public static function loadOne ($sql, $values = array (), $numberKey = false) {
$answer = self::$join->prepare ($sql);
$answer->execute ($values);
if (!$numberKey) {
return $answer->fetch (PDO::FETCH_ASSOC);
} else {
return $answer->fetch (PDO::FETCH_NUM);
}
}
public static function command ($sql, $values = array()) {
$answer = self::$join->prepare ($sql);
return $answer->execute ($values);
}
public static function loadAll ($sql, $values = array(), $numberKey = false) {
$answer = self::$join->prepare ($sql);
$answer->execute ($values);
if (!$numberKey) {
return $answer->fetchALL (PDO::FETCH_ASSOC);
} else {
return $answer->fetchALL (PDO::FETCH_NUM);
}
}
public static function loadAlone ($sql, $values = array()) {
$answer = self::$join->prepare ($sql);
$answer->execute ($values);
return $answer->fetch (PDO::FETCH_NUM)[0];
}
public static function add ($table, $values = array()) {
return self::command (
"INSERT INTO `$table` (`" .
implode('`, `', array_keys($values)) .
"`) VALUES (" .
str_repeat('?,', (count($values) > 0 ? count($values)-1 : 0)) .
"?)"
, array_values ($values));
}
// TODO: pokud vlozim prazdne pole tak chyba ??
public static function addAll ($table, $values = array ()) {
try {
foreach ($values as $value) {
self::add ($table, $value);
}
} catch (PDOException $ex) {
throw new PDOException ($ex->getMessage());
}
}
public static function edit (
$table,
$values = array(),
$conditions,
$values2 = array()
) {
return self::command (
"UPDATE `$table` SET `" .
implode('` =?, `', array_keys($values)) .
"` =? " .
$conditions
, array_merge (array_values ($values), $values2));
}
public static function insertId () {
return self::$join->lastInsertId ();
}
public static function addId ($lastTable, $lastIdName) {
$answer = self::$join->prepare ("SELECT `$lastIdName` FROM `$lastTable` ORDER BY `$lastIdName` DESC");
$answer->execute ();
return $answer->fetch (PDO::FETCH_NUM)[0];
}
}

View File

@ -0,0 +1,41 @@
<?php
class DashboardManager{
public static $devices;
function getAllDashboards ($userId) {
return Db::loadAll ("SELECT * FROM dashboard WHERE user_id=?", array($userId));
}
function getAllSubDevices ($userId) {
return Db::loadAll ("SELECT * FROM subdevices WHERE subdevice_id IN (SELECT subdevice_id FROM dashboard WHERE user_id=?)", array($userId));
}
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));
}
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();
}
}
}
function Remove ($subDeviceId){
$userId = UserManager::getUserData('user_id');
Db::command ('DELETE FROM dashboard WHERE subdevice_id=? AND user_id = ?', array ($subDeviceId, $userId));
}
}

View File

@ -0,0 +1,96 @@
<?php
class DeviceManager{
public static $devices;
function getAllDevices () {
return Db::loadAll ("SELECT * FROM devices WHERE approved != ?", Array(2));
}
function getAllDevicesInRoom ($roomId = "") {
return Db::loadAll ("SELECT * FROM devices WHERE room_id = ? AND approved != ?", Array($roomId, 2));
}
function getOtherDevices(){
return Db::loadAll ("SELECT * FROM devices WHERE room_id IS NULL ");
}
function getDeviceByToken($deviceToken) {
return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken));
}
function getDeviceByMac($deviceMac) {
return Db::loadOne("SELECT * FROM devices WHERE mac = ?", array($deviceMac));
}
function getDeviceById($deviceId) {
return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
}
public function create ($name, $token) {
$defaultRoom = RoomManager::getDefaultRoomId();
$device = array (
'name' => $name,
'token' => $token,
'room_id' => $defaultRoom,
);
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 function edit ($deviceId, $values = []) {
try {
Db::edit ('devices', $values, 'WHERE device_id = ?', array($deviceId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public 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 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 function delete ($deviceId) {
Db::command ('DELETE FROM devices WHERE device_id=?', array ($deviceId));
}
public function registeret ($deviceToken) {
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=?", array($deviceToken))) == 1 ? true : false);
}
public function approved ($deviceToken) {
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=? AND approved = ?", array($deviceToken, 1))) == 1 ? true : false);
}
}
?>

View File

@ -0,0 +1,44 @@
<?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"]);
}
}
}
}
}

121
app/class/Form.php Normal file
View File

@ -0,0 +1,121 @@
<?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;
}
}

59
app/class/LangManager.php Normal file
View File

@ -0,0 +1,59 @@
<?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 = './app/lang/en.php';
if (!file_exists($file)){
die();
//TODO add lng EXEPTIONS
}
$arrayFirst = include($file);
$file = './app/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;
}
}

60
app/class/LogManager.php Normal file
View File

@ -0,0 +1,60 @@
<?php
/**
*
*/
class LogRecordType{
const WARNING = 'warning';
const ERROR = 'error';
const INFO = 'info';
}
class LogKeeper
{
function purge($days){
$todayFileName = date("Y-m-d").'.log';
$seconds = $days * 86400;
$logFiles = scandir('./app/logs/');
foreach ($logFiles as $key => $file) {
if (in_array($file,array(".","..", ".gitkeep", $todayFileName)))
{
continue;
}
if (filemtime($file) > $seconds) {
unlink('./app/logs/'.$file);
}
}
}
}
class LogManager
{
private $logFile;
function __construct($fileName = "")
{
if ($fileName == ""){
$fileName = './app/logs/'. date("Y-m-d").'.log';
}
if(!is_dir("./app/logs/"))
{
mkdir("./app/logs/");
}
$this->logFile = fopen($fileName, "a") or die("Unable to open file!");
}
function write($value, $type = LogRecordType::ERROR){
$record = "[".date("H:m:s")."][".$type."]" . $value . "\n";
if (strlen($record) > 65 ) {
$record = Utilities::stringInsert($record,"\n",65);
}
fwrite($this->logFile, $record);
}
function __destruct(){
if (isset($this->logFile)) {
fclose($this->logFile);
}
}
}

View File

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

View File

@ -0,0 +1,107 @@
<?php
/**
* Notification Manager
*/
//TODO: Working timestamp to body or $title
class NotificationManager
{
function addSubscriber($userID = '', $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);
}
}
function getSubscription () {
return Db::loadAll ("SELECT * FROM notifications");
}
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'], $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"] = date("h:i") . " - " . $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;
}
}

34
app/class/Partial.php Normal file
View File

@ -0,0 +1,34 @@
<?php
class Partial{
var $assignedValues = [];
var $partBuffer;
var $path;
var $debug;
function __construct($path = "", $debug = false) {
$this->debug = $debug;
if (!empty('app/templates/part/' . $path . '.phtml') && file_exists('app/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/templates/part/' . $this->path . '.phtml');
}
}

View File

@ -0,0 +1,80 @@
<?php
class RecordManager{
public static $records;
public 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;
};
$record = array (
'subdevice_id' => $subDeviceId,
'value' => $value,
);
try {
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 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));
}
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');
$groupBy = strtoupper($groupBy).'(time)';
$sql = 'SELECT value, time FROM records
WHERE
subdevice_id = ?
AND
value != 999
AND
time > ?
GROUP BY '.$groupBy.'
ORDER BY time ASC';
//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));
}
}
?>

31
app/class/RoomManager.php Normal file
View File

@ -0,0 +1,31 @@
<?php
class RoomManager{
public static $rooms;
function getDefaultRoomId() {
$defaultRoom = Db::loadOne("SELECT room_id FROM rooms WHERE 'default' = 1");
return $defaultRoom['room_id'];
}
function getAllRooms () {
$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;
}
public function create ($name) {
$room = array (
'name' => $name,
);
try {
Db::add ('rooms', $room);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function delete ($roomId) {
Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId));
}
}
?>

30
app/class/Route.php Normal file
View File

@ -0,0 +1,30 @@
<?php
class Route{
private $urls = [];
private $views = [];
function __construct() {
// code...
}
function add($url, $view = "", $conrol = "") {
$this->urls[] = '/'.trim($url, '/');
if (!empty($view)) {
$this->views[] = $view;
}
}
function submit(){
$urlGetParam = isset($_GET['url']) ? '/' . $_GET['url'] : '/';
foreach ($this->urls as $urlKey => $urlValue) {
if ($urlValue === $urlGetParam) {
$useView = $this->views[$urlKey];
new $useView();
die();
}
}
echo 'Not Fount 404';
die();
//TODO: 404 přidělat
}
}

View File

@ -0,0 +1,41 @@
<?php
class SceneManager{
public static $scenes;
public 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 function getAllScenes () {
return Db::loadAll ("SELECT * FROM scenes");
}
public function getScene ($sceneId) {
return Db::loadOne("SELECT * FROM scenes WHERE scene_id = ?", array($sceneId));
}
public 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 function delete($sceneId){
Db::command ('DELETE FROM scenes WHERE scene_id=?', array ($sceneId));
}
}
?>

View File

@ -0,0 +1,71 @@
<?php
class SubDeviceManager
{
public static $devices;
public function getAllSubDevices($deviceId)
{
return Db::loadAll("SELECT * FROM subdevices WHERE device_id = ?", array($deviceId));
}
public function getSubDeviceMaster($subDeviceId)
{
return Db::loadOne("SELECT * FROM devices WHERE device_id = (SELECT device_id FROM subdevices WHERE subdevice_id = ?)", array($subDeviceId));
}
public 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 function getSubDeviceByMasterAndType($deviceId, $subDeviceType = null)
{
if (!empty($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 function getSubDevice($subDeviceId)
{
return Db::loadOne("SELECT * FROM subdevices WHERE subdevice_id = ?;", array($subDeviceId));
}
public 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
public 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 function remove($subDeviceId)
{
RecordManager::cleanSubdeviceRecords($subDeviceId);
return Db::loadAll("DELETE FROM subdevices WHERE subdevice_id = ?", array($subDeviceId));
}
}

34
app/class/Template.php Normal file
View File

@ -0,0 +1,34 @@
<?php
class Template extends Partial{
var $assignedValues = [];
var $partBuffer;
var $path;
var $debug;
function __construct($path = "", $debug = false) {
$this->debug = $debug;
if (!empty('app/templates/' . $path . '.phtml') && file_exists('app/templates/' . $path . '.phtml')) {
$this->path = $path;
} else {
echo '<pre>';
echo 'PHTML: Template 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() {
extract($this->assignedValues);
if (!empty('app/controls/' . $this->path . '.php') && file_exists('app/controls/' . $this->path . '.php')) {
include('app/controls/' . $this->path . '.php');
}
require_once('app/templates/' . $this->path . '.phtml');
}
}

210
app/class/UserManager.php Normal file
View File

@ -0,0 +1,210 @@
<?php
class UserManager
{
public function getUsers () {
try {
$allUsers = Db::loadAll ("SELECT user_id, username, at_home, ota FROM users");
return $allUsers;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function getUser ($userName) {
try {
$user = Db::loadOne ("SELECT * FROM users WHERE username = ?", [$userName]);
return $user;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function getUserId ($userId) {
try {
$user = Db::loadOne ("SELECT * FROM users WHERE user_id = ?", [$userId]);
return $user;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function getAvatarUrl($userId = null){
$email = self::getUserData('email');
if ($userId != null){
$email = self::getUserData('email',$userId);
}
return 'https://secure.gravatar.com/avatar/' . md5( strtolower( trim( $email ) ) );
}
public function login ($username, $password, $rememberMe) {
try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
if ($user['password'] == UserManager::getHashPassword($password)) {
if (isset($rememberMe) && $rememberMe == 'true') {
setcookie ("rememberMe", $this->setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
}
$_SESSION['user']['id'] = $user['user_id'];
$page = "";
if ($user["startPage"] == 1) {
$page = "dashboard";
}
unset($_POST['login']);
return $page;
} else {
throw new PDOException("Heslo není správné!");
}
} else {
throw new PDOException("Uživatel s tím to jménem neexistuje!");
}
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function loginNew ($username, $password) {
try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
if ($user['password'] == UserManager::getHashPassword($password)) {
echo "user loged in";
return $user['user_id'];
} else {
return false;
}
} else {
return false;
}
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public 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 ($this->getDecryptedCookie($_COOKIE['rememberMe'])))) {
$_SESSION['user']['id'] = $user['user_id'];
return true;
}
}
}
return false;
}
public function logout () {
unset($_SESSION['user']);
session_destroy();
if (isset($_COOKIE['rememberMe'])){
unset($_COOKIE['rememberMe']);
setcookie("rememberMe", 'false', time(), BASEDIR, $_SERVER['HTTP_HOST']);
}
}
public 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 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 function setUserData ($type, $value) {
if (isset ($_SESSION['user']['id'])) {
Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $_SESSION['user']['id']));
}
}
public function getHashPassword ($password) {
$salt = "s0mRIdlKvI";
$hashPassword = hash('sha512', ($password . $salt));
return $hashPassword;
}
public function atHome($userId, $atHome){
try {
Db::edit ('users', ['at_home' => $atHome], 'WHERE user_id = ?', array($userId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public 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 function createUser($userName, $password){
$userId = Db::loadOne('SELECT * FROM users WHERE username = ?;', array($userName))['user_id'];
if ($userId != null) {
return false;
};
try {
$user = [
'username' => $userName,
'password' => self::getHashPassword($password),
];
return Db::add ('users', $user);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function haveOtaEnabled($userName){
$ota = $this->getUser($userName)['ota'];
if ($ota != ''){
return ($ota != '' ? $ota : false);
} else {
return false;
}
}
}
?>

144
app/class/Utilities.php Normal file
View File

@ -0,0 +1,144 @@
<?php
/**
*
*/
class Utilities
{
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);
}
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]
*/
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);
}
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;
}
function pluralize( $count, $text )
{
return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}
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
}
}

View File

@ -0,0 +1,77 @@
<?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: ' . BASEDIR . 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: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
die();
}
}
?>

View File

@ -0,0 +1,13 @@
<?php
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['modalFinal']) && $_POST['modalFinal'] != "") {
$subDeviceIds = $_POST['devices'];
foreach ($subDeviceIds as $subDeviceId) {
DashboardManager::Add($subDeviceId);
}
}
header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
die();
}
?>

87
app/controls/home.php Normal file
View File

@ -0,0 +1,87 @@
<?php
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['saveDevice']) && $_POST['saveDevice'] != "") {
$deviceId = $_POST['deviceId'];
$deviceName = $_POST['deviceName'];
$deviceIcon = $_POST['deviceIcon'];
$sleepTime = 0;
if (isset($_FILES['deviceFirmware']) && isset($_FILES['deviceFirmware']['tmp_name']) && $_FILES['deviceFirmware']['tmp_name'] != "") {
$file = $_FILES['deviceFirmware'];
$deviceMac = DeviceManager::getDeviceById($deviceId)['mac'];
$fileName = (isset ($deviceMac) && $deviceMac != "" ? str_replace(":", "", $deviceMac) . ".bin" : "");
if ($fileName != "" && file_exists("./app/updater/" . $fileName)) {
unlink("./app/updater/" . $fileName);
}
if ($fileName != "") {
copy($file['tmp_name'], "./app/updater/" . $fileName);
} else {
}
}
if (isset($_POST['sleepTime'])) {
$sleepTime = $_POST['sleepTime'];
}
//TODO: if device isnt on off
$permissionsInJson = json_encode([
(int) $_POST['permissionOwner'],
(int) $_POST['permissionOther'],
]);
$deviceOwnerUserId = $_POST['deviceOwnerUserId'];
$deviceOwnerRoomId = $_POST['deviceOwnerId'];
try {
$args = array(
'owner' => $deviceOwnerUserId,
'name' => $deviceName,
'icon' => $deviceIcon,
'permission' => $permissionsInJson,
'sleep_time' => $sleepTime,
'room_id' => $deviceOwnerRoomId,
);
DeviceManager::edit($deviceId, $args);
} catch (\Exception $e) {
echo $e->message();
}
//Debug
if (DEBUGMOD == 1) {
echo '<pre>';
echo $permissionsInJson;
echo $deviceId;
var_dump(json_decode ($permissionsInJson));
echo '</pre>';
echo '<a href="' . BASEDIR .'">CONTINUE</a>';
die();
}
} else if (isset($_POST['approveDevice'])) {
$deviceId = $_POST['deviceId'];
$args = array(
'approved' => 1,
);
DeviceManager::edit($deviceId, $args);
} else if (isset($_POST['disableDevice'])) {
$deviceId = $_POST['deviceId'];
$args = array(
'approved' => 2,
);
DeviceManager::edit($deviceId, $args);
}
//Debug
if (DEBUGMOD == 1) {
echo '<pre>';
var_dump($POST);
echo '</pre>';
echo '<a href="' . BASEDIR . '">CONTINUE</a>';
die();
}
header('Location: ' . BASEDIR );
die();
}
?>

51
app/controls/login.php Normal file
View File

@ -0,0 +1,51 @@
<?php
global $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: ' . BASEDIR . $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: ' . BASEDIR . $landingPage);
echo 'OK';
} else {
echo 'FAILED';
}
//TODO: upravi a ověřit jeslti ja zabezpečené
//TODO:
die();
}

18
app/controls/scene.php Normal file
View File

@ -0,0 +1,18 @@
<?php
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['submitFinal']) && $_POST['submitFinal'] != "") {
SceneManager::create($_POST['sceneIcon'], $_POST['sceneName'], json_encode($_POST['devices']));
header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
die();
}
//Debug
if (DEBUGMOD == 1) {
echo '<pre>';
var_dump($_POST);
echo '</pre>';
echo '<a href="/' . BASEDIR . strtolower(basename(__FILE__, '.php')).'">CONTINUE</a>';
die();
}
}

34
app/controls/setting.php Normal file
View File

@ -0,0 +1,34 @@
<?php
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
$oldPassword = $_POST['oldPassword'];
$newPassword = $_POST['newPassword1'];
$newPassword2 = $_POST['newPassword2'];
UserManager::changePassword($oldPassword, $newPassword, $newPassword2);
header('Location: ' . BASEDIR . 'logout');
die();
} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
$userName = $_POST['userName'];
$password = $_POST['userPassword'];
UserManager::createUser($userName, $password);
header('Location: ' . BASEDIR . 'setting');
die();
} else if (isset($_POST['submitCreateRoom']) && $_POST['submitCreateRoom'] != "") {
$roomName = $_POST['roomName'];
RoomManager::create($roomName);
header('Location: ' . BASEDIR . 'setting');
die();
} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
echo $otaCode = $_POST['otaCode'];
echo $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: ' . BASEDIR . 'setting');
die();
}
}

17
app/controls/settings.php Normal file
View File

@ -0,0 +1,17 @@
<?php
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
$oldPassword = $_POST['oldPassword'];
$newPassword = $_POST['newPassword1'];
$newPassword2 = $_POST['newPassword2'];
UserManager::changePassword($oldPassword, $newPassword, $newPassword2);
header('Location: ' . BASEDIR . 'logout');
die();
} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
$userName = $_POST['userName'];
$password = $_POST['userPassword'];
UserManager::createUser($userName, $password);
header('Location: ' . BASEDIR . 'setting');
die();
}
}

123
app/lang/cs.php Normal file
View File

@ -0,0 +1,123 @@
<?php
return $lang = [
//Menu
'm_home' => 'Domů',
'm_dashboard' => 'Nástěnka',
'm_settings' => 'Nastavení',
'm_automatization' => 'Automatizace',
'm_scenes' => 'Scény',
'm_log' => 'Log',
//Buttons
'b_year' => 'Rok',
'b_month' => 'Měsíc',
'b_week' => 'Týden',
'b_day' => 'Den',
'b_hour' => 'Hodina',
'b_next' => 'Další',
'b_create' => 'Vytvořit',
'b_edit' => 'Upravit',
'b_remove' => 'Smazat',
'b_finish' => 'Dokončit',
'b_approve' => 'Povolit',
'b_disable' => 'Zakázat',
'b_save' => 'Uložit',
'b_logOut' => 'Odhlásit',
'b_sendTestNotification' => 'Odeslat testovací notifikaci',
'b_rooms' => 'Místnosti',
'b_restart' => 'Restart',
'b_disable' => 'Deaktivovat',
'b_select' => 'Zvolit',
'b_ota' => 'ota',
//labels
'l_choseDevice' => 'Zvolte zařízení:',
'l_inHome' => 'Při příchodu',
'l_outHome' => 'Pri odchodu',
'l_sunSet' => 'Západ Slunce',
'l_sunRice' => 'Východ Slunce',
'l_time' => 'Čase',
'l_deviceValue' => 'Hodnotě zařízení',
'l_runAt' => 'Spustit při',
'l_resetAt' => 'Restartovat při',
'l_affectedDevices' => 'Ovlivněná zařízení',
'l_atDays' => 'Ve dny',
'l_read' => 'Číst',
'l_use' => 'Použít',
'l_edit' => 'Upravit',
'l_owner' => 'Vlastník',
'l_member' => 'Člen Domácnosti',
'l_permission' => 'Oprávmnění',
'l_inMinutes' => 'v minutách',
'l_sleepTime' => 'Doba spánku zařízení',
'l_atHome' => 'Doma Jsou',
'l_nameAt' => 'Název',
'l_lastSeen' => 'Naposledy připojeno',
'l_notificationStatus' => 'Notification status',
'l_userName' => 'Uživatelské jméno',
'l_password' => 'Heslo',
'l_oldPassword' => 'Staré Heslo',
'l_newPassword' => 'Nové Heslo',
'l_uploadFirmware' => 'Nahrát Firmware',
'l_userAvatar' => 'Avatar',
'l_userEmail' => 'Email',
'l_roomName' => 'Jméno Místnosti',
//Title
't_createScene' => 'Vytvořit scénu',
't_editScene' => 'Upravit scénu',
't_createAutomation' => 'Vytvořit Automatizaci',
't_addDevice' => 'Přidat Zařízení',
't_editDevice' => 'Upravit Zařízení',
't_pageAfterLogIn' => 'stránka po přihlášení',
't_profile' => 'Profil',
't_notification' => 'Notificatifikace',
't_experimental' => 'Experimental',
't_createuser' => 'Vytvořit Uživatele',
't_changePassword' => 'Změnit Heslo',
't_networkSetting' => 'Nastavení Sítě',
't_deviceVersion' => 'Nastavení Verze',
't_ota' => 'OTA',
't_listUsers' => 'Seznam Uživatelů',
't_avatar' => 'Avatar',
't_listRooms' => 'Seznam Místností',
't_roomName' => 'Jméno Místnosti',
't_createRoom' => 'Vytvořit Místnost',
//constants
'temp' => 'Teplota',
'humi' => 'Vlhkost',
'light' => 'Světlo',
'battery' => 'Baterie',
'on/off' => 'Vypínač',
//words
'w_title' => 'Název',
'w_icon' => 'Ikona',
'w_no' => 'žádná',
'w_noOne' => 'Nikdo',
'w_someOne' => 'Někdo',
'w_room' => 'Místnost',
'w_moduls' => 'Moduly',
'w_home' => 'Doma',
'w_neni' => 'Není',
'w_is' => 'je',
//tables
't_time' => 'Čas',
't_state' => 'Stav',
't_userName' => 'Uživatelské Jméno',
't_action' => 'Akce',
//Days Long
'd_monday' => 'Pondělí',
'd_tuesday' => 'Ůterí',
'd_wednesday' => 'Středa',
'd_thursday' => 'Čtvrtek',
'd_friday' => 'Pátek',
'd_saturday' => 'Sobota',
'd_sunday' => 'Neděle',
//example
'' => '',
];

123
app/lang/en.php Normal file
View File

@ -0,0 +1,123 @@
<?php
return $lang = [
//Menu
'm_home' => 'Home',
'm_dashboard' => 'Dashboard',
'm_settings' => 'Setting',
'm_automatization' => 'Automatization',
'm_scenes' => 'Scenes',
'm_log' => 'Log',
//Buttons
'b_year' => 'Year',
'b_month' => 'Month',
'b_week' => 'Week',
'b_day' => 'Day',
'b_hour' => 'Hour',
'b_next' => 'Next',
'b_create' => 'Create',
'b_edit' => 'Edit',
'b_remove' => 'Remove',
'b_finish' => 'Finish',
'b_approve' => 'Approve',
'b_disable' => 'Disable',
'b_save' => 'Save',
'b_logOut' => 'Logout',
'b_sendTestNotification' => 'Send Test Notification',
'b_rooms' => 'Rooms',
'b_restart' => 'Restart',
'b_disable' => 'disabele',
'b_select' => 'Select',
'b_ota' => 'ota',
//labels
'l_choseDevice' => 'Chose device:',
'l_inHome' => 'When entering',
'l_outHome' => 'When exiting',
'l_sunSet' => 'Sun Set',
'l_sunRice' => 'Sun Rise',
'l_time' => 'Time',
'l_deviceValue' => 'Device Valalue',
'l_runAt' => 'Run at',
'l_resetAt' => 'Reset at',
'l_affectedDevices' => 'Affected devices',
'l_atDays' => 'At days',
'l_read' => 'Read',
'l_use' => 'Use',
'l_edit' => 'Edit',
'l_owner' => 'Owner',
'l_member' => 'Home Member',
'l_permission' => 'Permission',
'l_inMinutes' => 'in minutes',
'l_sleepTime' => 'Device sleep Time',
'l_atHome' => 'At home',
'l_nameAt' => 'Name',
'l_lastSeen' => 'Last Seen',
'l_notificationStatus' => 'Notification status',
'l_userName' => 'Username',
'l_password' => 'Password',
'l_oldPassword' => 'Old Password',
'l_newPassword' => 'New Password',
'l_uploadFirmware' => 'Upload Firmware',
'l_userAvatar' => 'Avatar',
'l_userEmail' => 'Email',
'l_roomName' => 'Room Name',
//Title
't_createScene' => 'Create Scene',
't_editScene' => 'Edit scénu',
't_createAutomation' => 'Create Automation',
't_addDevice' => 'Add Device',
't_editDevice' => 'Edit Device',
't_pageAfterLogIn' => 'Page After Login',
't_profile' => 'Profile',
't_notification' => 'Notification',
't_experimental' => 'Experimental',
't_createuser' => 'Create User',
't_changePassword' => 'Change Password',
't_networkSetting' => 'Network Setting',
't_deviceVersion' => 'Version Setting',
't_ota' => 'OTA',
't_listUsers' => 'User List',
't_avatar' => 'Avatar',
't_listRooms' => 'Room List',
't_roomName' => 'Room Name',
't_createRoom' => 'Create Rom',
//constants
'humi' => 'Humidity',
'temp' => 'Temperature',
'light' => 'Light',
'battery' => 'Batteri',
'on/off' => 'Switch',
//words
'w_title' => 'Name',
'w_icon' => 'Icon',
'w_no' => 'no',
'w_noOne' => 'noone',
'w_someOne' => 'Some',
'w_room' => 'Room',
'w_moduls' => 'Moduls',
'w_home' => 'Home',
'w_neni' => 'At',
'w_is' => 'is',
//tables
't_time' => 'Time',
't_state' => 'State',
't_userName' => 'State',
't_action' => 'Action',
//Days Long
'd_monday' => 'Monday',
'd_tuesday' => 'Tuesday',
'd_wednesday' => 'Wednesday',
'd_thursday' => 'Thursday',
'd_friday' => 'Friday',
'd_saturday' => 'Saturday',
'd_sunday' => 'Sunday',
//example
'' => '',
];

102
app/lang/nl.php Normal file
View File

@ -0,0 +1,102 @@
<?php
return $lang = [
//Menu
'm_home' => 'Home',
'm_dashboard' => 'Controlepaneel',
'm_settings' => 'Instellingen',
'm_automatization' => 'Automatisatie',
'm_scenes' => 'Scénes',
'm_log' => 'Log',
//Buttons
'b_year' => 'Jaar',
'b_month' => 'Maand',
'b_week' => 'Week',
'b_day' => 'Dag',
'b_hour' => 'Uur',
'b_next' => 'Volgende',
'b_create' => 'Maak',
'b_edit' => 'Bewerk',
'b_remove' => 'Verwijder',
'b_approve' => 'Keur goed',
'b_disable' => 'Zet uit',
'b_save' => 'Opslaan',
'b_logOut' => 'Log Uit',
'b_sendTestNotification' => 'Verzend Test Notificatie',
'b_rooms' => 'Kamers',
'b_restart' => 'Herstart',
'b_disable' => 'Zet uit',
'b_select' => 'Selecteer',
//labels
'l_choseDevice' => 'Kies apparaat:',
'l_inHome' => 'Bij het inkomen',
'l_outHome' => 'Bij het buitengaan',
'l_sunSet' => 'Zonsondergang',
'l_sunRice' => 'Zonsopkomst',
'l_time' => 'Tijd',
'l_deviceValue' => 'Apparaat Waarde',
'l_runAt' => 'Voer uit bij',
'l_resetAt' => 'Reset bij',
'l_affectedDevices' => 'Getroffen apparaten',
'l_atDays' => 'Op dagen ',
'l_read' => 'Lees',
'l_use' => 'Gebruik',
'l_edit' => 'Bewerk',
'l_owner' => 'eigenaar',
'l_member' => 'Huis lid',
'l_permission' => 'Permissie',
'l_inMinutes' => 'in minuten',
'l_sleepTime' => 'Apparaat slaaptijd',
'l_atHome' => 'Thuis',
'l_nameAt' => 'Naam',
'l_lastSeen' => 'Laatst gezien',
'l_notificationStatus' => 'Notificatie status',
//Title
't_createScene' => 'Maak scéne',
't_editScene' => 'Bewerk scéne',
't_createAutomation' => 'Maak automatisatie',
't_addDevice' => 'Voeg apparaat toe',
't_editDevice' => 'Bewerk apparaat',
't_pageAfterLogIn' => 'Pagina na Login',
't_profile' => 'Profiel',
't_notification' => 'Notificatie',
't_experimental' => 'experimenteel',
//constants
'humi' => 'Vochtigheid',
'temp' => 'Temperatuur',
'light' => 'Licht',
'battery' => 'Batterij',
'on/off' => 'Schakelaar',
//words
'w_title' => 'Naam',
'w_icon' => 'Icoon',
'w_no' => 'nee',
'w_noOne' => 'niemand',
'w_someOne' => 'Sommige',
'w_room' => 'Kamer',
'w_moduls' => 'Modules',
'w_home' => 'Huis',
'w_neni' => 'Bij',
'w_is' => 'is',
//tables
't_time' => 'Tijd',
't_state' => 'Status',
//Days Long
'd_monday' => 'Maandag',
'd_tuesday' => 'Dinsdag',
'd_wednesday' => 'Woensdag',
'd_thursday' => 'Donderdag',
'd_friday' => 'Vrijdag',
'd_saturday' => 'Zaterdag',
'd_sunday' => 'Zondag',
//example
'' => '',
];

110
app/lang/pl.php Normal file
View File

@ -0,0 +1,110 @@
<?php
return $lang = [
//Menu
'm_home' => 'Strona główna',
'm_dashboard' => 'Panel urządzeń',
'm_settings' => 'Ustawienia',
'm_automatization' => 'Zaplanowane działania',
'm_scenes' => 'Scenariusze',
'm_log' => 'Logi',
//Buttons
'b_year' => 'Rok',
'b_month' => 'Miesiąc',
'b_week' => 'Tydzień',
'b_day' => 'Dzień',
'b_hour' => 'Godzina',
'b_next' => 'Dalej',
'b_create' => 'Utwórz',
'b_edit' => 'Edytuj',
'b_remove' => 'Usuń',
'b_finish' => 'Dokončit', //newOne
'b_approve' => 'Zaakceptuj',
'b_disable' => 'Wyłącz',
'b_save' => 'Zapisz',
'b_logOut' => 'Wyloguj',
'b_sendTestNotification' => 'Wyślij próbne powiadomienie',
'b_rooms' => 'Pokoje',
'b_restart' => 'Zrestartuj',
'b_disable' => 'Wyłącz',
'b_select' => 'Wybierz',
//labels
'l_choseDevice' => 'Wybierz urządzenie:',
'l_inHome' => 'Przy wchodzeniu',
'l_outHome' => 'Przy wychodzeniu',
'l_sunSet' => 'Zachodzie słońca',
'l_sunRice' => 'Zschodzie słońca',
'l_time' => 'O określonym czasie',
'l_deviceValue' => 'Przy wartości urządzenia',
'l_runAt' => 'Uruchom o',
'l_resetAt' => 'Resetuj o',
'l_affectedDevices' => 'Ma wpływ na urządzenia',
'l_atDays' => 'W dni',
'l_read' => 'Odczytywanie',
'l_use' => 'Używanie',
'l_edit' => 'Edytowanie',
'l_owner' => 'Właściciel',
'l_member' => 'Domownik',
'l_permission' => 'Uprawnienia',
'l_inMinutes' => 'w minutach',
'l_sleepTime' => 'Czas snu urządzenia',
'l_atHome' => 'W domu',
'l_nameAt' => 'Nazwa',
'l_lastSeen' => 'Ostatnio zaktualizowany',
'l_notificationStatus' => 'Stan powiadomienia',
'l_userName' => 'Username', //newOne
'l_password' => 'Password', //newOne
'l_oldPassword' => 'Old Password', //newOne
'l_newPassword' => 'New Password', //newOne
//Title
't_createScene' => 'Utwórz scenariusz',
't_editScene' => 'Edytuj scenariusz',
't_createAutomation' => 'Utwórz automację',
't_addDevice' => 'Dodaj Urządzenie',
't_editDevice' => 'Edutuj urządzenie',
't_pageAfterLogIn' => 'Strona Po Zalogowaniu',
't_profile' => 'Profil',
't_notification' => 'Powiadomienie',
't_experimental' => 'Eksperymentalne',
't_createuser' => 'Vytvořit Uživatele', //newOne
't_changePassword' => 'Změnit Heslo', //newOne
//constants
'humi' => 'Wilgotność',
'temp' => 'Temperatura',
'light' => 'Światło',
'battery' => 'Bateria',
'on/off' => 'Przełącznik',
//words
'w_title' => 'Nazwa',
'w_icon' => 'ikony',
'w_no' => 'Brak',
'w_noOne' => 'nikt',
'w_someOne' => 'Ktoś',
'w_room' => 'Pokój',
'w_moduls' => 'Moduły',
'w_home' => 'Dom',
'w_neni' => 'W',
'w_is' => 'jest',
//tables
't_time' => 'Czas',
't_state' => 'Stan',
't_userName' => 'State', //newOne
't_action' => 'Action', //newOne
//Days Long
'd_monday' => 'Poniedziałek',
'd_tuesday' => 'Wtorek',
'd_wednesday' => 'Środa',
'd_thursday' => 'Czwartek',
'd_friday' => 'Piątek',
'd_saturday' => 'Sobota',
'd_sunday' => 'Niedziela',
//example
'' => '',
];

View File

@ -0,0 +1,69 @@
.button{
background-color: $secondary-color;
border: 0;
border-radius: $control-border-radius;
color: $base-font-color;
padding: $control-padding-y $control-padding-x;
transition: background-color .15s;
height: 2.5rem;
display: inline-block;
line-height: 1.5;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
text-decoration: none;
&:hover{
color: $base-font-color;
background-color: $secondary-color-dark;
}
&:active{
background-color: $secondary-color-dark;
}
&:focus{
box-shadow: 0 0 3px $control-focus-color;
}
}
.button.is-small{
padding: $control-padding-y $control-padding-x/1.5;
height: 2rem;
font-size: .875rem;
}
.button.is-large{
height: 3rem;
font-size: 1.25rem;
}
.buttons .button{
margin-right: .25rem;
margin-bottom: .25rem;
}
.button.is-primary{
background-color: $primary-color;
color: white;
&:hover{
color: white;
background-color: $primary-color-dark;
}
&:active{
background-color: $primary-color-dark;
}
}
.button.is-danger{
background-color: map-get($red-colors , '100');
color: map-get($red-colors , '500');
&:hover{
background-color: map-get($red-colors , '200');
color: map-get($red-colors , '600');
}
&:active{
background-color: map-get($red-colors , '200');
color: map-get($red-colors , '600');
}
}

View File

@ -0,0 +1,66 @@
<!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">
<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->render();
?>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

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

2966
app/templates/css/main.css Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,28 @@
.modal-container-hiden {
display: none !important;
}
#modal:target {
display: flex;
}
#modal2:target {
display: flex;
}
#modal3:target {
display: flex;
}
#modal4:target {
display: flex;
}
@media (max-width: 767px){
.modal>.overflow {
height: calc(100% - 44px);
overflow-y: scroll;
overflow-x: hidden;
}
}

View File

@ -0,0 +1,21 @@
table.table td, table.table th {
border: 2px solid #121a2b;
padding: 8px;
}
/*tr:nth-child(even){background-color: #f2f2f2;}*/
table.table tr:hover {background-color: #121a2b;}
table.table th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #121a2b;
color: white;
}
button:disabled,
button[disabled] {
opacity: .4;
}

17
app/templates/css/pre.css Normal file
View File

@ -0,0 +1,17 @@
pre{
border-radius: 3px;
border: 0px solid transparent;
color: #d4def7;
padding: 0.5em 0.8em;
line-height: 1.5;
background: #121a2b;
width: 100%;
display: block;
}
.rectangle-content{
width: 100%;
background: linear-gradient(135deg, rgba(116, 34, 189, 0.5), rgba(185, 19, 121, 0.5));
border-radius: 8px;
padding: .25rem !important;
}

View File

@ -0,0 +1,67 @@
<!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">
<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', 'dashboard');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>
<div class="col-md-9 main-body">
<a onClick="$('#modal').removeClass('modal-container-hiden').show();" class="button is-primary m-1"><?php $LANGMNG->echo('t_addDevice'); ?></a>
<div class="row no-gutters">
<?php foreach ($DASHBOARD as $dashboardItemId => $dashboardItemData) {
$partialDeviceButton = new Partial('dashboardButton');
$partialDeviceButton->prepare('dashboardItemData', $dashboardItemData);
$partialDeviceButton->render();
} ?>
</div>
</div>
</div>
<div class="modal-container modal-container-hiden" id="modal">
<div class="modal">
<div class="close">
<i class="fa fa-times"></i>
</div>
<h4 class="mb-4"><?php $LANGMNG->echo('t_addDevice'); ?></h4>
<form method="post">
<div class="field px-2">
<div class="label"><?php $LANGMNG->echo('l_choseDevice'); ?>:</div>
<select class="input" name="devices[]" multiple required>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){ ?>
<option value="<?php echo $subDeviceKey; ?>"><?php echo $subDeviceValue['name'] . '[' . $subDeviceValue['type'] . ']'; ?></option>
<?php } ?>
</select>
</div>
<input type="submit" class="button" name="modalFinal" value="<?php $LANGMNG->echo('b_create'); ?>"/>
</form>
</div>
</div>
<?php
if (isset($_POST['deviceId'])) {
$partial = new Partial('deviceEdit');
$partial->prepare('DEVICEDATA', $DEVICEDATA);
$partial->render();
}
$partial = new Partial('footer');
$partial->render();
?>
</body>
</html>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 434 KiB

Binary file not shown.

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