init
This commit is contained in:
234
kirby/src/Http/Cookie.php
Normal file
234
kirby/src/Http/Cookie.php
Normal file
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* The `Cookie` class helps you to
|
||||
* handle cookies in your projects.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Cookie
|
||||
{
|
||||
/**
|
||||
* Key to use for cookie signing
|
||||
*/
|
||||
public static string $key = 'KirbyHttpCookieKey';
|
||||
|
||||
/**
|
||||
* Set a new cookie
|
||||
*
|
||||
* <code>
|
||||
*
|
||||
* cookie::set('mycookie', 'hello', ['lifetime' => 60]);
|
||||
* // expires in 1 hour
|
||||
*
|
||||
* </code>
|
||||
*
|
||||
* @param string $key The name of the cookie
|
||||
* @param string $value The cookie content
|
||||
* @param array $options Array of options:
|
||||
* lifetime, path, domain, secure, httpOnly, sameSite
|
||||
* @return bool true: cookie was created,
|
||||
* false: cookie creation failed
|
||||
*/
|
||||
public static function set(
|
||||
string $key,
|
||||
string $value,
|
||||
array $options = []
|
||||
): bool {
|
||||
// modify CMS caching behavior
|
||||
static::trackUsage($key);
|
||||
|
||||
// extract options
|
||||
$expires = static::lifetime($options['lifetime'] ?? 0);
|
||||
$path = $options['path'] ?? '/';
|
||||
$domain = $options['domain'] ?? null;
|
||||
$secure = $options['secure'] ?? false;
|
||||
$httponly = $options['httpOnly'] ?? true;
|
||||
$samesite = $options['sameSite'] ?? 'Lax';
|
||||
|
||||
// add an HMAC signature of the value
|
||||
$value = static::hmac($value) . '+' . $value;
|
||||
|
||||
// store that thing in the cookie global
|
||||
$_COOKIE[$key] = $value;
|
||||
|
||||
// store the cookie
|
||||
return setcookie(
|
||||
$key,
|
||||
$value,
|
||||
compact('expires', 'path', 'domain', 'secure', 'httponly', 'samesite')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the lifetime for a cookie
|
||||
*
|
||||
* @param int $minutes Number of minutes or timestamp
|
||||
*/
|
||||
public static function lifetime(int $minutes): int
|
||||
{
|
||||
// absolute timestamp
|
||||
if ($minutes > 1000000000) {
|
||||
return $minutes;
|
||||
}
|
||||
|
||||
// minutes from now
|
||||
if ($minutes > 0) {
|
||||
return time() + ($minutes * 60);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a cookie forever
|
||||
*
|
||||
* <code>
|
||||
*
|
||||
* cookie::forever('mycookie', 'hello');
|
||||
* // never expires
|
||||
*
|
||||
* </code>
|
||||
*
|
||||
* @param string $key The name of the cookie
|
||||
* @param string $value The cookie content
|
||||
* @param array $options Array of options:
|
||||
* path, domain, secure, httpOnly
|
||||
* @return bool true: cookie was created,
|
||||
* false: cookie creation failed
|
||||
*/
|
||||
public static function forever(
|
||||
string $key,
|
||||
string $value,
|
||||
array $options = []
|
||||
): bool {
|
||||
// 9999-12-31 if supported (lower on 32-bit servers)
|
||||
$options['lifetime'] = min(253402214400, PHP_INT_MAX);
|
||||
return static::set($key, $value, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a cookie value
|
||||
*
|
||||
* <code>
|
||||
* cookie::get('mycookie', 'peter');
|
||||
* // sample output: 'hello' or if the cookie is not set 'peter'
|
||||
* </code>
|
||||
*
|
||||
* @param string|null $key The name of the cookie
|
||||
* @param string|null $default The default value, which should be returned
|
||||
* if the cookie has not been found
|
||||
* @return string|array|null The found value
|
||||
*/
|
||||
public static function get(
|
||||
string|null $key = null,
|
||||
string|null $default = null
|
||||
): string|array|null {
|
||||
if ($key === null) {
|
||||
return $_COOKIE;
|
||||
}
|
||||
|
||||
// modify CMS caching behavior
|
||||
static::trackUsage($key);
|
||||
|
||||
if ($value = $_COOKIE[$key] ?? null) {
|
||||
return static::parse($value);
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a cookie exists
|
||||
*/
|
||||
public static function exists(string $key): bool
|
||||
{
|
||||
return static::get($key) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a HMAC for the cookie value
|
||||
* Used as a cookie signature to prevent easy tampering with cookie data
|
||||
*/
|
||||
protected static function hmac(string $value): string
|
||||
{
|
||||
return hash_hmac('sha1', $value, static::$key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the hashed value from a cookie
|
||||
* and tries to extract the value
|
||||
*/
|
||||
protected static function parse(string $string): string|null
|
||||
{
|
||||
// if no hash-value separator is present, we can't parse the value
|
||||
if (strpos($string, '+') === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// extract hash and value
|
||||
$hash = Str::before($string, '+');
|
||||
$value = Str::after($string, '+');
|
||||
|
||||
// if the hash or the value is missing at all return null
|
||||
// $value can be an empty string, $hash can't be!
|
||||
if ($hash === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// compare the extracted hash with the hashed value
|
||||
// don't accept value if the hash is invalid
|
||||
if (hash_equals(static::hmac($value), $hash) !== true) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a cookie
|
||||
*
|
||||
* <code>
|
||||
*
|
||||
* cookie::remove('mycookie');
|
||||
* // mycookie is now gone
|
||||
*
|
||||
* </code>
|
||||
*
|
||||
* @param string $key The name of the cookie
|
||||
* @return bool true: the cookie has been removed,
|
||||
* false: the cookie could not be removed
|
||||
*/
|
||||
public static function remove(string $key): bool
|
||||
{
|
||||
if (isset($_COOKIE[$key]) === true) {
|
||||
unset($_COOKIE[$key]);
|
||||
return setcookie($key, '', 1, '/') && setcookie($key, false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the CMS responder that the response relies on a cookie and
|
||||
* its value (even if the cookie isn't set in the current request);
|
||||
* this ensures that the response is only cached for visitors who don't
|
||||
* have this cookie set;
|
||||
* https://github.com/getkirby/kirby/issues/4423#issuecomment-1166300526
|
||||
*/
|
||||
protected static function trackUsage(string $key): void
|
||||
{
|
||||
// lazily request the instance for non-CMS use cases
|
||||
$kirby = App::instance(null, true);
|
||||
$kirby?->response()->usesCookie($key);
|
||||
}
|
||||
}
|
||||
1018
kirby/src/Http/Environment.php
Normal file
1018
kirby/src/Http/Environment.php
Normal file
File diff suppressed because it is too large
Load Diff
16
kirby/src/Http/Exceptions/NextRouteException.php
Normal file
16
kirby/src/Http/Exceptions/NextRouteException.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Exceptions;
|
||||
|
||||
/**
|
||||
* NextRouteException
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class NextRouteException extends \Exception
|
||||
{
|
||||
}
|
||||
313
kirby/src/Http/Header.php
Normal file
313
kirby/src/Http/Header.php
Normal file
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Filesystem\F;
|
||||
|
||||
/**
|
||||
* The Header class provides methods
|
||||
* for sending HTTP headers.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Header
|
||||
{
|
||||
// configuration
|
||||
public static array $codes = [
|
||||
// successful
|
||||
'_200' => 'OK',
|
||||
'_201' => 'Created',
|
||||
'_202' => 'Accepted',
|
||||
|
||||
// redirection
|
||||
'_300' => 'Multiple Choices',
|
||||
'_301' => 'Moved Permanently',
|
||||
'_302' => 'Found',
|
||||
'_303' => 'See Other',
|
||||
'_304' => 'Not Modified',
|
||||
'_307' => 'Temporary Redirect',
|
||||
'_308' => 'Permanent Redirect',
|
||||
|
||||
// client error
|
||||
'_400' => 'Bad Request',
|
||||
'_401' => 'Unauthorized',
|
||||
'_402' => 'Payment Required',
|
||||
'_403' => 'Forbidden',
|
||||
'_404' => 'Not Found',
|
||||
'_405' => 'Method Not Allowed',
|
||||
'_406' => 'Not Acceptable',
|
||||
'_410' => 'Gone',
|
||||
'_418' => 'I\'m a teapot',
|
||||
'_451' => 'Unavailable For Legal Reasons',
|
||||
|
||||
// server error
|
||||
'_500' => 'Internal Server Error',
|
||||
'_501' => 'Not Implemented',
|
||||
'_502' => 'Bad Gateway',
|
||||
'_503' => 'Service Unavailable',
|
||||
'_504' => 'Gateway Time-out'
|
||||
];
|
||||
|
||||
/**
|
||||
* Sends a content type header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function contentType(
|
||||
string $mime,
|
||||
string $charset = 'UTF-8',
|
||||
bool $send = true
|
||||
) {
|
||||
if ($found = F::extensionToMime($mime)) {
|
||||
$mime = $found;
|
||||
}
|
||||
|
||||
$header = 'Content-type: ' . $mime;
|
||||
|
||||
if (empty($charset) === false) {
|
||||
$header .= '; charset=' . $charset;
|
||||
}
|
||||
|
||||
if ($send === false) {
|
||||
return $header;
|
||||
}
|
||||
|
||||
header($header);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates headers by key and value
|
||||
*/
|
||||
public static function create(
|
||||
string|array $key,
|
||||
string|null $value = null
|
||||
): string {
|
||||
if (is_array($key) === true) {
|
||||
$headers = [];
|
||||
|
||||
foreach ($key as $k => $v) {
|
||||
$headers[] = static::create($k, $v);
|
||||
}
|
||||
|
||||
return implode("\r\n", $headers);
|
||||
}
|
||||
|
||||
// prevent header injection by stripping
|
||||
// any newline characters from single headers
|
||||
return str_replace(["\r", "\n"], '', $key . ': ' . $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut for static::contentType()
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function type(
|
||||
string $mime,
|
||||
string $charset = 'UTF-8',
|
||||
bool $send = true
|
||||
) {
|
||||
return static::contentType($mime, $charset, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a status header
|
||||
*
|
||||
* Checks $code against a list of known status codes. To bypass this check
|
||||
* and send a custom status code and message, use a $code string formatted
|
||||
* as 3 digits followed by a space and a message, e.g. '999 Custom Status'.
|
||||
*
|
||||
* @param int|string|null $code The HTTP status code
|
||||
* @param bool $send If set to false the header will be returned instead
|
||||
* @return string|void
|
||||
* @psalm-return ($send is false ? string : void)
|
||||
*/
|
||||
public static function status(
|
||||
int|string|null $code = null,
|
||||
bool $send = true
|
||||
) {
|
||||
$codes = static::$codes;
|
||||
$protocol = Environment::getGlobally('SERVER_PROTOCOL', 'HTTP/1.1');
|
||||
|
||||
// allow full control over code and message
|
||||
if (
|
||||
is_string($code) === true &&
|
||||
preg_match('/^\d{3} \w.+$/', $code) === 1
|
||||
) {
|
||||
$message = substr(rtrim($code), 4);
|
||||
$code = substr($code, 0, 3);
|
||||
} else {
|
||||
if (array_key_exists('_' . $code, $codes) === false) {
|
||||
$code = 500;
|
||||
}
|
||||
|
||||
$message = $codes['_' . $code] ?? 'Something went wrong';
|
||||
}
|
||||
|
||||
$header = $protocol . ' ' . $code . ' ' . $message;
|
||||
|
||||
if ($send === false) {
|
||||
return $header;
|
||||
}
|
||||
|
||||
// try to send the header
|
||||
header($header);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 200 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function success(bool $send = true)
|
||||
{
|
||||
return static::status(200, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 201 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function created(bool $send = true)
|
||||
{
|
||||
return static::status(201, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 202 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function accepted(bool $send = true)
|
||||
{
|
||||
return static::status(202, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 400 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function error(bool $send = true)
|
||||
{
|
||||
return static::status(400, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 403 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function forbidden(bool $send = true)
|
||||
{
|
||||
return static::status(403, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 404 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function notfound(bool $send = true)
|
||||
{
|
||||
return static::status(404, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 404 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function missing(bool $send = true)
|
||||
{
|
||||
return static::status(404, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 410 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function gone(bool $send = true)
|
||||
{
|
||||
return static::status(410, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 500 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function panic(bool $send = true)
|
||||
{
|
||||
return static::status(500, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a 503 header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function unavailable(bool $send = true)
|
||||
{
|
||||
return static::status(503, $send);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a redirect header
|
||||
*
|
||||
* @return string|void
|
||||
*/
|
||||
public static function redirect(
|
||||
string $url,
|
||||
int $code = 302,
|
||||
bool $send = true
|
||||
) {
|
||||
$status = static::status($code, false);
|
||||
$location = 'Location:' . Url::unIdn($url);
|
||||
|
||||
if ($send !== true) {
|
||||
return $status . "\r\n" . $location;
|
||||
}
|
||||
|
||||
header($status);
|
||||
header($location);
|
||||
exit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends download headers for anything that is downloadable
|
||||
*
|
||||
* @param array $params Check out the defaults array for available parameters
|
||||
*/
|
||||
public static function download(array $params = []): void
|
||||
{
|
||||
$defaults = [
|
||||
'name' => 'download',
|
||||
'size' => false,
|
||||
'mime' => 'application/force-download',
|
||||
'modified' => time()
|
||||
];
|
||||
|
||||
$options = array_merge($defaults, $params);
|
||||
|
||||
header('Pragma: public');
|
||||
header('Cache-Control: no-cache, no-store, must-revalidate');
|
||||
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $options['modified']) . ' GMT');
|
||||
header('Content-Disposition: attachment; filename="' . $options['name'] . '"');
|
||||
header('Content-Transfer-Encoding: binary');
|
||||
|
||||
static::contentType($options['mime']);
|
||||
|
||||
if ($options['size']) {
|
||||
header('Content-Length: ' . $options['size']);
|
||||
}
|
||||
|
||||
header('Connection: close');
|
||||
}
|
||||
}
|
||||
63
kirby/src/Http/Idn.php
Normal file
63
kirby/src/Http/Idn.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* Handles Internationalized Domain Names
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Idn
|
||||
{
|
||||
/**
|
||||
* Convert domain name from IDNA ASCII to Unicode
|
||||
*/
|
||||
public static function decode(string $domain): string|false
|
||||
{
|
||||
return idn_to_utf8($domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert domain name to IDNA ASCII form
|
||||
*/
|
||||
public static function encode(string $domain): string|false
|
||||
{
|
||||
return idn_to_ascii($domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a email address to the Unicode format
|
||||
*/
|
||||
public static function decodeEmail(string $email): string
|
||||
{
|
||||
if (Str::contains($email, 'xn--') === true) {
|
||||
$parts = Str::split($email, '@');
|
||||
$address = $parts[0];
|
||||
$domain = Idn::decode($parts[1] ?? '');
|
||||
$email = $address . '@' . $domain;
|
||||
}
|
||||
|
||||
return $email;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a email address to the Punycode format
|
||||
*/
|
||||
public static function encodeEmail(string $email): string
|
||||
{
|
||||
if (mb_detect_encoding($email, 'ASCII', true) === false) {
|
||||
$parts = Str::split($email, '@');
|
||||
$address = $parts[0];
|
||||
$domain = Idn::encode($parts[1] ?? '');
|
||||
$email = $address . '@' . $domain;
|
||||
}
|
||||
|
||||
return $email;
|
||||
}
|
||||
}
|
||||
156
kirby/src/Http/Params.php
Normal file
156
kirby/src/Http/Params.php
Normal file
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Toolkit\Obj;
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* A wrapper around a URL params
|
||||
* that converts it into a Kirby Obj for easier
|
||||
* access of each param.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Params extends Obj
|
||||
{
|
||||
public static string|null $separator = null;
|
||||
|
||||
/**
|
||||
* Creates a new params object
|
||||
*/
|
||||
public function __construct(array|string|null $params)
|
||||
{
|
||||
if (is_string($params) === true) {
|
||||
$params = static::extract($params)['params'];
|
||||
}
|
||||
|
||||
parent::__construct($params ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the params from a string or array
|
||||
*/
|
||||
public static function extract(string|array|null $path = null): array
|
||||
{
|
||||
if (empty($path) === true) {
|
||||
return [
|
||||
'path' => null,
|
||||
'params' => null,
|
||||
'slash' => false
|
||||
];
|
||||
}
|
||||
|
||||
$slash = false;
|
||||
|
||||
if (is_string($path) === true) {
|
||||
$slash = substr($path, -1, 1) === '/';
|
||||
$path = Str::split($path, '/');
|
||||
}
|
||||
|
||||
if (is_array($path) === true) {
|
||||
$params = [];
|
||||
$separator = static::separator();
|
||||
|
||||
foreach ($path as $index => $p) {
|
||||
if (strpos($p, $separator) === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$paramParts = Str::split($p, $separator);
|
||||
$paramKey = $paramParts[0] ?? null;
|
||||
$paramValue = $paramParts[1] ?? null;
|
||||
|
||||
if ($paramKey !== null) {
|
||||
$params[rawurldecode($paramKey)] = $paramValue !== null ? rawurldecode($paramValue) : null;
|
||||
}
|
||||
|
||||
unset($path[$index]);
|
||||
}
|
||||
|
||||
return [
|
||||
'path' => $path,
|
||||
'params' => $params,
|
||||
'slash' => $slash
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'path' => null,
|
||||
'params' => null,
|
||||
'slash' => false
|
||||
];
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return empty((array)$this) === true;
|
||||
}
|
||||
|
||||
public function isNotEmpty(): bool
|
||||
{
|
||||
return $this->isEmpty() === false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the param separator according
|
||||
* to the operating system.
|
||||
*
|
||||
* Unix = ':'
|
||||
* Windows = ';'
|
||||
*/
|
||||
public static function separator(): string
|
||||
{
|
||||
if (static::$separator !== null) {
|
||||
return static::$separator;
|
||||
}
|
||||
|
||||
if (DIRECTORY_SEPARATOR === '/') {
|
||||
return static::$separator = ':';
|
||||
}
|
||||
|
||||
return static::$separator = ';';
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the params object to a params string
|
||||
* which can then be used in the URL builder again
|
||||
*/
|
||||
public function toString(
|
||||
bool $leadingSlash = false,
|
||||
bool $trailingSlash = false
|
||||
): string {
|
||||
if ($this->isEmpty() === true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$params = [];
|
||||
$separator = static::separator();
|
||||
|
||||
foreach ($this as $key => $value) {
|
||||
if ($value !== null && $value !== '') {
|
||||
$params[] = rawurlencode($key) . $separator . rawurlencode($value);
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($params) === true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$params = implode('/', $params);
|
||||
|
||||
$leadingSlash = $leadingSlash === true ? '/' : null;
|
||||
$trailingSlash = $trailingSlash === true ? '/' : null;
|
||||
|
||||
return $leadingSlash . $params . $trailingSlash;
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toString();
|
||||
}
|
||||
}
|
||||
49
kirby/src/Http/Path.php
Normal file
49
kirby/src/Http/Path.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Toolkit\Collection;
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* A wrapper around an URL path
|
||||
* that converts the path into a Kirby stack
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Path extends Collection
|
||||
{
|
||||
public function __construct(string|array|null $items)
|
||||
{
|
||||
if (is_string($items) === true) {
|
||||
$items = Str::split($items, '/');
|
||||
}
|
||||
|
||||
parent::__construct($items ?? []);
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toString();
|
||||
}
|
||||
|
||||
public function toString(
|
||||
bool $leadingSlash = false,
|
||||
bool $trailingSlash = false
|
||||
): string {
|
||||
if (empty($this->data) === true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$path = implode('/', $this->data);
|
||||
|
||||
$leadingSlash = $leadingSlash === true ? '/' : null;
|
||||
$trailingSlash = $trailingSlash === true ? '/' : null;
|
||||
|
||||
return $leadingSlash . $path . $trailingSlash;
|
||||
}
|
||||
}
|
||||
59
kirby/src/Http/Query.php
Normal file
59
kirby/src/Http/Query.php
Normal file
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Toolkit\Obj;
|
||||
|
||||
/**
|
||||
* A wrapper around a URL query string
|
||||
* that converts it into a Kirby Obj for easier
|
||||
* access of each query attribute.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Query extends Obj
|
||||
{
|
||||
public function __construct(string|array|null $query)
|
||||
{
|
||||
if (is_string($query) === true) {
|
||||
parse_str(ltrim($query, '?'), $query);
|
||||
}
|
||||
|
||||
parent::__construct($query ?? []);
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return empty((array)$this) === true;
|
||||
}
|
||||
|
||||
public function isNotEmpty(): bool
|
||||
{
|
||||
return $this->isEmpty() === false;
|
||||
}
|
||||
|
||||
public function toString(bool $questionMark = false): string
|
||||
{
|
||||
$query = http_build_query($this, '', '&', PHP_QUERY_RFC3986);
|
||||
|
||||
if (empty($query) === true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($questionMark === true) {
|
||||
$query = '?' . $query;
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toString();
|
||||
}
|
||||
}
|
||||
364
kirby/src/Http/Remote.php
Normal file
364
kirby/src/Http/Remote.php
Normal file
@@ -0,0 +1,364 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use CurlHandle;
|
||||
use Exception;
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Exception\InvalidArgumentException;
|
||||
use Kirby\Filesystem\F;
|
||||
use Kirby\Toolkit\Str;
|
||||
use stdClass;
|
||||
|
||||
/**
|
||||
* A handy little class to handle
|
||||
* all kinds of remote requests
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Remote
|
||||
{
|
||||
public const CA_INTERNAL = 1;
|
||||
public const CA_SYSTEM = 2;
|
||||
|
||||
public static array $defaults = [
|
||||
'agent' => null,
|
||||
'basicAuth' => null,
|
||||
'body' => true,
|
||||
'ca' => self::CA_INTERNAL,
|
||||
'data' => [],
|
||||
'encoding' => 'utf-8',
|
||||
'file' => null,
|
||||
'headers' => [],
|
||||
'method' => 'GET',
|
||||
'progress' => null,
|
||||
'test' => false,
|
||||
'timeout' => 10,
|
||||
];
|
||||
|
||||
public string|null $content = null;
|
||||
public CurlHandle|false $curl;
|
||||
public array $curlopt = [];
|
||||
public int $errorCode;
|
||||
public string $errorMessage;
|
||||
public array $headers = [];
|
||||
public array $info = [];
|
||||
public array $options = [];
|
||||
|
||||
/**
|
||||
* @throws \Exception when the curl request failed
|
||||
*/
|
||||
public function __construct(string $url, array $options = [])
|
||||
{
|
||||
$defaults = static::$defaults;
|
||||
|
||||
// use the system CA store by default if
|
||||
// one has been configured in php.ini
|
||||
$cainfo = ini_get('curl.cainfo');
|
||||
|
||||
// Suppress warnings e.g. if system CA is outside of open_basedir (See: issue #6236)
|
||||
if (empty($cainfo) === false && @is_file($cainfo) === true) {
|
||||
$defaults['ca'] = self::CA_SYSTEM;
|
||||
}
|
||||
|
||||
// update the defaults with App config if set;
|
||||
// request the App instance lazily
|
||||
if ($app = App::instance(null, true)) {
|
||||
$defaults = array_merge($defaults, $app->option('remote', []));
|
||||
}
|
||||
|
||||
// set all options
|
||||
$this->options = array_merge($defaults, $options);
|
||||
|
||||
// add the url
|
||||
$this->options['url'] = $url;
|
||||
|
||||
// send the request
|
||||
$this->fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic getter for request info data
|
||||
*/
|
||||
public function __call(string $method, array $arguments = [])
|
||||
{
|
||||
$method = str_replace('-', '_', Str::kebab($method));
|
||||
return $this->info[$method] ?? null;
|
||||
}
|
||||
|
||||
public static function __callStatic(
|
||||
string $method,
|
||||
array $arguments = []
|
||||
): static {
|
||||
return new static(
|
||||
url: $arguments[0],
|
||||
options: array_merge(
|
||||
['method' => strtoupper($method)],
|
||||
$arguments[1] ?? []
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the http status code
|
||||
*/
|
||||
public function code(): int|null
|
||||
{
|
||||
return $this->info['http_code'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the response content
|
||||
*/
|
||||
public function content(): string|null
|
||||
{
|
||||
return $this->content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up all curl options and sends the request
|
||||
*
|
||||
* @return $this
|
||||
* @throws \Exception when the curl request failed
|
||||
*/
|
||||
public function fetch(): static
|
||||
{
|
||||
// curl options
|
||||
$this->curlopt = [
|
||||
CURLOPT_URL => $this->options['url'],
|
||||
CURLOPT_ENCODING => $this->options['encoding'],
|
||||
CURLOPT_CONNECTTIMEOUT => $this->options['timeout'],
|
||||
CURLOPT_TIMEOUT => $this->options['timeout'],
|
||||
CURLOPT_AUTOREFERER => true,
|
||||
CURLOPT_RETURNTRANSFER => $this->options['body'],
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_MAXREDIRS => 10,
|
||||
CURLOPT_HEADER => false,
|
||||
CURLOPT_HEADERFUNCTION => function ($curl, $header): int {
|
||||
$parts = Str::split($header, ':');
|
||||
|
||||
if (empty($parts[0]) === false && empty($parts[1]) === false) {
|
||||
$key = array_shift($parts);
|
||||
$this->headers[$key] = implode(':', $parts);
|
||||
}
|
||||
|
||||
return strlen($header);
|
||||
}
|
||||
];
|
||||
|
||||
// determine the TLS CA to use
|
||||
if ($this->options['ca'] === self::CA_INTERNAL) {
|
||||
$this->curlopt[CURLOPT_SSL_VERIFYPEER] = true;
|
||||
$this->curlopt[CURLOPT_CAINFO] = dirname(__DIR__, 2) . '/cacert.pem';
|
||||
} elseif ($this->options['ca'] === self::CA_SYSTEM) {
|
||||
$this->curlopt[CURLOPT_SSL_VERIFYPEER] = true;
|
||||
} elseif ($this->options['ca'] === false) {
|
||||
$this->curlopt[CURLOPT_SSL_VERIFYPEER] = false;
|
||||
} elseif (
|
||||
is_string($this->options['ca']) === true &&
|
||||
is_file($this->options['ca']) === true
|
||||
) {
|
||||
$this->curlopt[CURLOPT_SSL_VERIFYPEER] = true;
|
||||
$this->curlopt[CURLOPT_CAINFO] = $this->options['ca'];
|
||||
} elseif (
|
||||
is_string($this->options['ca']) === true &&
|
||||
is_dir($this->options['ca']) === true
|
||||
) {
|
||||
$this->curlopt[CURLOPT_SSL_VERIFYPEER] = true;
|
||||
$this->curlopt[CURLOPT_CAPATH] = $this->options['ca'];
|
||||
} else {
|
||||
throw new InvalidArgumentException('Invalid "ca" option for the Remote class');
|
||||
}
|
||||
|
||||
// add the progress
|
||||
if (is_callable($this->options['progress']) === true) {
|
||||
$this->curlopt[CURLOPT_NOPROGRESS] = false;
|
||||
$this->curlopt[CURLOPT_PROGRESSFUNCTION] = $this->options['progress'];
|
||||
}
|
||||
|
||||
// add all headers
|
||||
if (empty($this->options['headers']) === false) {
|
||||
// convert associative arrays to strings
|
||||
$headers = [];
|
||||
foreach ($this->options['headers'] as $key => $value) {
|
||||
if (is_string($key) === true) {
|
||||
$value = $key . ': ' . $value;
|
||||
}
|
||||
|
||||
$headers[] = $value;
|
||||
}
|
||||
|
||||
$this->curlopt[CURLOPT_HTTPHEADER] = $headers;
|
||||
}
|
||||
|
||||
// add HTTP Basic authentication
|
||||
if (empty($this->options['basicAuth']) === false) {
|
||||
$this->curlopt[CURLOPT_USERPWD] = $this->options['basicAuth'];
|
||||
}
|
||||
|
||||
// add the user agent
|
||||
if (empty($this->options['agent']) === false) {
|
||||
$this->curlopt[CURLOPT_USERAGENT] = $this->options['agent'];
|
||||
}
|
||||
|
||||
// do some request specific stuff
|
||||
switch (strtoupper($this->options['method'])) {
|
||||
case 'POST':
|
||||
$this->curlopt[CURLOPT_POST] = true;
|
||||
$this->curlopt[CURLOPT_CUSTOMREQUEST] = 'POST';
|
||||
$this->curlopt[CURLOPT_POSTFIELDS] = $this->postfields($this->options['data']);
|
||||
break;
|
||||
case 'PUT':
|
||||
$this->curlopt[CURLOPT_CUSTOMREQUEST] = 'PUT';
|
||||
$this->curlopt[CURLOPT_POSTFIELDS] = $this->postfields($this->options['data']);
|
||||
|
||||
// put a file
|
||||
if ($this->options['file']) {
|
||||
$this->curlopt[CURLOPT_INFILE] = fopen($this->options['file'], 'r');
|
||||
$this->curlopt[CURLOPT_INFILESIZE] = F::size($this->options['file']);
|
||||
}
|
||||
break;
|
||||
case 'PATCH':
|
||||
$this->curlopt[CURLOPT_CUSTOMREQUEST] = 'PATCH';
|
||||
$this->curlopt[CURLOPT_POSTFIELDS] = $this->postfields($this->options['data']);
|
||||
break;
|
||||
case 'DELETE':
|
||||
$this->curlopt[CURLOPT_CUSTOMREQUEST] = 'DELETE';
|
||||
$this->curlopt[CURLOPT_POSTFIELDS] = $this->postfields($this->options['data']);
|
||||
break;
|
||||
case 'HEAD':
|
||||
$this->curlopt[CURLOPT_CUSTOMREQUEST] = 'HEAD';
|
||||
$this->curlopt[CURLOPT_POSTFIELDS] = $this->postfields($this->options['data']);
|
||||
$this->curlopt[CURLOPT_NOBODY] = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if ($this->options['test'] === true) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
// start a curl request
|
||||
$this->curl = curl_init();
|
||||
|
||||
curl_setopt_array($this->curl, $this->curlopt);
|
||||
|
||||
$this->content = curl_exec($this->curl);
|
||||
$this->info = curl_getinfo($this->curl);
|
||||
$this->errorCode = curl_errno($this->curl);
|
||||
$this->errorMessage = curl_error($this->curl);
|
||||
|
||||
if ($this->errorCode) {
|
||||
throw new Exception($this->errorMessage, $this->errorCode);
|
||||
}
|
||||
|
||||
curl_close($this->curl);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static method to send a GET request
|
||||
*
|
||||
* @throws \Exception when the curl request failed
|
||||
*/
|
||||
public static function get(string $url, array $params = []): static
|
||||
{
|
||||
$defaults = [
|
||||
'method' => 'GET',
|
||||
'data' => [],
|
||||
];
|
||||
|
||||
$options = array_merge($defaults, $params);
|
||||
$query = http_build_query($options['data']);
|
||||
|
||||
if (empty($query) === false) {
|
||||
$url = match (Url::hasQuery($url)) {
|
||||
true => $url . '&' . $query,
|
||||
default => $url . '?' . $query
|
||||
};
|
||||
}
|
||||
|
||||
// remove the data array from the options
|
||||
unset($options['data']);
|
||||
|
||||
return new static($url, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all received headers
|
||||
*/
|
||||
public function headers(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the request info
|
||||
*/
|
||||
public function info(): array
|
||||
{
|
||||
return $this->info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the response content
|
||||
*
|
||||
* @param bool $array decode as array or object
|
||||
* @psalm-return ($array is true ? array|null : stdClass|null)
|
||||
*/
|
||||
public function json(bool $array = true): array|stdClass|null
|
||||
{
|
||||
return json_decode($this->content(), $array);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the request method
|
||||
*/
|
||||
public function method(): string
|
||||
{
|
||||
return $this->options['method'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all options which have been
|
||||
* set for the current request
|
||||
*/
|
||||
public function options(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method to handle post field data
|
||||
*/
|
||||
protected function postfields($data)
|
||||
{
|
||||
if (is_object($data) || is_array($data)) {
|
||||
return http_build_query($data);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static method to init this class and send a request
|
||||
*
|
||||
* @throws \Exception when the curl request failed
|
||||
*/
|
||||
public static function request(string $url, array $params = []): static
|
||||
{
|
||||
return new static($url, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the request Url
|
||||
*/
|
||||
public function url(): string
|
||||
{
|
||||
return $this->options['url'];
|
||||
}
|
||||
}
|
||||
426
kirby/src/Http/Request.php
Normal file
426
kirby/src/Http/Request.php
Normal file
@@ -0,0 +1,426 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Http\Request\Auth;
|
||||
use Kirby\Http\Request\Auth\BasicAuth;
|
||||
use Kirby\Http\Request\Auth\BearerAuth;
|
||||
use Kirby\Http\Request\Auth\SessionAuth;
|
||||
use Kirby\Http\Request\Body;
|
||||
use Kirby\Http\Request\Files;
|
||||
use Kirby\Http\Request\Query;
|
||||
use Kirby\Toolkit\A;
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* The `Request` class provides
|
||||
* a simple API to inspect incoming
|
||||
* requests.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Request
|
||||
{
|
||||
public static array $authTypes = [
|
||||
'basic' => BasicAuth::class,
|
||||
'bearer' => BearerAuth::class,
|
||||
'session' => SessionAuth::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* The auth object if available
|
||||
*/
|
||||
protected Auth|false|null $auth = null;
|
||||
|
||||
/**
|
||||
* The Body object is a wrapper around
|
||||
* the request body, which parses the contents
|
||||
* of the body and provides an API to fetch
|
||||
* particular parts of the body
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* `$request->body()->get('foo')`
|
||||
*/
|
||||
protected Body|null $body = null;
|
||||
|
||||
/**
|
||||
* The Files object is a wrapper around
|
||||
* the $_FILES global. It sanitizes the
|
||||
* $_FILES array and provides an API to fetch
|
||||
* individual files by key
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* `$request->files()->get('upload')['size']`
|
||||
* `$request->file('upload')['size']`
|
||||
*/
|
||||
protected Files|null $files = null;
|
||||
|
||||
/**
|
||||
* The Method type
|
||||
*/
|
||||
protected string $method;
|
||||
|
||||
/**
|
||||
* All options that have been passed to
|
||||
* the request in the constructor
|
||||
*/
|
||||
protected array $options;
|
||||
|
||||
/**
|
||||
* The Query object is a wrapper around
|
||||
* the URL query string, which parses the
|
||||
* string and provides a clean API to fetch
|
||||
* particular parts of the query
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* `$request->query()->get('foo')`
|
||||
*/
|
||||
protected Query $query;
|
||||
|
||||
/**
|
||||
* Request URL object
|
||||
*/
|
||||
protected Uri $url;
|
||||
|
||||
/**
|
||||
* Creates a new Request object
|
||||
* You can either pass your own request
|
||||
* data via the $options array or use
|
||||
* the data from the incoming request.
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
$this->options = $options;
|
||||
$this->method = $this->detectRequestMethod($options['method'] ?? null);
|
||||
|
||||
if (isset($options['body']) === true) {
|
||||
$this->body =
|
||||
$options['body'] instanceof Body
|
||||
? $options['body']
|
||||
: new Body($options['body']);
|
||||
}
|
||||
|
||||
if (isset($options['files']) === true) {
|
||||
$this->files =
|
||||
$options['files'] instanceof Files
|
||||
? $options['files']
|
||||
: new Files($options['files']);
|
||||
}
|
||||
|
||||
if (isset($options['query']) === true) {
|
||||
$this->query =
|
||||
$options['query'] instanceof Query
|
||||
? $options['query']
|
||||
: new Query($options['query']);
|
||||
}
|
||||
|
||||
if (isset($options['url']) === true) {
|
||||
$this->url =
|
||||
$options['url'] instanceof Uri
|
||||
? $options['url']
|
||||
: new Uri($options['url']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Improved `var_dump` output
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function __debugInfo(): array
|
||||
{
|
||||
return [
|
||||
'body' => $this->body(),
|
||||
'files' => $this->files(),
|
||||
'method' => $this->method(),
|
||||
'query' => $this->query(),
|
||||
'url' => $this->url()->toString()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Auth object if authentication is set
|
||||
*/
|
||||
public function auth(): Auth|false|null
|
||||
{
|
||||
if ($this->auth !== null) {
|
||||
return $this->auth;
|
||||
}
|
||||
|
||||
// lazily request the instance for non-CMS use cases
|
||||
$kirby = App::instance(null, true);
|
||||
|
||||
// tell the CMS responder that the response relies on
|
||||
// the `Authorization` header and its value (even if
|
||||
// the header isn't set in the current request);
|
||||
// this ensures that the response is only cached for
|
||||
// unauthenticated visitors;
|
||||
// https://github.com/getkirby/kirby/issues/4423#issuecomment-1166300526
|
||||
$kirby?->response()->usesAuth(true);
|
||||
|
||||
if ($auth = $this->authString()) {
|
||||
$type = Str::lower(Str::before($auth, ' '));
|
||||
$data = Str::after($auth, ' ');
|
||||
|
||||
$class = static::$authTypes[$type] ?? null;
|
||||
if (!$class || class_exists($class) === false) {
|
||||
return $this->auth = false;
|
||||
}
|
||||
|
||||
$object = new $class($data);
|
||||
|
||||
return $this->auth = $object;
|
||||
}
|
||||
|
||||
return $this->auth = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Body object
|
||||
*/
|
||||
public function body(): Body
|
||||
{
|
||||
return $this->body ??= new Body();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the request has been made from the command line
|
||||
*/
|
||||
public function cli(): bool
|
||||
{
|
||||
return $this->options['cli'] ?? (new Environment())->cli();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a CSRF token if stored in a header or the query
|
||||
*/
|
||||
public function csrf(): string|null
|
||||
{
|
||||
return $this->header('x-csrf') ?? $this->query()->get('csrf');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the request input as array
|
||||
*/
|
||||
public function data(): array
|
||||
{
|
||||
return array_replace(
|
||||
$this->body()->toArray(),
|
||||
$this->query()->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the request method from various
|
||||
* options: given method, query string, server vars
|
||||
*/
|
||||
public function detectRequestMethod(string|null $method = null): string
|
||||
{
|
||||
// all possible methods
|
||||
$methods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'];
|
||||
|
||||
// the request method can be overwritten with a header
|
||||
$methodOverride = strtoupper(Environment::getGlobally('HTTP_X_HTTP_METHOD_OVERRIDE', ''));
|
||||
|
||||
if (in_array($methodOverride, $methods) === true) {
|
||||
$method ??= $methodOverride;
|
||||
}
|
||||
|
||||
// final chain of options to detect the method
|
||||
$method ??= Environment::getGlobally('REQUEST_METHOD', 'GET');
|
||||
|
||||
// uppercase the shit out of it
|
||||
$method = strtoupper($method);
|
||||
|
||||
// sanitize the method
|
||||
if (in_array($method, $methods) === false) {
|
||||
$method = 'GET';
|
||||
}
|
||||
|
||||
return $method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the domain
|
||||
*/
|
||||
public function domain(): string
|
||||
{
|
||||
return $this->url()->domain();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a single file array
|
||||
* from the Files object by key
|
||||
*/
|
||||
public function file(string $key): array|null
|
||||
{
|
||||
return $this->files()->get($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Files object
|
||||
*/
|
||||
public function files(): Files
|
||||
{
|
||||
return $this->files ??= new Files();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns any data field from the request
|
||||
* if it exists
|
||||
*/
|
||||
public function get(string|array|null $key = null, $fallback = null)
|
||||
{
|
||||
return A::get($this->data(), $key, $fallback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the request contains
|
||||
* the `Authorization` header
|
||||
* @since 3.7.0
|
||||
*/
|
||||
public function hasAuth(): bool
|
||||
{
|
||||
return $this->authString() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a header by key if it exists
|
||||
*/
|
||||
public function header(string $key, $fallback = null)
|
||||
{
|
||||
$headers = array_change_key_case($this->headers());
|
||||
return $headers[strtolower($key)] ?? $fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all headers with polyfill for
|
||||
* missing getallheaders function
|
||||
*/
|
||||
public function headers(): array
|
||||
{
|
||||
$headers = [];
|
||||
|
||||
foreach (Environment::getGlobally() as $key => $value) {
|
||||
if (
|
||||
substr($key, 0, 5) !== 'HTTP_' &&
|
||||
substr($key, 0, 14) !== 'REDIRECT_HTTP_'
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// remove HTTP_
|
||||
$key = str_replace(['REDIRECT_HTTP_', 'HTTP_'], '', $key);
|
||||
|
||||
// convert to lowercase
|
||||
$key = strtolower($key);
|
||||
|
||||
// replace _ with spaces
|
||||
$key = str_replace('_', ' ', $key);
|
||||
|
||||
// uppercase first char in each word
|
||||
$key = ucwords($key);
|
||||
|
||||
// convert spaces to dashes
|
||||
$key = str_replace(' ', '-', $key);
|
||||
|
||||
$headers[$key] = $value;
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given method name
|
||||
* matches the name of the request method.
|
||||
*/
|
||||
public function is(string $method): bool
|
||||
{
|
||||
return strtoupper($this->method) === strtoupper($method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the request method
|
||||
*/
|
||||
public function method(): string
|
||||
{
|
||||
return $this->method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut to the Params object
|
||||
*/
|
||||
public function params(): Params
|
||||
{
|
||||
return $this->url()->params();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut to the Path object
|
||||
*/
|
||||
public function path(): Path
|
||||
{
|
||||
return $this->url()->path();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Query object
|
||||
*/
|
||||
public function query(): Query
|
||||
{
|
||||
return $this->query ??= new Query();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for a valid SSL connection
|
||||
*/
|
||||
public function ssl(): bool
|
||||
{
|
||||
return $this->url()->scheme() === 'https';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current Uri object.
|
||||
* If you pass props you can safely modify
|
||||
* the Url with new parameters without destroying
|
||||
* the original object.
|
||||
*/
|
||||
public function url(array|null $props = null): Uri
|
||||
{
|
||||
if ($props !== null) {
|
||||
return $this->url()->clone($props);
|
||||
}
|
||||
|
||||
return $this->url ??= Uri::current();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw auth string from the `auth` option
|
||||
* or `Authorization` header unless both are empty
|
||||
*/
|
||||
protected function authString(): string|null
|
||||
{
|
||||
// both variants need to be checked separately
|
||||
// because empty strings are treated as invalid
|
||||
// but the `??` operator wouldn't do the fallback
|
||||
|
||||
$option = $this->options['auth'] ?? null;
|
||||
if (empty($option) === false) {
|
||||
return $option;
|
||||
}
|
||||
|
||||
$header = $this->header('authorization');
|
||||
if (empty($header) === false) {
|
||||
return $header;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
48
kirby/src/Http/Request/Auth.php
Normal file
48
kirby/src/Http/Request/Auth.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request;
|
||||
|
||||
use SensitiveParameter;
|
||||
|
||||
/**
|
||||
* Base class for auth types
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Lukas Bestle <lukas@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
abstract class Auth
|
||||
{
|
||||
/**
|
||||
* @param string $data Raw authentication data after the first space in the `Authorization` header
|
||||
*/
|
||||
public function __construct(
|
||||
#[SensitiveParameter]
|
||||
protected string $data
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the object to a string
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return ucfirst($this->type()) . ' ' . $this->data();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw authentication data after the
|
||||
* first space in the `Authorization` header
|
||||
*/
|
||||
public function data(): string
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the auth type (lowercase)
|
||||
*/
|
||||
abstract public function type(): string;
|
||||
}
|
||||
66
kirby/src/Http/Request/Auth/BasicAuth.php
Normal file
66
kirby/src/Http/Request/Auth/BasicAuth.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request\Auth;
|
||||
|
||||
use Kirby\Http\Request\Auth;
|
||||
use Kirby\Toolkit\Str;
|
||||
use SensitiveParameter;
|
||||
|
||||
/**
|
||||
* HTTP basic authentication data
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class BasicAuth extends Auth
|
||||
{
|
||||
protected string $credentials;
|
||||
protected string|null $password;
|
||||
protected string|null $username;
|
||||
|
||||
public function __construct(
|
||||
#[SensitiveParameter]
|
||||
string $data
|
||||
) {
|
||||
parent::__construct($data);
|
||||
|
||||
$this->credentials = base64_decode($data);
|
||||
$this->username = Str::before($this->credentials, ':');
|
||||
$this->password = Str::after($this->credentials, ':');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the entire unencoded credentials string
|
||||
*/
|
||||
public function credentials(): string
|
||||
{
|
||||
return $this->credentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the password
|
||||
*/
|
||||
public function password(): string|null
|
||||
{
|
||||
return $this->password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the authentication type
|
||||
*/
|
||||
public function type(): string
|
||||
{
|
||||
return 'basic';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the username
|
||||
*/
|
||||
public function username(): string|null
|
||||
{
|
||||
return $this->username;
|
||||
}
|
||||
}
|
||||
33
kirby/src/Http/Request/Auth/BearerAuth.php
Normal file
33
kirby/src/Http/Request/Auth/BearerAuth.php
Normal file
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request\Auth;
|
||||
|
||||
use Kirby\Http\Request\Auth;
|
||||
|
||||
/**
|
||||
* Bearer token authentication data
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class BearerAuth extends Auth
|
||||
{
|
||||
/**
|
||||
* Returns the authentication token
|
||||
*/
|
||||
public function token(): string
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the auth type
|
||||
*/
|
||||
public function type(): string
|
||||
{
|
||||
return 'bearer';
|
||||
}
|
||||
}
|
||||
43
kirby/src/Http/Request/Auth/SessionAuth.php
Normal file
43
kirby/src/Http/Request/Auth/SessionAuth.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request\Auth;
|
||||
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Http\Request\Auth;
|
||||
use Kirby\Session\Session;
|
||||
|
||||
/**
|
||||
* Authentication data using Kirby's session
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Lukas Bestle <lukas@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class SessionAuth extends Auth
|
||||
{
|
||||
/**
|
||||
* Tries to return the session object
|
||||
*/
|
||||
public function session(): Session
|
||||
{
|
||||
return App::instance()->sessionHandler()->getManually($this->data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the session token
|
||||
*/
|
||||
public function token(): string
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the authentication type
|
||||
*/
|
||||
public function type(): string
|
||||
{
|
||||
return 'session';
|
||||
}
|
||||
}
|
||||
115
kirby/src/Http/Request/Body.php
Normal file
115
kirby/src/Http/Request/Body.php
Normal file
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request;
|
||||
|
||||
/**
|
||||
* The Body class parses the
|
||||
* request body and provides a nice
|
||||
* interface to get values from
|
||||
* structured bodies (json encoded or form data)
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Body
|
||||
{
|
||||
use Data;
|
||||
|
||||
/**
|
||||
* The raw body content
|
||||
*/
|
||||
protected string|array|null $contents;
|
||||
|
||||
/**
|
||||
* The parsed content as array
|
||||
*/
|
||||
protected array|null $data = null;
|
||||
|
||||
/**
|
||||
* Creates a new request body object.
|
||||
* You can pass your own array or string.
|
||||
* If null is being passed, the class will
|
||||
* fetch the body either from the $_POST global
|
||||
* or from php://input.
|
||||
*/
|
||||
public function __construct(array|string|null $contents = null)
|
||||
{
|
||||
$this->contents = $contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the raw contents for the body
|
||||
* or uses the passed contents.
|
||||
*/
|
||||
public function contents(): string|array
|
||||
{
|
||||
if ($this->contents !== null) {
|
||||
return $this->contents;
|
||||
}
|
||||
|
||||
if (empty($_POST) === false) {
|
||||
return $this->contents = $_POST;
|
||||
}
|
||||
|
||||
return $this->contents = file_get_contents('php://input');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the raw contents once and caches
|
||||
* the result. The parser will try to convert
|
||||
* the body with the json decoder first and
|
||||
* then run parse_str to get some results
|
||||
* if the json decoder failed.
|
||||
*/
|
||||
public function data(): array
|
||||
{
|
||||
if (is_array($this->data) === true) {
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
$contents = $this->contents();
|
||||
|
||||
// return content which is already in array form
|
||||
if (is_array($contents) === true) {
|
||||
return $this->data = $contents;
|
||||
}
|
||||
|
||||
// try to convert the body from json
|
||||
$json = json_decode($contents, true);
|
||||
|
||||
if (is_array($json) === true) {
|
||||
return $this->data = $json;
|
||||
}
|
||||
|
||||
if (strstr($contents, '=') !== false) {
|
||||
// try to parse the body as query string
|
||||
parse_str($contents, $parsed);
|
||||
|
||||
if (is_array($parsed)) {
|
||||
return $this->data = $parsed;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->data = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the data array back
|
||||
* to a http query string
|
||||
*/
|
||||
public function toString(): string
|
||||
{
|
||||
return http_build_query($this->data());
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic string converter
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toString();
|
||||
}
|
||||
}
|
||||
73
kirby/src/Http/Request/Data.php
Normal file
73
kirby/src/Http/Request/Data.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request;
|
||||
|
||||
/**
|
||||
* The Data Trait is being used in
|
||||
* Query, Files and Body classes to
|
||||
* provide unified get and data methods.
|
||||
* Especially the get method is a bit more
|
||||
* complex with the option to fetch single keys
|
||||
* or entire arrays.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
trait Data
|
||||
{
|
||||
/**
|
||||
* Improved `var_dump` output
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function __debugInfo(): array
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* The data provider method has to be
|
||||
* implemented by each class using this Trait
|
||||
* and has to return an associative array
|
||||
* for the get method
|
||||
*/
|
||||
abstract public function data(): array;
|
||||
|
||||
/**
|
||||
* The get method is the heart and soul of this
|
||||
* Trait. You can use it to fetch a single value
|
||||
* of the data array by key or multiple values by
|
||||
* passing an array of keys.
|
||||
*/
|
||||
public function get(string|array $key, $default = null)
|
||||
{
|
||||
if (is_array($key) === true) {
|
||||
$result = [];
|
||||
foreach ($key as $k) {
|
||||
$result[$k] = $this->get($k);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $this->data()[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data array.
|
||||
* This is basically an alias for Data::data()
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return $this->data();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the data array to json
|
||||
*/
|
||||
public function toJson(): string
|
||||
{
|
||||
return json_encode($this->data());
|
||||
}
|
||||
}
|
||||
63
kirby/src/Http/Request/Files.php
Normal file
63
kirby/src/Http/Request/Files.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request;
|
||||
|
||||
/**
|
||||
* The Files object sanitizes
|
||||
* the input coming from the $_FILES
|
||||
* global. Especially for multiple uploads
|
||||
* for the same key, it will produce a more
|
||||
* usable array.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Files
|
||||
{
|
||||
use Data;
|
||||
|
||||
/**
|
||||
* Sanitized array of all received files
|
||||
*/
|
||||
protected array $files = [];
|
||||
|
||||
/**
|
||||
* Creates a new Files object
|
||||
* Pass your own array to mock
|
||||
* uploads.
|
||||
*/
|
||||
public function __construct(array|null $files = null)
|
||||
{
|
||||
$files ??= $_FILES;
|
||||
|
||||
foreach ($files as $key => $file) {
|
||||
if (is_array($file['name'])) {
|
||||
foreach ($file['name'] as $i => $name) {
|
||||
$this->files[$key][] = [
|
||||
'name' => $file['name'][$i] ?? null,
|
||||
'type' => $file['type'][$i] ?? null,
|
||||
'tmp_name' => $file['tmp_name'][$i] ?? null,
|
||||
'error' => $file['error'][$i] ?? null,
|
||||
'size' => $file['size'][$i] ?? null,
|
||||
];
|
||||
}
|
||||
} else {
|
||||
$this->files[$key] = $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The data method returns the files
|
||||
* array. This is only needed to make
|
||||
* the Data trait work for the Files::get($key)
|
||||
* method.
|
||||
*/
|
||||
public function data(): array
|
||||
{
|
||||
return $this->files;
|
||||
}
|
||||
}
|
||||
84
kirby/src/Http/Request/Query.php
Normal file
84
kirby/src/Http/Request/Query.php
Normal file
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http\Request;
|
||||
|
||||
/**
|
||||
* The Query class helps to
|
||||
* parse and inspect URL queries
|
||||
* as part of the Request object
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Query
|
||||
{
|
||||
use Data;
|
||||
|
||||
/**
|
||||
* The Query data array
|
||||
*/
|
||||
protected array|null $data = null;
|
||||
|
||||
/**
|
||||
* Creates a new Query object.
|
||||
* The passed data can be an array
|
||||
* or a parsable query string. If
|
||||
* null is passed, the current Query
|
||||
* will be taken from $_GET
|
||||
*/
|
||||
public function __construct(array|string|null $data = null)
|
||||
{
|
||||
if ($data === null) {
|
||||
$this->data = $_GET;
|
||||
} elseif (is_array($data) === true) {
|
||||
$this->data = $data;
|
||||
} else {
|
||||
parse_str($data, $parsed);
|
||||
$this->data = $parsed;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Query data as array
|
||||
*/
|
||||
public function data(): array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if the request doesn't contain query variables
|
||||
*/
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return empty($this->data) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if the request contains query variables
|
||||
*/
|
||||
public function isNotEmpty(): bool
|
||||
{
|
||||
return empty($this->data) === false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the query data array
|
||||
* back to a query string
|
||||
*/
|
||||
public function toString(): string
|
||||
{
|
||||
return http_build_query($this->data());
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic string converter
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toString();
|
||||
}
|
||||
}
|
||||
319
kirby/src/Http/Response.php
Normal file
319
kirby/src/Http/Response.php
Normal file
@@ -0,0 +1,319 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Kirby\Exception\LogicException;
|
||||
use Kirby\Filesystem\F;
|
||||
|
||||
/**
|
||||
* Representation of an Http response,
|
||||
* to simplify sending correct headers
|
||||
* and Http status codes.
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Response
|
||||
{
|
||||
/**
|
||||
* Store for all registered headers,
|
||||
* which will be sent with the response
|
||||
*/
|
||||
protected array $headers = [];
|
||||
|
||||
/**
|
||||
* The response body
|
||||
*/
|
||||
protected string $body;
|
||||
|
||||
/**
|
||||
* The HTTP response code
|
||||
*/
|
||||
protected int $code;
|
||||
|
||||
/**
|
||||
* The content type for the response
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* The content type charset
|
||||
*/
|
||||
protected string $charset = 'UTF-8';
|
||||
|
||||
/**
|
||||
* Creates a new response object
|
||||
*/
|
||||
public function __construct(
|
||||
string|array $body = '',
|
||||
string|null $type = null,
|
||||
int|null $code = null,
|
||||
array|null $headers = null,
|
||||
string|null $charset = null
|
||||
) {
|
||||
// array construction
|
||||
if (is_array($body) === true) {
|
||||
$params = $body;
|
||||
$body = $params['body'] ?? '';
|
||||
$type = $params['type'] ?? $type;
|
||||
$code = $params['code'] ?? $code;
|
||||
$headers = $params['headers'] ?? $headers;
|
||||
$charset = $params['charset'] ?? $charset;
|
||||
}
|
||||
|
||||
// regular construction
|
||||
$this->body = $body;
|
||||
$this->type = $type ?? 'text/html';
|
||||
$this->code = $code ?? 200;
|
||||
$this->headers = $headers ?? [];
|
||||
$this->charset = $charset ?? 'UTF-8';
|
||||
|
||||
// automatic mime type detection
|
||||
if (strpos($this->type, '/') === false) {
|
||||
$this->type = F::extensionToMime($this->type) ?? 'text/html';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Improved `var_dump` output
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function __debugInfo(): array
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes it possible to convert the
|
||||
* entire response object to a string
|
||||
* to send the headers and print the body
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the body
|
||||
*/
|
||||
public function body(): string
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the content type charset
|
||||
*/
|
||||
public function charset(): string
|
||||
{
|
||||
return $this->charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the HTTP status code
|
||||
*/
|
||||
public function code(): int
|
||||
{
|
||||
return $this->code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a response that triggers
|
||||
* a file download for the given file
|
||||
*
|
||||
* @param array $props Custom overrides for response props (e.g. headers)
|
||||
*/
|
||||
public static function download(
|
||||
string $file,
|
||||
string|null $filename = null,
|
||||
array $props = []
|
||||
): static {
|
||||
if (file_exists($file) === false) {
|
||||
throw new Exception('The file could not be found');
|
||||
}
|
||||
|
||||
$filename ??= basename($file);
|
||||
$modified = filemtime($file);
|
||||
$body = file_get_contents($file);
|
||||
$size = strlen($body);
|
||||
|
||||
$props = array_replace_recursive([
|
||||
'body' => $body,
|
||||
'type' => F::mime($file),
|
||||
'headers' => [
|
||||
'Pragma' => 'public',
|
||||
'Cache-Control' => 'no-cache, no-store, must-revalidate',
|
||||
'Last-Modified' => gmdate('D, d M Y H:i:s', $modified) . ' GMT',
|
||||
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
|
||||
'Content-Transfer-Encoding' => 'binary',
|
||||
'Content-Length' => $size,
|
||||
'Connection' => 'close'
|
||||
]
|
||||
], $props);
|
||||
|
||||
return new static($props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a response for a file and
|
||||
* sends the file content to the browser
|
||||
*
|
||||
* @param array $props Custom overrides for response props (e.g. headers)
|
||||
*/
|
||||
public static function file(string $file, array $props = []): static
|
||||
{
|
||||
$props = array_merge([
|
||||
'body' => F::read($file),
|
||||
'type' => F::extensionToMime(F::extension($file))
|
||||
], $props);
|
||||
|
||||
// if we couldn't serve a correct MIME type, force
|
||||
// the browser to display the file as plain text to
|
||||
// harden against attacks from malicious file uploads
|
||||
if ($props['type'] === null) {
|
||||
if (isset($props['headers']) !== true) {
|
||||
$props['headers'] = [];
|
||||
}
|
||||
|
||||
$props['type'] = 'text/plain';
|
||||
$props['headers']['X-Content-Type-Options'] = 'nosniff';
|
||||
}
|
||||
|
||||
return new static($props);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Redirects to the given Urls
|
||||
* Urls can be relative or absolute.
|
||||
* @since 3.7.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function go(string $url = '/', int $code = 302): never
|
||||
{
|
||||
die(static::redirect($url, $code));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the callback does not produce the first body output
|
||||
* (used to show when loading a file creates side effects)
|
||||
*/
|
||||
public static function guardAgainstOutput(Closure $callback, ...$args): mixed
|
||||
{
|
||||
$before = headers_sent();
|
||||
$result = $callback(...$args);
|
||||
$after = headers_sent($file, $line);
|
||||
|
||||
if ($before === false && $after === true) {
|
||||
throw new LogicException("Disallowed output from file $file:$line, possible accidental whitespace?");
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for single headers
|
||||
*
|
||||
* @param string $key Name of the header
|
||||
*/
|
||||
public function header(string $key): string|null
|
||||
{
|
||||
return $this->headers[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for all headers
|
||||
*/
|
||||
public function headers(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a json response with appropriate
|
||||
* header and automatic conversion of arrays.
|
||||
*/
|
||||
public static function json(
|
||||
string|array $body = '',
|
||||
int|null $code = null,
|
||||
bool|null $pretty = null,
|
||||
array $headers = []
|
||||
): static {
|
||||
if (is_array($body) === true) {
|
||||
$body = json_encode($body, $pretty === true ? JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES : 0);
|
||||
}
|
||||
|
||||
return new static([
|
||||
'body' => $body,
|
||||
'code' => $code,
|
||||
'type' => 'application/json',
|
||||
'headers' => $headers
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a redirect response,
|
||||
* which will send the visitor to the
|
||||
* given location.
|
||||
*/
|
||||
public static function redirect(string $location = '/', int $code = 302): static
|
||||
{
|
||||
return new static([
|
||||
'code' => $code,
|
||||
'headers' => [
|
||||
'Location' => Url::unIdn($location)
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends all registered headers and
|
||||
* returns the response body
|
||||
*/
|
||||
public function send(): string
|
||||
{
|
||||
// send the status response code
|
||||
http_response_code($this->code());
|
||||
|
||||
// send all custom headers
|
||||
foreach ($this->headers() as $key => $value) {
|
||||
header($key . ': ' . $value);
|
||||
}
|
||||
|
||||
// send the content type header
|
||||
header('Content-Type:' . $this->type() . '; charset=' . $this->charset());
|
||||
|
||||
// print the response body
|
||||
return $this->body();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all relevant response attributes
|
||||
* to an associative array for debugging,
|
||||
* testing or whatever.
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'type' => $this->type(),
|
||||
'charset' => $this->charset(),
|
||||
'code' => $this->code(),
|
||||
'headers' => $this->headers(),
|
||||
'body' => $this->body()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the content type
|
||||
*/
|
||||
public function type(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
}
|
||||
192
kirby/src/Http/Route.php
Normal file
192
kirby/src/Http/Route.php
Normal file
@@ -0,0 +1,192 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Route
|
||||
{
|
||||
/**
|
||||
* The callback action function
|
||||
*/
|
||||
protected Closure $action;
|
||||
|
||||
/**
|
||||
* Listed of parsed arguments
|
||||
*/
|
||||
protected array $arguments = [];
|
||||
|
||||
/**
|
||||
* An array of all passed attributes
|
||||
*/
|
||||
protected array $attributes = [];
|
||||
|
||||
/**
|
||||
* The registered request method
|
||||
*/
|
||||
protected string $method;
|
||||
|
||||
/**
|
||||
* The registered pattern
|
||||
*/
|
||||
protected string $pattern;
|
||||
|
||||
/**
|
||||
* Wildcards, which can be used in
|
||||
* Route patterns to make regular expressions
|
||||
* a little more human
|
||||
*/
|
||||
protected array $wildcards = [
|
||||
'required' => [
|
||||
'(:num)' => '(-?[0-9]+)',
|
||||
'(:alpha)' => '([a-zA-Z]+)',
|
||||
'(:alphanum)' => '([a-zA-Z0-9]+)',
|
||||
'(:any)' => '([a-zA-Z0-9\.\-_%= \+\@\(\)]+)',
|
||||
'(:all)' => '(.*)',
|
||||
],
|
||||
'optional' => [
|
||||
'/(:num?)' => '(?:/(-?[0-9]+)',
|
||||
'/(:alpha?)' => '(?:/([a-zA-Z]+)',
|
||||
'/(:alphanum?)' => '(?:/([a-zA-Z0-9]+)',
|
||||
'/(:any?)' => '(?:/([a-zA-Z0-9\.\-_%= \+\@\(\)]+)',
|
||||
'/(:all?)' => '(?:/(.*)',
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Magic getter for route attributes
|
||||
*/
|
||||
public function __call(string $key, array $args = null): mixed
|
||||
{
|
||||
return $this->attributes[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Route object for the given
|
||||
* pattern(s), method(s) and the callback action
|
||||
*/
|
||||
public function __construct(
|
||||
string $pattern,
|
||||
string $method,
|
||||
Closure $action,
|
||||
array $attributes = []
|
||||
) {
|
||||
$this->action = $action;
|
||||
$this->attributes = $attributes;
|
||||
$this->method = $method;
|
||||
$this->pattern = $this->regex(ltrim($pattern, '/'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the action callback
|
||||
*/
|
||||
public function action(): Closure
|
||||
{
|
||||
return $this->action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all parsed arguments
|
||||
*/
|
||||
public function arguments(): array
|
||||
{
|
||||
return $this->arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for additional attributes
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return $this->attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the method
|
||||
*/
|
||||
public function method(): string
|
||||
{
|
||||
return $this->method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the route name if set
|
||||
*/
|
||||
public function name(): string|null
|
||||
{
|
||||
return $this->attributes['name'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws a specific exception to tell
|
||||
* the router to jump to the next route
|
||||
* @since 3.0.3
|
||||
*/
|
||||
public static function next(): void
|
||||
{
|
||||
throw new Exceptions\NextRouteException('next');
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the pattern
|
||||
*/
|
||||
public function pattern(): string
|
||||
{
|
||||
return $this->pattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the pattern into a full regular
|
||||
* expression by replacing all the wildcards
|
||||
*/
|
||||
public function regex(string $pattern): string
|
||||
{
|
||||
$search = array_keys($this->wildcards['optional']);
|
||||
$replace = array_values($this->wildcards['optional']);
|
||||
|
||||
// For optional parameters, first translate the wildcards to their
|
||||
// regex equivalent, sans the ")?" ending. We'll add the endings
|
||||
// back on when we know the replacement count.
|
||||
$pattern = str_replace($search, $replace, $pattern, $count);
|
||||
|
||||
if ($count > 0) {
|
||||
$pattern .= str_repeat(')?', $count);
|
||||
}
|
||||
|
||||
return strtr($pattern, $this->wildcards['required']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to match the path with the regular expression and
|
||||
* extracts all arguments for the Route action
|
||||
*/
|
||||
public function parse(string $pattern, string $path): array|false
|
||||
{
|
||||
// check for direct matches
|
||||
if ($pattern === $path) {
|
||||
return $this->arguments = [];
|
||||
}
|
||||
|
||||
// We only need to check routes with regular expression since all others
|
||||
// would have been able to be matched by the search for literal matches
|
||||
// we just did before we started searching.
|
||||
if (strpos($pattern, '(') === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If we have a match we'll return all results
|
||||
// from the preg without the full first match.
|
||||
if (preg_match('#^' . $this->regex($pattern) . '$#u', $path, $parameters)) {
|
||||
return $this->arguments = array_slice($parameters, 1);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
198
kirby/src/Http/Router.php
Normal file
198
kirby/src/Http/Router.php
Normal file
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use Kirby\Toolkit\A;
|
||||
|
||||
/**
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Router
|
||||
{
|
||||
/**
|
||||
* Hook that is called after each route
|
||||
*/
|
||||
protected Closure|null $afterEach;
|
||||
|
||||
/**
|
||||
* Hook that is called before each route
|
||||
*/
|
||||
protected Closure|null $beforeEach;
|
||||
|
||||
/**
|
||||
* Store for the current route,
|
||||
* if one can be found
|
||||
*/
|
||||
protected Route|null $route = null;
|
||||
|
||||
/**
|
||||
* All registered routes, sorted by
|
||||
* their request method. This makes
|
||||
* it faster to find the right route
|
||||
* later.
|
||||
*/
|
||||
protected array $routes = [
|
||||
'GET' => [],
|
||||
'HEAD' => [],
|
||||
'POST' => [],
|
||||
'PUT' => [],
|
||||
'DELETE' => [],
|
||||
'CONNECT' => [],
|
||||
'OPTIONS' => [],
|
||||
'TRACE' => [],
|
||||
'PATCH' => [],
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates a new router object and
|
||||
* registers all the given routes
|
||||
*
|
||||
* @param array<string, \Closure> $hooks Optional `beforeEach` and `afterEach` hooks
|
||||
*/
|
||||
public function __construct(array $routes = [], array $hooks = [])
|
||||
{
|
||||
$this->beforeEach = $hooks['beforeEach'] ?? null;
|
||||
$this->afterEach = $hooks['afterEach'] ?? null;
|
||||
|
||||
foreach ($routes as $props) {
|
||||
if (isset($props['pattern'], $props['action']) === false) {
|
||||
throw new InvalidArgumentException('Invalid route parameters');
|
||||
}
|
||||
|
||||
$patterns = A::wrap($props['pattern']);
|
||||
$methods = A::map(
|
||||
explode('|', strtoupper($props['method'] ?? 'GET')),
|
||||
'trim'
|
||||
);
|
||||
|
||||
if ($methods === ['ALL']) {
|
||||
$methods = array_keys($this->routes);
|
||||
}
|
||||
|
||||
foreach ($methods as $method) {
|
||||
foreach ($patterns as $pattern) {
|
||||
$this->routes[$method][] = new Route(
|
||||
$pattern,
|
||||
$method,
|
||||
$props['action'],
|
||||
$props
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the Router by path and method.
|
||||
* This will try to find a Route object
|
||||
* and then call the Route action with
|
||||
* the appropriate arguments and a Result
|
||||
* object.
|
||||
*/
|
||||
public function call(
|
||||
string|null $path = null,
|
||||
string $method = 'GET',
|
||||
Closure|null $callback = null
|
||||
) {
|
||||
$path ??= '';
|
||||
$ignore = [];
|
||||
$result = null;
|
||||
$loop = true;
|
||||
|
||||
while ($loop === true) {
|
||||
$route = $this->find($path, $method, $ignore);
|
||||
|
||||
if ($this->beforeEach instanceof Closure) {
|
||||
($this->beforeEach)($route, $path, $method);
|
||||
}
|
||||
|
||||
try {
|
||||
if ($callback) {
|
||||
$result = $callback($route);
|
||||
} else {
|
||||
$result = $route->action()->call(
|
||||
$route,
|
||||
...$route->arguments()
|
||||
);
|
||||
}
|
||||
|
||||
$loop = false;
|
||||
} catch (Exceptions\NextRouteException) {
|
||||
$ignore[] = $route;
|
||||
}
|
||||
|
||||
if ($this->afterEach instanceof Closure) {
|
||||
$final = $loop === false;
|
||||
$result = ($this->afterEach)($route, $path, $method, $result, $final);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a micro-router and executes
|
||||
* the routing action immediately
|
||||
* @since 3.7.0
|
||||
*/
|
||||
public static function execute(
|
||||
string|null $path = null,
|
||||
string $method = 'GET',
|
||||
array $routes = [],
|
||||
Closure|null $callback = null
|
||||
) {
|
||||
return (new static($routes))->call($path, $method, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a Route object by path and method
|
||||
* The Route's arguments method is used to
|
||||
* find matches and return all the found
|
||||
* arguments in the path.
|
||||
*/
|
||||
public function find(
|
||||
string $path,
|
||||
string $method,
|
||||
array|null $ignore = null
|
||||
): Route {
|
||||
if (isset($this->routes[$method]) === false) {
|
||||
throw new InvalidArgumentException('Invalid routing method: ' . $method, 400);
|
||||
}
|
||||
|
||||
// remove leading and trailing slashes
|
||||
$path = trim($path, '/');
|
||||
|
||||
foreach ($this->routes[$method] as $route) {
|
||||
$arguments = $route->parse($route->pattern(), $path);
|
||||
|
||||
if ($arguments !== false) {
|
||||
if (
|
||||
empty($ignore) === true ||
|
||||
in_array($route, $ignore) === false
|
||||
) {
|
||||
return $this->route = $route;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('No route found for path: "' . $path . '" and request method: "' . $method . '"', 404);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current route.
|
||||
* This will only return something,
|
||||
* once Router::find() has been called
|
||||
* and only if a route was found.
|
||||
*/
|
||||
public function route(): Route|null
|
||||
{
|
||||
return $this->route;
|
||||
}
|
||||
}
|
||||
514
kirby/src/Http/Uri.php
Normal file
514
kirby/src/Http/Uri.php
Normal file
@@ -0,0 +1,514 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Exception\InvalidArgumentException;
|
||||
use SensitiveParameter;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Uri builder class
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Uri
|
||||
{
|
||||
/**
|
||||
* Cache for the current Uri object
|
||||
*/
|
||||
public static Uri|null $current = null;
|
||||
|
||||
/**
|
||||
* The fragment after the hash
|
||||
*/
|
||||
protected string|false|null $fragment;
|
||||
|
||||
/**
|
||||
* The host address
|
||||
*/
|
||||
protected string|null $host;
|
||||
|
||||
/**
|
||||
* The optional password for basic authentication
|
||||
*/
|
||||
protected string|false|null $password;
|
||||
|
||||
/**
|
||||
* The optional list of params
|
||||
*/
|
||||
protected Params $params;
|
||||
|
||||
/**
|
||||
* The optional path
|
||||
*/
|
||||
protected Path $path;
|
||||
|
||||
/**
|
||||
* The optional port number
|
||||
*/
|
||||
protected int|false|null $port;
|
||||
|
||||
/**
|
||||
* All original properties
|
||||
*/
|
||||
protected array $props;
|
||||
|
||||
/**
|
||||
* The optional query string without leading ?
|
||||
*/
|
||||
protected Query $query;
|
||||
|
||||
/**
|
||||
* https or http
|
||||
*/
|
||||
protected string|null $scheme;
|
||||
|
||||
/**
|
||||
* Supported schemes
|
||||
*/
|
||||
protected static array $schemes = ['http', 'https', 'ftp'];
|
||||
|
||||
protected bool $slash;
|
||||
|
||||
/**
|
||||
* The optional username for basic authentication
|
||||
*/
|
||||
protected string|false|null $username = null;
|
||||
|
||||
/**
|
||||
* Creates a new URI object
|
||||
*
|
||||
* @param array $inject Additional props to inject if a URL string is passed
|
||||
*/
|
||||
public function __construct(array|string $props = [], array $inject = [])
|
||||
{
|
||||
if (is_string($props) === true) {
|
||||
$props = parse_url($props);
|
||||
$props['username'] = $props['user'] ?? null;
|
||||
$props['password'] = $props['pass'] ?? null;
|
||||
|
||||
$props = array_merge($props, $inject);
|
||||
}
|
||||
|
||||
// parse the path and extract params
|
||||
if (empty($props['path']) === false) {
|
||||
$props = static::parsePath($props);
|
||||
}
|
||||
|
||||
$this->props = $props;
|
||||
$this->setFragment($props['fragment'] ?? null);
|
||||
$this->setHost($props['host'] ?? null);
|
||||
$this->setParams($props['params'] ?? null);
|
||||
$this->setPassword($props['password'] ?? null);
|
||||
$this->setPath($props['path'] ?? null);
|
||||
$this->setPort($props['port'] ?? null);
|
||||
$this->setQuery($props['query'] ?? null);
|
||||
$this->setScheme($props['scheme'] ?? 'http');
|
||||
$this->setSlash($props['slash'] ?? false);
|
||||
$this->setUsername($props['username'] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic caller to access all properties
|
||||
*/
|
||||
public function __call(string $property, array $arguments = [])
|
||||
{
|
||||
return $this->$property ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure that cloning also clones
|
||||
* the path and query objects
|
||||
*/
|
||||
public function __clone()
|
||||
{
|
||||
$this->path = clone $this->path;
|
||||
$this->query = clone $this->query;
|
||||
$this->params = clone $this->params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic getter
|
||||
*/
|
||||
public function __get(string $property)
|
||||
{
|
||||
return $this->$property ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic setter
|
||||
*/
|
||||
public function __set(string $property, $value): void
|
||||
{
|
||||
if (method_exists($this, 'set' . $property) === true) {
|
||||
$this->{'set' . $property}($value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the URL object to string
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
try {
|
||||
return $this->toString();
|
||||
} catch (Throwable) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the auth details (username:password)
|
||||
*/
|
||||
public function auth(): string|null
|
||||
{
|
||||
$auth = trim($this->username . ':' . $this->password);
|
||||
return $auth !== ':' ? $auth : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base url (scheme + host)
|
||||
* without trailing slash
|
||||
*/
|
||||
public function base(): string|null
|
||||
{
|
||||
if ($domain = $this->domain()) {
|
||||
return $this->scheme ? $this->scheme . '://' . $domain : $domain;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clones the Uri object and applies optional
|
||||
* new props.
|
||||
*/
|
||||
public function clone(array $props = []): static
|
||||
{
|
||||
$clone = clone $this;
|
||||
|
||||
foreach ($props as $key => $value) {
|
||||
$clone->__set($key, $value);
|
||||
}
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
public static function current(array $props = []): static
|
||||
{
|
||||
if (static::$current !== null) {
|
||||
return static::$current;
|
||||
}
|
||||
|
||||
if ($app = App::instance(null, true)) {
|
||||
$environment = $app->environment();
|
||||
} else {
|
||||
$environment = new Environment();
|
||||
}
|
||||
|
||||
return new static($environment->requestUrl(), $props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the domain without scheme, path or query.
|
||||
* Includes auth part when not empty.
|
||||
* Includes port number when different from 80 or 443.
|
||||
*/
|
||||
public function domain(): string|null
|
||||
{
|
||||
if (empty($this->host) === true || $this->host === '/') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$auth = $this->auth();
|
||||
$domain = '';
|
||||
|
||||
if ($auth !== null) {
|
||||
$domain .= $auth . '@';
|
||||
}
|
||||
|
||||
$domain .= $this->host;
|
||||
|
||||
if (
|
||||
$this->port !== null &&
|
||||
in_array($this->port, [80, 443]) === false
|
||||
) {
|
||||
$domain .= ':' . $this->port;
|
||||
}
|
||||
|
||||
return $domain;
|
||||
}
|
||||
|
||||
public function hasFragment(): bool
|
||||
{
|
||||
return empty($this->fragment) === false;
|
||||
}
|
||||
|
||||
public function hasPath(): bool
|
||||
{
|
||||
return $this->path()->isNotEmpty();
|
||||
}
|
||||
|
||||
public function hasQuery(): bool
|
||||
{
|
||||
return $this->query()->isNotEmpty();
|
||||
}
|
||||
|
||||
public function https(): bool
|
||||
{
|
||||
return $this->scheme() === 'https';
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to convert the internationalized host
|
||||
* name to the human-readable UTF8 representation
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function idn(): static
|
||||
{
|
||||
if (empty($this->host) === false) {
|
||||
$this->setHost(Idn::decode($this->host));
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an Uri object for the URL to the index.php
|
||||
* or any other executed script.
|
||||
*/
|
||||
public static function index(array $props = []): static
|
||||
{
|
||||
if ($app = App::instance(null, true)) {
|
||||
$url = $app->url('index');
|
||||
} else {
|
||||
$url = (new Environment())->baseUrl();
|
||||
}
|
||||
|
||||
return new static($url, $props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the host exists
|
||||
*/
|
||||
public function isAbsolute(): bool
|
||||
{
|
||||
return empty($this->host) === false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setFragment(string|null $fragment = null): static
|
||||
{
|
||||
$this->fragment = $fragment ? ltrim($fragment, '#') : null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setHost(string|null $host = null): static
|
||||
{
|
||||
$this->host = $host;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setParams(Params|string|array|false|null $params = null): static
|
||||
{
|
||||
// ensure that the special constructor value of `false`
|
||||
// is never passed through as it's not supported by `Params`
|
||||
if ($params === false) {
|
||||
$params = [];
|
||||
}
|
||||
|
||||
$this->params = $params instanceof Params ? $params : new Params($params);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setPassword(
|
||||
#[SensitiveParameter]
|
||||
string|null $password = null
|
||||
): static {
|
||||
$this->password = $password;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setPath(Path|string|array|null $path = null): static
|
||||
{
|
||||
$this->path = $path instanceof Path ? $path : new Path($path);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setPort(int|null $port = null): static
|
||||
{
|
||||
if ($port === 0) {
|
||||
$port = null;
|
||||
}
|
||||
|
||||
if ($port !== null) {
|
||||
if ($port < 1 || $port > 65535) {
|
||||
throw new InvalidArgumentException('Invalid port format: ' . $port);
|
||||
}
|
||||
}
|
||||
|
||||
$this->port = $port;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setQuery(Query|string|array|null $query = null): static
|
||||
{
|
||||
$this->query = $query instanceof Query ? $query : new Query($query);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setScheme(string|null $scheme = null): static
|
||||
{
|
||||
if ($scheme !== null && in_array($scheme, static::$schemes) === false) {
|
||||
throw new InvalidArgumentException('Invalid URL scheme: ' . $scheme);
|
||||
}
|
||||
|
||||
$this->scheme = $scheme;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set if a trailing slash should be added to
|
||||
* the path when the URI is being built
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setSlash(bool $slash = false): static
|
||||
{
|
||||
$this->slash = $slash;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function setUsername(string|null $username = null): static
|
||||
{
|
||||
$this->username = $username;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the Url object to an array
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$array = [];
|
||||
|
||||
foreach ($this->props as $key => $value) {
|
||||
$value = $this->$key;
|
||||
|
||||
if (is_object($value) === true) {
|
||||
$value = $value->toArray();
|
||||
}
|
||||
|
||||
$array[$key] = $value;
|
||||
}
|
||||
|
||||
return $array;
|
||||
}
|
||||
|
||||
public function toJson(...$arguments): string
|
||||
{
|
||||
return json_encode($this->toArray(), ...$arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the full URL as string
|
||||
*/
|
||||
public function toString(): string
|
||||
{
|
||||
$url = $this->base();
|
||||
$slash = true;
|
||||
|
||||
if (empty($url) === true) {
|
||||
$url = '/';
|
||||
$slash = false;
|
||||
}
|
||||
|
||||
$path = $this->path->toString($slash) . $this->params->toString(true);
|
||||
|
||||
if ($this->slash && $slash === true) {
|
||||
$path .= '/';
|
||||
}
|
||||
|
||||
$url .= $path;
|
||||
$url .= $this->query->toString(true);
|
||||
|
||||
if (empty($this->fragment) === false) {
|
||||
$url .= '#' . $this->fragment;
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to convert a URL with an internationalized host
|
||||
* name to the machine-readable Punycode representation
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function unIdn(): static
|
||||
{
|
||||
if (empty($this->host) === false) {
|
||||
$this->setHost(Idn::encode($this->host));
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the path inside the props and extracts
|
||||
* the params unless disabled
|
||||
*
|
||||
* @return array Modified props array
|
||||
*/
|
||||
protected static function parsePath(array $props): array
|
||||
{
|
||||
// extract params, the rest is the path;
|
||||
// only do this if not explicitly disabled (set to `false`)
|
||||
if (isset($props['params']) === false || $props['params'] !== false) {
|
||||
$extract = Params::extract($props['path']);
|
||||
$props['params'] ??= $extract['params'];
|
||||
$props['path'] = $extract['path'];
|
||||
$props['slash'] ??= $extract['slash'];
|
||||
|
||||
return $props;
|
||||
}
|
||||
|
||||
// use the full path;
|
||||
// automatically detect the trailing slash from it if possible
|
||||
if (is_string($props['path']) === true) {
|
||||
$props['slash'] = substr($props['path'], -1, 1) === '/';
|
||||
}
|
||||
|
||||
return $props;
|
||||
}
|
||||
}
|
||||
249
kirby/src/Http/Url.php
Normal file
249
kirby/src/Http/Url.php
Normal file
@@ -0,0 +1,249 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* Static URL tools
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Url
|
||||
{
|
||||
/**
|
||||
* The base Url to build absolute Urls from
|
||||
*/
|
||||
public static string|null $home = '/';
|
||||
|
||||
/**
|
||||
* The current Uri object as string
|
||||
*/
|
||||
public static string|null $current = null;
|
||||
|
||||
/**
|
||||
* Facade for all Uri object methods
|
||||
*/
|
||||
public static function __callStatic(string $method, array $arguments)
|
||||
{
|
||||
$uri = new Uri($arguments[0] ?? static::current());
|
||||
return $uri->$method(...array_slice($arguments, 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Url Builder
|
||||
* Actually just a factory for `new Uri($parts)`
|
||||
*/
|
||||
public static function build(
|
||||
array $parts = [],
|
||||
string|null $url = null
|
||||
): string {
|
||||
$url ??= static::current();
|
||||
$uri = new Uri($url);
|
||||
return $uri->clone($parts)->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current url with all bells and whistles
|
||||
*/
|
||||
public static function current(): string
|
||||
{
|
||||
return static::$current ??= static::toObject()->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the url for the current directory
|
||||
*/
|
||||
public static function currentDir(): string
|
||||
{
|
||||
return dirname(static::current());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to fix a broken url without protocol
|
||||
* @psalm-return ($url is null ? string|null : string)
|
||||
*/
|
||||
public static function fix(string|null $url = null): string|null
|
||||
{
|
||||
// make sure to not touch absolute urls
|
||||
if (!preg_match('!^(https|http|ftp)\:\/\/!i', $url ?? '')) {
|
||||
return 'http://' . $url;
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the home url if defined
|
||||
*/
|
||||
public static function home(): string
|
||||
{
|
||||
return static::$home;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the url to the executed script
|
||||
*/
|
||||
public static function index(array $props = []): string
|
||||
{
|
||||
return Uri::index($props)->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an URL is absolute
|
||||
*/
|
||||
public static function isAbsolute(string|null $url = null): bool
|
||||
{
|
||||
// matches the following groups of URLs:
|
||||
// //example.com/uri
|
||||
// http://example.com/uri, https://example.com/uri, ftp://example.com/uri
|
||||
// mailto:example@example.com, geo:49.0158,8.3239?z=11
|
||||
return
|
||||
$url !== null &&
|
||||
preg_match('!^(//|[a-z0-9+-.]+://|mailto:|tel:|geo:)!i', $url) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a relative path into an absolute URL
|
||||
*/
|
||||
public static function makeAbsolute(string|null $path = null, string|null $home = null): string
|
||||
{
|
||||
if ($path === '' || $path === '/' || $path === null) {
|
||||
return $home ?? static::home();
|
||||
}
|
||||
|
||||
if (substr($path, 0, 1) === '#') {
|
||||
return $path;
|
||||
}
|
||||
|
||||
if (static::isAbsolute($path)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
// build the full url
|
||||
$path = ltrim($path, '/');
|
||||
$home ??= static::home();
|
||||
|
||||
if (empty($path) === true) {
|
||||
return $home;
|
||||
}
|
||||
|
||||
return $home === '/' ? '/' . $path : $home . '/' . $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path for the given url
|
||||
*/
|
||||
public static function path(
|
||||
string|array|null $url = null,
|
||||
bool $leadingSlash = false,
|
||||
bool $trailingSlash = false
|
||||
): string {
|
||||
return Url::toObject($url)
|
||||
->path()
|
||||
->toString($leadingSlash, $trailingSlash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the query for the given url
|
||||
*/
|
||||
public static function query(string|array|null $url = null): string
|
||||
{
|
||||
return Url::toObject($url)->query()->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the last url the user has been on if detectable
|
||||
*/
|
||||
public static function last(): string
|
||||
{
|
||||
return Environment::getGlobally('HTTP_REFERER', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortens the Url by removing all unnecessary parts
|
||||
*/
|
||||
public static function short(
|
||||
string|null $url = null,
|
||||
int $length = 0,
|
||||
bool $base = false,
|
||||
string $rep = '…'
|
||||
): string {
|
||||
$uri = static::toObject($url);
|
||||
|
||||
$uri->fragment = null;
|
||||
$uri->query = null;
|
||||
$uri->password = null;
|
||||
$uri->port = null;
|
||||
$uri->scheme = null;
|
||||
$uri->username = null;
|
||||
|
||||
// remove the trailing slash from the path
|
||||
$uri->slash = false;
|
||||
|
||||
$url = $base ? $uri->base() : $uri->toString();
|
||||
$url = str_replace('www.', '', $url ?? '');
|
||||
|
||||
return Str::short($url, $length, $rep);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the path from the Url
|
||||
*/
|
||||
public static function stripPath(string|null $url = null): string
|
||||
{
|
||||
return static::toObject($url)->setPath(null)->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the query string from the Url
|
||||
*/
|
||||
public static function stripQuery(string|null $url = null): string
|
||||
{
|
||||
return static::toObject($url)->setQuery(null)->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the fragment (hash) from the Url
|
||||
*/
|
||||
public static function stripFragment(string|null $url = null): string
|
||||
{
|
||||
return static::toObject($url)->setFragment(null)->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Smart resolver for internal and external urls
|
||||
*/
|
||||
public static function to(
|
||||
string|null $path = null,
|
||||
array $options = null
|
||||
): string {
|
||||
// make sure $path is string
|
||||
$path ??= '';
|
||||
|
||||
// keep relative urls
|
||||
if (substr($path, 0, 2) === './' || substr($path, 0, 3) === '../') {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$url = static::makeAbsolute($path);
|
||||
|
||||
if ($options === null) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
return (new Uri($url, $options))->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the Url to a Uri object
|
||||
*/
|
||||
public static function toObject(string|null $url = null): Uri
|
||||
{
|
||||
return $url === null ? Uri::current() : new Uri($url);
|
||||
}
|
||||
}
|
||||
229
kirby/src/Http/Visitor.php
Normal file
229
kirby/src/Http/Visitor.php
Normal file
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
namespace Kirby\Http;
|
||||
|
||||
use Kirby\Filesystem\Mime;
|
||||
use Kirby\Toolkit\Collection;
|
||||
use Kirby\Toolkit\Obj;
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* The Visitor class makes it easy to inspect information
|
||||
* like the ip address, language, user agent and more
|
||||
* of the current visitor
|
||||
*
|
||||
* @package Kirby Http
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Visitor
|
||||
{
|
||||
protected string|null $ip = null;
|
||||
protected string|null $userAgent = null;
|
||||
protected string|null $acceptedLanguage = null;
|
||||
protected string|null $acceptedMimeType = null;
|
||||
|
||||
/**
|
||||
* Creates a new visitor object.
|
||||
* Optional arguments can be passed to
|
||||
* modify the information about the visitor.
|
||||
*
|
||||
* By default everything is pulled from $_SERVER
|
||||
*/
|
||||
public function __construct(array $arguments = [])
|
||||
{
|
||||
$ip = $arguments['ip'] ?? null;
|
||||
$ip ??= Environment::getGlobally('REMOTE_ADDR', '');
|
||||
$agent = $arguments['userAgent'] ?? null;
|
||||
$agent ??= Environment::getGlobally('HTTP_USER_AGENT', '');
|
||||
$language = $arguments['acceptedLanguage'] ?? null;
|
||||
$language ??= Environment::getGlobally('HTTP_ACCEPT_LANGUAGE', '');
|
||||
$mime = $arguments['acceptedMimeType'] ?? null;
|
||||
$mime ??= Environment::getGlobally('HTTP_ACCEPT', '');
|
||||
|
||||
$this->ip($ip);
|
||||
$this->userAgent($agent);
|
||||
$this->acceptedLanguage($language);
|
||||
$this->acceptedMimeType($mime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the accepted language if
|
||||
* provided or returns the user's
|
||||
* accepted language otherwise
|
||||
*
|
||||
* @return $this|\Kirby\Toolkit\Obj|null
|
||||
*/
|
||||
public function acceptedLanguage(
|
||||
string|null $acceptedLanguage = null
|
||||
): static|Obj|null {
|
||||
if ($acceptedLanguage === null) {
|
||||
return $this->acceptedLanguages()->first();
|
||||
}
|
||||
|
||||
$this->acceptedLanguage = $acceptedLanguage;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of all accepted languages
|
||||
* including their quality and locale
|
||||
*/
|
||||
public function acceptedLanguages(): Collection
|
||||
{
|
||||
$accepted = Str::accepted($this->acceptedLanguage);
|
||||
$languages = [];
|
||||
|
||||
foreach ($accepted as $language) {
|
||||
$value = $language['value'];
|
||||
$parts = Str::split($value, '-');
|
||||
$code = isset($parts[0]) ? Str::lower($parts[0]) : null;
|
||||
$region = isset($parts[1]) ? Str::upper($parts[1]) : null;
|
||||
$locale = $region ? $code . '_' . $region : $code;
|
||||
|
||||
$languages[$locale] = new Obj([
|
||||
'code' => $code,
|
||||
'locale' => $locale,
|
||||
'original' => $value,
|
||||
'quality' => $language['quality'],
|
||||
'region' => $region,
|
||||
]);
|
||||
}
|
||||
|
||||
return new Collection($languages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user accepts the given language
|
||||
*/
|
||||
public function acceptsLanguage(string $code): bool
|
||||
{
|
||||
$mode = Str::contains($code, '_') === true ? 'locale' : 'code';
|
||||
|
||||
foreach ($this->acceptedLanguages() as $language) {
|
||||
if ($language->$mode() === $code) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the accepted mime type if
|
||||
* provided or returns the user's
|
||||
* accepted mime type otherwise
|
||||
*
|
||||
* @return $this|\Kirby\Toolkit\Obj|null
|
||||
*/
|
||||
public function acceptedMimeType(
|
||||
string|null $acceptedMimeType = null
|
||||
): static|Obj|null {
|
||||
if ($acceptedMimeType === null) {
|
||||
return $this->acceptedMimeTypes()->first();
|
||||
}
|
||||
|
||||
$this->acceptedMimeType = $acceptedMimeType;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a collection of all accepted mime types
|
||||
*/
|
||||
public function acceptedMimeTypes(): Collection
|
||||
{
|
||||
$accepted = Str::accepted($this->acceptedMimeType);
|
||||
$mimes = [];
|
||||
|
||||
foreach ($accepted as $mime) {
|
||||
$mimes[$mime['value']] = new Obj([
|
||||
'type' => $mime['value'],
|
||||
'quality' => $mime['quality'],
|
||||
]);
|
||||
}
|
||||
|
||||
return new Collection($mimes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user accepts the given mime type
|
||||
*/
|
||||
public function acceptsMimeType(string $mimeType): bool
|
||||
{
|
||||
return Mime::isAccepted($mimeType, $this->acceptedMimeType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the MIME type from the provided list that
|
||||
* is most accepted (= preferred) by the visitor
|
||||
* @since 3.3.0
|
||||
*
|
||||
* @param string ...$mimeTypes MIME types to query for
|
||||
* @return string|null Preferred MIME type
|
||||
*/
|
||||
public function preferredMimeType(string ...$mimeTypes): string|null
|
||||
{
|
||||
foreach ($this->acceptedMimeTypes() as $acceptedMime) {
|
||||
// look for direct matches
|
||||
if (in_array($acceptedMime->type(), $mimeTypes)) {
|
||||
return $acceptedMime->type();
|
||||
}
|
||||
|
||||
// test each option against wildcard `Accept` values
|
||||
foreach ($mimeTypes as $expectedMime) {
|
||||
if (Mime::matches($expectedMime, $acceptedMime->type()) === true) {
|
||||
return $expectedMime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the visitor prefers a JSON response over
|
||||
* an HTML response based on the `Accept` request header
|
||||
* @since 3.3.0
|
||||
*/
|
||||
public function prefersJson(): bool
|
||||
{
|
||||
$preferred = $this->preferredMimeType('application/json', 'text/html');
|
||||
return $preferred === 'application/json';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the ip address if provided
|
||||
* or returns the ip of the current
|
||||
* visitor otherwise
|
||||
*
|
||||
* @return $this|string|null
|
||||
*/
|
||||
public function ip(string|null $ip = null): static|string|null
|
||||
{
|
||||
if ($ip === null) {
|
||||
return $this->ip;
|
||||
}
|
||||
|
||||
$this->ip = $ip;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the user agent if provided
|
||||
* or returns the user agent string of
|
||||
* the current visitor otherwise
|
||||
*
|
||||
* @return $this|string|null
|
||||
*/
|
||||
public function userAgent(string|null $userAgent = null): static|string|null
|
||||
{
|
||||
if ($userAgent === null) {
|
||||
return $this->userAgent;
|
||||
}
|
||||
|
||||
$this->userAgent = $userAgent;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user