<?php
require_once dirname(__DIR__,2).'/vendor/autoload.php';
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
function sendPushToAll(string $title,string $body,?string $url=null,string $permissionKey='faxalarm'){
global $permissions;
if(!defined('PUSH_SUBJECT')||!defined('PUSH_PUBLIC_KEY')||!defined('PUSH_PRIVATE_KEY'))return false;
if(!isset($permissions[$permissionKey]))return false;
$basePath=realpath(__DIR__.'/../../');
$file=$basePath.'/data/push/subscription.json';
if(!file_exists($file))return false;
$list=json_decode(file_get_contents($file),true);
if(!is_array($list)||empty($list))return false;
$auth=['VAPID'=>['subject'=>PUSH_SUBJECT,'publicKey'=>PUSH_PUBLIC_KEY,'privateKey'=>PUSH_PRIVATE_KEY]];
$webPush=new WebPush($auth);
$payload=json_encode(['title'=>$title,'body'=>$body,'url'=>$url?:'/'],JSON_UNESCAPED_UNICODE);
$map=[];$successCount=0;
foreach($list as $sub){
if(is_string($sub))$sub=json_decode($sub,true);
if(!isset($sub['endpoint'],$sub['role'],$sub['user_id']))continue;
$role=$sub['role'];
if(!isset($permissions[$permissionKey][$role])||$permissions[$permissionKey][$role]!=='on')continue;
try{$subscription=Subscription::create($sub);$webPush->queueNotification($subscription,$payload);$map[$sub['endpoint']]=$sub;}catch(\Throwable $e){}
}
foreach($webPush->flush() as $report){
$endpoint=(string)$report->getRequest()->getUri();
if($report->isSuccess()){$successCount++;continue;}
if($report->isSubscriptionExpired())unset($map[$endpoint]);
}
file_put_contents($file,json_encode(array_values($map),JSON_UNESCAPED_UNICODE),LOCK_EX);
return $successCount>0;
}
function sendPushToUser(string $userId,string $title,string $body,?string $url=null){
if(!defined('PUSH_SUBJECT')||!defined('PUSH_PUBLIC_KEY')||!defined('PUSH_PRIVATE_KEY'))return false;
$basePath=realpath(__DIR__.'/../../');
$file=$basePath.'/data/push/subscription.json';
if(!file_exists($file))return false;
$list=json_decode(file_get_contents($file),true);
if(!is_array($list)||empty($list))return false;
$auth=['VAPID'=>['subject'=>PUSH_SUBJECT,'publicKey'=>PUSH_PUBLIC_KEY,'privateKey'=>PUSH_PRIVATE_KEY]];
$webPush=new WebPush($auth);
$payload=json_encode(['title'=>$title,'body'=>$body,'url'=>$url?:'/'],JSON_UNESCAPED_UNICODE);
$success=false;
foreach($list as $sub){
if(is_string($sub))$sub=json_decode($sub,true);
if(!isset($sub['endpoint'],$sub['user_id'])||$sub['user_id']!==$userId)continue;
try{$subscription=Subscription::create($sub);$webPush->queueNotification($subscription,$payload);}catch(\Throwable $e){}
}
foreach($webPush->flush() as $report){if($report->isSuccess())$success=true;}
return $success;
}
