Manager Duplication Clean Up

This commit is contained in:
JonatanRek 2020-05-16 22:05:11 +02:00
parent 090b9f7a7b
commit 87c719e9e6
15 changed files with 4 additions and 1181 deletions

View File

@ -1,45 +0,0 @@
<?php
class AuthManager {
public function getToken($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;
}
public function deleteToken($token){
Db::command ('DELETE FROM tokens WHERE token=?', array ($token));
return true;
}
public function validateToken($token){
$tokens = Db::loadAll('SELECT * FROM tokens WHERE token = ? AND expire >= CURRENT_TIMESTAMP AND blocked = 0;', array($token));
if (count($tokens) == 1) {
return true;
} else if (count($tokens) == 0) {
return false;
};
return false;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -69,6 +69,7 @@ class GoogleHome {
}
if ($waiting < $executed){
$status = "PENDING";
$online = true;
}
}
@ -84,9 +85,9 @@ class GoogleHome {
$tempDevice[$deviceId['id']]['thermostatMode'] = 'off';
if (RecordManager::getLastRecord($deviceId['id'])['value'] != 0) {
$tempDevice[$deviceId['id']]['thermostatMode'] = 'heat';
}
$tempDevice[$deviceId['id']]['thermostatTemperatureAmbient'] = RecordManager::getLastRecord($deviceId['id'])['value'];
$tempDevice[$deviceId['id']]['thermostatTemperatureSetpoint'] = RecordManager::getLastRecord($deviceId['id'])['value'];
}
} else {
$tempDevice[$deviceId['id']]['on'] = $state;
}
@ -201,6 +202,7 @@ class GoogleHome {
}
if ($waiting < $executed){
$status = "PENDING";
$status = "SUCCESS";
} else {
$status = "OFFLINE";
}
@ -215,10 +217,6 @@ class GoogleHome {
//ambient z dalšího zenzoru v roomu
],
];
if ($timeout >= 5){
$commandTemp['status'] = "OFFLINE";
}
return $commandTemp;
}
@ -236,7 +234,7 @@ class GoogleHome {
$executed = 0;
$waiting = 0;
foreach (RecordManager::getLastRecord($deviceId['id'], 4) as $key => $value) {
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
if ($value['execuded'] == 1){
$executed++;
} else {

View File

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

View File

@ -1,57 +0,0 @@
<?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('../logs/');
foreach ($logFiles as $key => $file) {
if (in_array($file,array(".","..", ".gitkeep", $todayFileName)))
{
continue;
}
if (filemtime($file) > $seconds) {
unlink('../logs/'.$file);
}
}
}
}
class LogManager
{
private $logFile;
function __construct($fileName = "")
{
if ($fileName == ""){
$fileName = '../logs/'. date("Y-m-d").'.log';
}
if(!is_dir("../logs/"))
{
mkdir("../logs/");
}
$this->logFile = fopen($fileName, "a") or die("Unable to open file!");
}
function write($value, $type = LogRecordType::ERROR){
$record = "[".date("H:m:s")."][".$type."]" . $value . "\n";
fwrite($this->logFile, $record);
}
function __destruct(){
if (isset($this->logFile)) {
fclose($this->logFile);
}
}
}

View File

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

View File

@ -1,107 +0,0 @@
<?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"] = $body;
$this->jsonPayload["data"]["notification"]["icon"] = $icon;
$this->jsonPayload["data"]["notification"]["click_action"] = $action;
}
function send(){
$data = json_encode($this->jsonPayload);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$this->server_key,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result === FALSE) {
die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
}

View File

