From 87c719e9e6ff447bae5490c176b7dfe1ccd96673 Mon Sep 17 00:00:00 2001 From: JonatanRek Date: Sat, 16 May 2020 22:05:11 +0200 Subject: [PATCH] Manager Duplication Clean Up --- app/models/AuthManager.php | 45 ------- app/models/AutomationManager.php | 175 ------------------------ app/models/DashboardManager.php | 41 ------ app/models/DeviceManager.php | 96 ------------- app/models/FallbackManager.php | 44 ------ app/models/GoogleHome.php | 10 +- app/models/LanguageManager.php | 60 --------- app/models/LogManager.php | 57 -------- app/models/NetworkManager.php | 18 --- app/models/NotificationManager.php | 107 --------------- app/models/RecordManager.php | 106 --------------- app/models/RoomManager.php | 31 ----- app/models/SceneManager.php | 41 ------ app/models/UserManager.php | 210 ----------------------------- app/models/managers/Utilities.php | 144 -------------------- 15 files changed, 4 insertions(+), 1181 deletions(-) delete mode 100644 app/models/AuthManager.php delete mode 100644 app/models/AutomationManager.php delete mode 100644 app/models/DashboardManager.php delete mode 100644 app/models/DeviceManager.php delete mode 100644 app/models/FallbackManager.php delete mode 100644 app/models/LanguageManager.php delete mode 100644 app/models/LogManager.php delete mode 100644 app/models/NetworkManager.php delete mode 100644 app/models/NotificationManager.php delete mode 100644 app/models/RecordManager.php delete mode 100644 app/models/RoomManager.php delete mode 100644 app/models/SceneManager.php delete mode 100644 app/models/UserManager.php delete mode 100644 app/models/managers/Utilities.php diff --git a/app/models/AuthManager.php b/app/models/AuthManager.php deleted file mode 100644 index 88c96a6..0000000 --- a/app/models/AuthManager.php +++ /dev/null @@ -1,45 +0,0 @@ -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; - } -} diff --git a/app/models/AutomationManager.php b/app/models/AutomationManager.php deleted file mode 100644 index aacf6f7..0000000 --- a/app/models/AutomationManager.php +++ /dev/null @@ -1,175 +0,0 @@ - $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'])); - } - } - } - } -} diff --git a/app/models/DashboardManager.php b/app/models/DashboardManager.php deleted file mode 100644 index b241a35..0000000 --- a/app/models/DashboardManager.php +++ /dev/null @@ -1,41 +0,0 @@ - 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)); - } -} diff --git a/app/models/DeviceManager.php b/app/models/DeviceManager.php deleted file mode 100644 index 53255f8..0000000 --- a/app/models/DeviceManager.php +++ /dev/null @@ -1,96 +0,0 @@ - $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 má 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); - } -} -?> diff --git a/app/models/FallbackManager.php b/app/models/FallbackManager.php deleted file mode 100644 index cb3fb79..0000000 --- a/app/models/FallbackManager.php +++ /dev/null @@ -1,44 +0,0 @@ -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"]); - } - } - } - } -} diff --git a/app/models/GoogleHome.php b/app/models/GoogleHome.php index 8882be9..9d66421 100644 --- a/app/models/GoogleHome.php +++ b/app/models/GoogleHome.php @@ -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 { diff --git a/app/models/LanguageManager.php b/app/models/LanguageManager.php deleted file mode 100644 index 507bd88..0000000 --- a/app/models/LanguageManager.php +++ /dev/null @@ -1,60 +0,0 @@ -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; - } -} diff --git a/app/models/LogManager.php b/app/models/LogManager.php deleted file mode 100644 index dde1c14..0000000 --- a/app/models/LogManager.php +++ /dev/null @@ -1,57 +0,0 @@ - $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); - } - } -} diff --git a/app/models/NetworkManager.php b/app/models/NetworkManager.php deleted file mode 100644 index 247e0df..0000000 --- a/app/models/NetworkManager.php +++ /dev/null @@ -1,18 +0,0 @@ - $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; - } -} diff --git a/app/models/RecordManager.php b/app/models/RecordManager.php deleted file mode 100644 index 143b6a2..0000000 --- a/app/models/RecordManager.php +++ /dev/null @@ -1,106 +0,0 @@ - 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)); - } -} -?> diff --git a/app/models/RoomManager.php b/app/models/RoomManager.php deleted file mode 100644 index 928b829..0000000 --- a/app/models/RoomManager.php +++ /dev/null @@ -1,31 +0,0 @@ - $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)); - } -} -?> diff --git a/app/models/SceneManager.php b/app/models/SceneManager.php deleted file mode 100644 index 2cd7fb8..0000000 --- a/app/models/SceneManager.php +++ /dev/null @@ -1,41 +0,0 @@ - $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)); - } -} -?> diff --git a/app/models/UserManager.php b/app/models/UserManager.php deleted file mode 100644 index 05fd3ef..0000000 --- a/app/models/UserManager.php +++ /dev/null @@ -1,210 +0,0 @@ -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; - } - } -} -?> diff --git a/app/models/managers/Utilities.php b/app/models/managers/Utilities.php deleted file mode 100644 index 32b66af..0000000 --- a/app/models/managers/Utilities.php +++ /dev/null @@ -1,144 +0,0 @@ - '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 - } -}