70 lines
1.8 KiB
PHP
70 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace com\fwdekker\deathnotifier;
|
|
|
|
use Exception;
|
|
|
|
|
|
/**
|
|
* Helper functions.
|
|
*/
|
|
class Util
|
|
{
|
|
/**
|
|
* Parses POST values from JSON-based inputs.
|
|
*
|
|
* @return array<int|string, mixed>|null the parsed POST-ed values
|
|
*/
|
|
static function parse_post(): ?array
|
|
{
|
|
$output = $_POST;
|
|
|
|
$post_input = file_get_contents("php://input");
|
|
if ($post_input !== false)
|
|
$output = json_decode($post_input, associative: true);
|
|
|
|
return $output;
|
|
}
|
|
|
|
/**
|
|
* Parses `$argv` into an array, similar to `$_GET`.
|
|
*
|
|
* Code from https://www.php.net/manual/en/features.commandline.php#108883.
|
|
*
|
|
* @return array<int|string, mixed> the parsed CLI inputs
|
|
*/
|
|
static function parse_cli(): array
|
|
{
|
|
parse_str(implode("&", array_slice($_SERVER["argv"], 1)), $output);
|
|
|
|
return $output;
|
|
}
|
|
|
|
|
|
/**
|
|
* Generates an appropriate CSRF token.
|
|
*
|
|
* @return string the generated CSRF token
|
|
* @throws Exception if the CSRF token could not be generated
|
|
*/
|
|
static function generate_csrf_token(): string
|
|
{
|
|
return bin2hex(random_bytes(32));
|
|
}
|
|
|
|
|
|
/**
|
|
* Returns the number of minutes until `timestamp` was `interval` minutes ago.
|
|
*
|
|
* For example, if `timestamp` was 5 minutes ago, and `interval` is 7, then this function returns 2.
|
|
*
|
|
* @param string $timestamp the timestamp at which some event occurred
|
|
* @param int $interval the number of minutes to measure against
|
|
* @return int the number of minutes until `timestamp` was `interval` minutes ago
|
|
*/
|
|
static function minutes_until_interval_elapsed(string $timestamp, int $interval): int
|
|
{
|
|
return $interval - ((time() - intval($timestamp)) / 60);
|
|
}
|
|
}
|