@ -1,106 +0,0 @@
<?php
class RecordManager{
public static $records;
public static function createWithSubId ($subDeviceId, $value) {
try {
$record = [
'execuded' => 1,
];
Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
$record = array (
'subdevice_id' => $subDeviceId,
'value' => $value,
);
return Db::add ('records', $record);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function create ($deviceId, $type, $value) {
$subDeviceId = Db::loadOne('SELECT * FROM subdevices WHERE device_id = ? AND type = ?;', array($deviceId, $type))['subdevice_id'];
if ($subDeviceId == '') {
return false;
};
try {
$record = [
'execuded' => 1,
];
Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
$record = array (
'subdevice_id' => $subDeviceId,
'value' => $value,
);
return Db::add ('records', $record);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function setExecuted($recordId) {
try {
Db::edit ('records', ['execuded' => 1], 'WHERE record_id = ?', array($recordId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getRecordById($recordId) {
return Db::loadOne('SELECT * FROM records WHERE record_id = ?;', array($recordId));
}
public static function getLastInsertedRecordId() {
return Db::insertId();
}
public static function getLastRecord($subDeviceId, $num = 1) {
if ($num == 1)
return Db::loadOne('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC;', array($subDeviceId, 999));
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC LIMIT ?;', array($subDeviceId, 999, $num));
}
public static function getLastRecordNotNull($subDeviceId) {
return Db::loadOne('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC;', array($subDeviceId, 0));
}
public static function getAllRecord($subDeviceId, $timeFrom, $timeTo) {
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND time >= ? AND time <= ? AND value != ? ORDER BY time;', array($subDeviceId, $timeFrom, $timeTo, 999));
}
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));
}
}
?>

View File

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

View File

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

View File

@ -1,210 +0,0 @@
<?php
class UserManager
{
public static 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 static function getUser ($userName) {
try {
$user = Db::loadOne ("SELECT * FROM users WHERE username = ?", [$userName]);
return $user;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getUserId ($userId) {
try {
$user = Db::loadOne ("SELECT * FROM users WHERE user_id = ?", [$userId]);
return $user;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function getAvatarUrl($userId = null){
$email = self::getUserData('email');
if ($userId != null){
$email = self::getUserData('email',$userId);
}
return 'https://secure.gravatar.com/avatar/' . md5( strtolower( trim( $email ) ) );
}
public static function login ($username, $password, $rememberMe) {
try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
if ($user['password'] == UserManager::getHashPassword($password)) {
if (isset($rememberMe) && $rememberMe == 'true') {
setcookie ("rememberMe", self::setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
}
$_SESSION['user']['id'] = $user['user_id'];
$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 static 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 static function isLogin () {
if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) {
return true;
} else {
if (isset ($_COOKIE['rememberMe'])){
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array (self::getDecryptedCookie($_COOKIE['rememberMe'])))) {
$_SESSION['user']['id'] = $user['user_id'];
return true;
}
}
}
return false;
}
public static function logout () {
unset($_SESSION['user']);
session_destroy();
if (isset($_COOKIE['rememberMe'])){
unset($_COOKIE['rememberMe']);
setcookie("rememberMe", 'false', time(), BASEDIR, $_SERVER['HTTP_HOST']);
}
}
public static function setEncryptedCookie($value){
$first_key = base64_decode(FIRSTKEY);
$second_key = base64_decode(SECONDKEY);
$method = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivlen);
$newvalue_raw = openssl_encrypt($value, $method, $first_key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $newvalue_raw, $second_key, TRUE);
$newvalue = base64_encode ($iv.$hmac.$newvalue_raw);
return $newvalue;
}
public static function getDecryptedCookie($value){
$first_key = base64_decode(FIRSTKEY);
$second_key = base64_decode(SECONDKEY);
$c = base64_decode($value);
$method = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($method);
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, 32);
$newValue_raw = substr($c, $ivlen+32);
$newValue = openssl_decrypt($newValue_raw, $method, $first_key, OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $newValue_raw, $second_key, TRUE);
if (hash_equals ($hmac, $calcmac)) {
return $newValue;
}
return false;
}
public static function getUserData ($type, $userId = '') {
if ($userId == '') {
$userId = $_SESSION['user']['id'];
}
$user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($userId));
return $user[$type];
}
public static function setUserData ($type, $value) {
if (isset ($_SESSION['user']['id'])) {
Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $_SESSION['user']['id']));
}
}
public static function getHashPassword ($password) {
$salt = "s0mRIdlKvI";
$hashPassword = hash('sha512', ($password . $salt));
return $hashPassword;
}
public static function atHome($userId, $atHome){
try {
Db::edit ('users', ['at_home' => $atHome], 'WHERE user_id = ?', array($userId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function changePassword($oldPassword, $newPassword, $newPassword2){
if ($newPassword == $newPassword2) {
//Password Criteria
$oldPasswordSaved = self::getUserData('password');
if (self::getHashPassword($oldPassword) == $oldPasswordSaved) {
self::setUserData('password', self::getHashPassword($newPassword));
} else {
throw new Exception ("old password did not match");
}
} else {
throw new Exception ("new password arent same");
}
}
public static function createUser($userName, $password){
$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 static function haveOtaEnabled($userName){
$ota = self::getUser($userName)['ota'];
if ($ota != ''){
return ($ota != '' ? $ota : false);
} else {
return false;
}
}
}
?>

View File

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