View source
<?php
function pwa_webpush_register($endpoint_sha256) {
$out = [
'status' => 'ok',
];
$uid = $GLOBALS['user']->uid;
$function = '_pwa_webpush_subscription_' . $_SERVER['REQUEST_METHOD'];
if (function_exists($function)) {
$function($endpoint_sha256, $uid, $out);
}
else {
$out['status'] = 'error';
$out['error'] = 'HTTP Method ' . $_SERVER['REQUEST_METHOD'] . ' not supported';
}
return $out;
}
function _pwa_webpush_subscription_exists($endpoint_sha256, $uid) {
$sub = db_query('SELECT * FROM {pwa_webpush_subscription} WHERE endpoint_sha256 = :sha AND uid = :uid', [
':sha' => $endpoint_sha256,
':uid' => $uid,
])
->fetchObject();
return $sub;
}
function _pwa_webpush_subscription_DELETE($endpoint_sha256, $uid, &$out) {
if ($sub = _pwa_webpush_subscription_exists($endpoint_sha256, $uid)) {
db_merge('pwa_webpush_subscription')
->key([
'uid' => $uid,
'endpoint_sha256' => $endpoint_sha256,
])
->fields([
'expired' => REQUEST_TIME,
])
->execute();
$out['sid'] = $sub->sid;
$out['action'] = 'remove';
return $out;
}
else {
drupal_add_http_header('Status', '400 Bad Request');
$out['status'] = 'error';
$out['error'] = 'Subscription "' . $endpoint_sha256 . '" missing for user ' . $uid;
return $out;
}
}
function _pwa_webpush_subscription_POST($endpoint_sha256, $uid, &$out) {
$json = file_get_contents('php://input');
$data = drupal_json_decode($json);
if (empty($json) || empty($data['sub']) || empty($data['sub']['endpoint'])) {
drupal_add_http_header('Status', '400 Bad Request');
$out['status'] = 'error';
$out['error'] = 'Required parameters missing';
return $out;
}
if (hash('sha256', $data['sub']['endpoint']) !== $endpoint_sha256) {
$out['status'] = 'error';
$out['error'] = 'SHA is not valid for this endpoint';
return $out;
}
if ($sub = _pwa_webpush_subscription_exists($endpoint_sha256, $uid)) {
$out['sid'] = $sub->sid;
$out['saved'] = $sub;
$out['action'] = 'add';
return $out;
}
$save = [
'uid' => $uid,
'created' => REQUEST_TIME,
'last_used' => 0,
'expired' => 0,
'endpoint_sha256' => $endpoint_sha256,
'json' => drupal_json_encode($data['sub']),
];
try {
$query = db_insert('pwa_webpush_subscription')
->fields($save)
->execute();
if (!$query) {
drupal_add_http_header('Status', '500 Server error');
$out['status'] = 'error';
$out['error'] = 'Could not save the subscription to the database';
}
else {
$out['sid'] = $query;
$out['saved'] = [
'sid' => $query,
] + $save;
$out['action'] = 'add';
}
} catch (Exception $exception) {
drupal_add_http_header('Status', '500 Server error');
$out['status'] = 'exception';
$out['exception'] = $exception
->getMessage();
}
return $out;
}