PHP_SMART_HOME_V3/app/models/managers/NotificationManager.php

108 lines
2.6 KiB
PHP
Raw Normal View History

2020-05-16 15:18:27 +00:00
<?php
/**
* Notification Manager
*/
2020-06-23 18:25:42 +00:00
//TODO: Working timestamp to $title
2020-05-16 15:18:27 +00:00
class NotificationManager
{
2020-07-29 06:35:00 +00:00
public static function addSubscriber($userID = '', $token = ''){
2020-05-16 15:18:27 +00:00
$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);
}
}
2020-07-29 06:35:00 +00:00
public static function getSubscription () {
2020-05-16 15:18:27 +00:00
return Db::loadAll ("SELECT * FROM notifications");
}
2020-07-29 06:35:00 +00:00
public static function sendSimpleNotification(string $serverKey, string $to, array $data, bool $timeStamp = false){
2020-05-16 15:18:27 +00:00
$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);
2020-05-20 07:11:49 +00:00
$notification->notification($data['title'], date("h:i") . " - " . $data['body'], $data['icon'], '');
2020-05-16 15:18:27 +00:00
$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;
2020-05-20 07:14:15 +00:00
$this->jsonPayload["data"]["notification"]["body"] = $body;
2020-05-16 15:18:27 +00:00
$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;
}
}