commit version 22.12.12447

This commit is contained in:
2023-01-01 22:36:12 -05:00
parent af1b03d79f
commit b948283a96
744 changed files with 620715 additions and 27381 deletions

View File

@ -0,0 +1,320 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
use flight\util\Collection;
/**
* The Request class represents an HTTP request. Data from
* all the super globals $_GET, $_POST, $_COOKIE, and $_FILES
* are stored and accessible via the Request object.
*
* The default request properties are:
* url - The URL being requested
* base - The parent subdirectory of the URL
* method - The request method (GET, POST, PUT, DELETE)
* referrer - The referrer URL
* ip - IP address of the client
* ajax - Whether the request is an AJAX request
* scheme - The server protocol (http, https)
* user_agent - Browser information
* type - The content type
* length - The content length
* query - Query string parameters
* data - Post parameters
* cookies - Cookie parameters
* files - Uploaded files
* secure - Connection is secure
* accept - HTTP accept parameters
* proxy_ip - Proxy IP address of the client
*/
final class Request
{
/**
* @var string URL being requested
*/
public string $url;
/**
* @var string Parent subdirectory of the URL
*/
public string $base;
/**
* @var string Request method (GET, POST, PUT, DELETE)
*/
public string $method;
/**
* @var string Referrer URL
*/
public string $referrer;
/**
* @var string IP address of the client
*/
public string $ip;
/**
* @var bool Whether the request is an AJAX request
*/
public bool $ajax;
/**
* @var string Server protocol (http, https)
*/
public string $scheme;
/**
* @var string Browser information
*/
public string $user_agent;
/**
* @var string Content type
*/
public string $type;
/**
* @var int Content length
*/
public int $length;
/**
* @var Collection Query string parameters
*/
public Collection $query;
/**
* @var Collection Post parameters
*/
public Collection $data;
/**
* @var Collection Cookie parameters
*/
public Collection $cookies;
/**
* @var Collection Uploaded files
*/
public Collection $files;
/**
* @var bool Whether the connection is secure
*/
public bool $secure;
/**
* @var string HTTP accept parameters
*/
public string $accept;
/**
* @var string Proxy IP address of the client
*/
public string $proxy_ip;
/**
* @var string HTTP host name
*/
public string $host;
/**
* Constructor.
*
* @param array $config Request configuration
*/
public function __construct(array $config = [])
{
// Default properties
if (empty($config)) {
$config = [
'url' => str_replace('@', '%40', self::getVar('REQUEST_URI', '/')),
'base' => str_replace(['\\', ' '], ['/', '%20'], \dirname(self::getVar('SCRIPT_NAME'))),
'method' => self::getMethod(),
'referrer' => self::getVar('HTTP_REFERER'),
'ip' => self::getVar('REMOTE_ADDR'),
'ajax' => 'XMLHttpRequest' === self::getVar('HTTP_X_REQUESTED_WITH'),
'scheme' => self::getScheme(),
'user_agent' => self::getVar('HTTP_USER_AGENT'),
'type' => self::getVar('CONTENT_TYPE'),
'length' => (int) self::getVar('CONTENT_LENGTH', 0),
'query' => new Collection($_GET),
'data' => new Collection($_POST),
'cookies' => new Collection($_COOKIE),
'files' => new Collection($_FILES),
'secure' => 'https' === self::getScheme(),
'accept' => self::getVar('HTTP_ACCEPT'),
'proxy_ip' => self::getProxyIpAddress(),
'host' => self::getVar('HTTP_HOST'),
];
}
$this->init($config);
}
/**
* Initialize request properties.
*
* @param array $properties Array of request properties
*/
public function init(array $properties = [])
{
// Set all the defined properties
foreach ($properties as $name => $value) {
$this->$name = $value;
}
// Get the requested URL without the base directory
if ('/' !== $this->base && '' !== $this->base && 0 === strpos($this->url, $this->base)) {
$this->url = substr($this->url, \strlen($this->base));
}
// Default url
if (empty($this->url)) {
$this->url = '/';
} else {
// Merge URL query parameters with $_GET
$_GET = array_merge($_GET, self::parseQuery($this->url));
$this->query->setData($_GET);
}
// Check for JSON input
if (0 === strpos($this->type, 'application/json')) {
$body = self::getBody();
if ('' !== $body && null !== $body) {
$data = json_decode($body, true);
if (is_array($data)) {
$this->data->setData($data);
}
}
}
}
/**
* Gets the body of the request.
*
* @return string Raw HTTP request body
*/
public static function getBody(): ?string
{
static $body;
if (null !== $body) {
return $body;
}
$method = self::getMethod();
if ('POST' === $method || 'PUT' === $method || 'DELETE' === $method || 'PATCH' === $method) {
$body = file_get_contents('php://input');
}
return $body;
}
/**
* Gets the request method.
*/
public static function getMethod(): string
{
$method = self::getVar('REQUEST_METHOD', 'GET');
if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
} elseif (isset($_REQUEST['_method'])) {
$method = $_REQUEST['_method'];
}
return strtoupper($method);
}
/**
* Gets the real remote IP address.
*
* @return string IP address
*/
public static function getProxyIpAddress(): string
{
static $forwarded = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
];
$flags = \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE;
foreach ($forwarded as $key) {
if (\array_key_exists($key, $_SERVER)) {
sscanf($_SERVER[$key], '%[^,]', $ip);
if (false !== filter_var($ip, \FILTER_VALIDATE_IP, $flags)) {
return $ip;
}
}
}
return '';
}
/**
* Gets a variable from $_SERVER using $default if not provided.
*
* @param string $var Variable name
* @param mixed $default Default value to substitute
*
* @return mixed Server variable value
*/
public static function getVar(string $var, $default = '')
{
return $_SERVER[$var] ?? $default;
}
/**
* Parse query parameters from a URL.
*
* @param string $url URL string
*
* @return array Query parameters
*/
public static function parseQuery(string $url): array
{
$params = [];
$args = parse_url($url);
if (isset($args['query'])) {
parse_str($args['query'], $params);
}
return $params;
}
public static function getScheme(): string
{
if (
(isset($_SERVER['HTTPS']) && 'on' === strtolower($_SERVER['HTTPS']))
||
(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' === $_SERVER['HTTP_X_FORWARDED_PROTO'])
||
(isset($_SERVER['HTTP_FRONT_END_HTTPS']) && 'on' === $_SERVER['HTTP_FRONT_END_HTTPS'])
||
(isset($_SERVER['REQUEST_SCHEME']) && 'https' === $_SERVER['REQUEST_SCHEME'])
) {
return 'https';
}
return 'http';
}
}

