function _pwa_webpush_subscription_POST in Progressive Web App 7.2
Parameters
$endpoint_sha256:
$uid:
$out:
Return value
mixed
File
- modules/
pwa_webpush/ pwa_webpush.pages.inc, line 72
Code
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;
}
// check that the sha256 matches between front and backend.
if (hash('sha256', $data['sub']['endpoint']) !== $endpoint_sha256) {
$out['status'] = 'error';
$out['error'] = 'SHA is not valid for this endpoint';
return $out;
}
// Check that the subscription doesn't exists already (especially useful for
// anonymous users). Returns the same format as an insertion to keep the
// frontend code working.
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,
// For unicity.
'endpoint_sha256' => $endpoint_sha256,
'json' => drupal_json_encode($data['sub']),
];
// Wrap in a try/catch in case there is an SQL error.
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;
}