View File

@ -0,0 +1,321 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
use Exception;
/**
* The Response class represents an HTTP response. The object
* contains the response headers, HTTP status code, and response
* body.
*/
class Response
{
/**
* header Content-Length.
*/
public bool $content_length = true;
/**
* @var array HTTP status codes
*/
public static array $codes = [
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '(Unused)',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large',
414 => 'URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
510 => 'Not Extended',
511 => 'Network Authentication Required',
];
/**
* @var int HTTP status
*/
protected int $status = 200;
/**
* @var array HTTP headers
*/
protected array $headers = [];
/**
* @var string HTTP response body
*/
protected string $body = '';
/**
* @var bool HTTP response sent
*/
protected bool $sent = false;
/**
* Sets the HTTP status of the response.
*
* @param int|null $code HTTP status code.
*
* @throws Exception If invalid status code
*
* @return int|object Self reference
*/
public function status(?int $code = null)
{
if (null === $code) {
return $this->status;
}
if (\array_key_exists($code, self::$codes)) {
$this->status = $code;
} else {
throw new Exception('Invalid status code.');
}
return $this;
}
/**
* Adds a header to the response.
*
* @param array|string $name Header name or array of names and values
* @param string|null $value Header value
*
* @return object Self reference
*/
public function header($name, ?string $value = null)
{
if (\is_array($name)) {
foreach ($name as $k => $v) {
$this->headers[$k] = $v;
}
} else {
$this->headers[$name] = $value;
}
return $this;
}
/**
* Returns the headers from the response.
*
* @return array
*/
public function headers()
{
return $this->headers;
}
/**
* Writes content to the response body.
*
* @param string $str Response content
*
* @return Response Self reference
*/
public function write(string $str): self
{
$this->body .= $str;
return $this;
}
/**
* Clears the response.
*
* @return Response Self reference
*/
public function clear(): self
{
$this->status = 200;
$this->headers = [];
$this->body = '';
return $this;
}
/**
* Sets caching headers for the response.
*
* @param int|string $expires Expiration time
*
* @return Response Self reference
*/
public function cache($expires): self
{
if (false === $expires) {
$this->headers['Expires'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
$this->headers['Cache-Control'] = [
'no-store, no-cache, must-revalidate',
'post-check=0, pre-check=0',
'max-age=0',
];
$this->headers['Pragma'] = 'no-cache';
} else {
$expires = \is_int($expires) ? $expires : strtotime($expires);
$this->headers['Expires'] = gmdate('D, d M Y H:i:s', $expires) . ' GMT';
$this->headers['Cache-Control'] = 'max-age=' . ($expires - time());
if (isset($this->headers['Pragma']) && 'no-cache' == $this->headers['Pragma']) {
unset($this->headers['Pragma']);
}
}
return $this;
}
/**
* Sends HTTP headers.
*
* @return Response Self reference
*/
public function sendHeaders(): self
{
// Send status code header
if (false !== strpos(\PHP_SAPI, 'cgi')) {
header(
sprintf(
'Status: %d %s',
$this->status,
self::$codes[$this->status]
),
true
);
} else {
header(
sprintf(
'%s %d %s',
$_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1',
$this->status,
self::$codes[$this->status]),
true,
$this->status
);
}
// Send other headers
foreach ($this->headers as $field => $value) {
if (\is_array($value)) {
foreach ($value as $v) {
header($field . ': ' . $v, false);
}
} else {
header($field . ': ' . $value);
}
}
if ($this->content_length) {
// Send content length
$length = $this->getContentLength();
if ($length > 0) {
header('Content-Length: ' . $length);
}
}
return $this;
}
/**
* Gets the content length.
*
* @return int Content length
*/
public function getContentLength(): int
{
return \extension_loaded('mbstring') ?
mb_strlen($this->body, 'latin1') :
\strlen($this->body);
}
/**
* Gets whether response was sent.
*/
public function sent(): bool
{
return $this->sent;
}
/**
* Sends a HTTP response.
*/
public function send(): void
{
if (ob_get_length() > 0) {
ob_end_clean();
}
if (!headers_sent()) {
$this->sendHeaders();
}
echo $this->body;
$this->sent = true;
}
}

156
libs/flight2/net/Route.php Normal file
View File

@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
/**
* The Route class is responsible for routing an HTTP request to
* an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns.
*/
final class Route
{
/**
* @var string URL pattern
*/
public string $pattern;
/**
* @var mixed Callback function
*/
public $callback;
/**
* @var array HTTP methods
*/
public array $methods = [];
/**
* @var array Route parameters
*/
public array $params = [];
/**
* @var string|null Matching regular expression
*/
public ?string $regex = null;
/**
* @var string URL splat content
*/
public string $splat = '';
/**
* @var bool Pass self in callback parameters
*/
public bool $pass = false;
/**
* Constructor.
*
* @param string $pattern URL pattern
* @param mixed $callback Callback function
* @param array $methods HTTP methods
* @param bool $pass Pass self in callback parameters
*/
public function __construct(string $pattern, $callback, array $methods, bool $pass)
{
$this->pattern = $pattern;
$this->callback = $callback;
$this->methods = $methods;
$this->pass = $pass;
}
/**
* Checks if a URL matches the route pattern. Also parses named parameters in the URL.
*
* @param string $url Requested URL
* @param bool $case_sensitive Case sensitive matching
*
* @return bool Match status
*/
public function matchUrl(string $url, bool $case_sensitive = false): bool
{
// Wildcard or exact match
if ('*' === $this->pattern || $this->pattern === $url) {
return true;
}
$ids = [];
$last_char = substr($this->pattern, -1);
// Get splat
if ('*' === $last_char) {
$n = 0;
$len = \strlen($url);
$count = substr_count($this->pattern, '/');
for ($i = 0; $i < $len; $i++) {
if ('/' === $url[$i]) {
$n++;
}
if ($n === $count) {
break;
}
}
$this->splat = (string) substr($url, $i + 1);
}
// Build the regex for matching
$regex = str_replace([')', '/*'], [')?', '(/?|/.*?)'], $this->pattern);
$regex = preg_replace_callback(
'#@([\w]+)(:([^/\(\)]*))?#',
static function ($matches) use (&$ids) {
$ids[$matches[1]] = null;
if (isset($matches[3])) {
return '(?P<' . $matches[1] . '>' . $matches[3] . ')';
}
return '(?P<' . $matches[1] . '>[^/\?]+)';
},
$regex
);
// Fix trailing slash
if ('/' === $last_char) {
$regex .= '?';
} // Allow trailing slash
else {
$regex .= '/?';
}
// Attempt to match route and named parameters
if (preg_match('#^' . $regex . '(?:\?.*)?$#' . (($case_sensitive) ? '' : 'i'), $url, $matches)) {
foreach ($ids as $k => $v) {
$this->params[$k] = (\array_key_exists($k, $matches)) ? urldecode($matches[$k]) : null;
}
$this->regex = $regex;
return true;
}
return false;
}
/**
* Checks if an HTTP method matches the route methods.
*
* @param string $method HTTP method
*
* @return bool Match status
*/
public function matchMethod(string $method): bool
{
return \count(array_intersect([$method, '*'], $this->methods)) > 0;
}
}

118
libs/flight2/net/Router.php Normal file
View File

@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
/**
* The Router class is responsible for routing an HTTP request to
* an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns.
*/
class Router
{
/**
* Case sensitive matching.
*/
public bool $case_sensitive = false;
/**
* Mapped routes.
*/
protected array $routes = [];
/**
* Pointer to current route.
*/
protected int $index = 0;
/**
* Gets mapped routes.
*
* @return array Array of routes
*/
public function getRoutes(): array
{
return $this->routes;
}
/**
* Clears all routes in the router.
*/
public function clear(): void
{
$this->routes = [];
}
/**
* Maps a URL pattern to a callback function.
*
* @param string $pattern URL pattern to match
* @param callback $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
*/
public function map(string $pattern, callable $callback, bool $pass_route = false): void
{
$url = trim($pattern);
$methods = ['*'];
if (false !== strpos($url, ' ')) {
[$method, $url] = explode(' ', $url, 2);
$url = trim($url);
$methods = explode('|', $method);
}
$this->routes[] = new Route($url, $callback, $methods, $pass_route);
}
/**
* Routes the current request.
*
* @param Request $request Request object
*
* @return bool|Route Matching route or false if no match
*/
public function route(Request $request)
{
$url_decoded = urldecode($request->url);
while ($route = $this->current()) {
if (false !== $route && $route->matchMethod($request->method) && $route->matchUrl($url_decoded, $this->case_sensitive)) {
return $route;
}
$this->next();
}
return false;
}
/**
* Gets the current route.
*
* @return bool|Route
*/
public function current()
{
return $this->routes[$this->index] ?? false;
}
/**
* Gets the next route.
*/
public function next(): void
{
$this->index++;
}
/**
* Reset to the first route.
*/
public function reset(): void
{
$this->index = 0;
}
}