Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace GuzzleHttp\Psr7;
   6  
   7  use GuzzleHttp\Psr7\Exception\MalformedUriException;
   8  use Psr\Http\Message\UriInterface;
   9  
  10  /**
  11   * PSR-7 URI implementation.
  12   *
  13   * @author Michael Dowling
  14   * @author Tobias Schultze
  15   * @author Matthew Weier O'Phinney
  16   */
  17  class Uri implements UriInterface, \JsonSerializable
  18  {
  19      /**
  20       * Absolute http and https URIs require a host per RFC 7230 Section 2.7
  21       * but in generic URIs the host can be empty. So for http(s) URIs
  22       * we apply this default host when no host is given yet to form a
  23       * valid URI.
  24       */
  25      private const HTTP_DEFAULT_HOST = 'localhost';
  26  
  27      private const DEFAULT_PORTS = [
  28          'http'  => 80,
  29          'https' => 443,
  30          'ftp' => 21,
  31          'gopher' => 70,
  32          'nntp' => 119,
  33          'news' => 119,
  34          'telnet' => 23,
  35          'tn3270' => 23,
  36          'imap' => 143,
  37          'pop' => 110,
  38          'ldap' => 389,
  39      ];
  40  
  41      /**
  42       * Unreserved characters for use in a regex.
  43       *
  44       * @link https://tools.ietf.org/html/rfc3986#section-2.3
  45       */
  46      private const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
  47  
  48      /**
  49       * Sub-delims for use in a regex.
  50       *
  51       * @link https://tools.ietf.org/html/rfc3986#section-2.2
  52       */
  53      private const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
  54      private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26'];
  55  
  56      /** @var string Uri scheme. */
  57      private $scheme = '';
  58  
  59      /** @var string Uri user info. */
  60      private $userInfo = '';
  61  
  62      /** @var string Uri host. */
  63      private $host = '';
  64  
  65      /** @var int|null Uri port. */
  66      private $port;
  67  
  68      /** @var string Uri path. */
  69      private $path = '';
  70  
  71      /** @var string Uri query string. */
  72      private $query = '';
  73  
  74      /** @var string Uri fragment. */
  75      private $fragment = '';
  76  
  77      /** @var string|null String representation */
  78      private $composedComponents;
  79  
  80      public function __construct(string $uri = '')
  81      {
  82          if ($uri !== '') {
  83              $parts = self::parse($uri);
  84              if ($parts === false) {
  85                  throw new MalformedUriException("Unable to parse URI: $uri");
  86              }
  87              $this->applyParts($parts);
  88          }
  89      }
  90      /**
  91       * UTF-8 aware \parse_url() replacement.
  92       *
  93       * The internal function produces broken output for non ASCII domain names
  94       * (IDN) when used with locales other than "C".
  95       *
  96       * On the other hand, cURL understands IDN correctly only when UTF-8 locale
  97       * is configured ("C.UTF-8", "en_US.UTF-8", etc.).
  98       *
  99       * @see https://bugs.php.net/bug.php?id=52923
 100       * @see https://www.php.net/manual/en/function.parse-url.php#114817
 101       * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING
 102       *
 103       * @return array|false
 104       */
 105      private static function parse(string $url)
 106      {
 107          // If IPv6
 108          $prefix = '';
 109          if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) {
 110              /** @var array{0:string, 1:string, 2:string} $matches */
 111              $prefix = $matches[1];
 112              $url = $matches[2];
 113          }
 114  
 115          /** @var string */
 116          $encodedUrl = preg_replace_callback(
 117              '%[^:/@?&=#]+%usD',
 118              static function ($matches) {
 119                  return urlencode($matches[0]);
 120              },
 121              $url
 122          );
 123  
 124          $result = parse_url($prefix . $encodedUrl);
 125  
 126          if ($result === false) {
 127              return false;
 128          }
 129  
 130          return array_map('urldecode', $result);
 131      }
 132  
 133      public function __toString(): string
 134      {
 135          if ($this->composedComponents === null) {
 136              $this->composedComponents = self::composeComponents(
 137                  $this->scheme,
 138                  $this->getAuthority(),
 139                  $this->path,
 140                  $this->query,
 141                  $this->fragment
 142              );
 143          }
 144  
 145          return $this->composedComponents;
 146      }
 147  
 148      /**
 149       * Composes a URI reference string from its various components.
 150       *
 151       * Usually this method does not need to be called manually but instead is used indirectly via
 152       * `Psr\Http\Message\UriInterface::__toString`.
 153       *
 154       * PSR-7 UriInterface treats an empty component the same as a missing component as
 155       * getQuery(), getFragment() etc. always return a string. This explains the slight
 156       * difference to RFC 3986 Section 5.3.
 157       *
 158       * Another adjustment is that the authority separator is added even when the authority is missing/empty
 159       * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with
 160       * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But
 161       * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
 162       * that format).
 163       *
 164       * @link https://tools.ietf.org/html/rfc3986#section-5.3
 165       */
 166      public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string
 167      {
 168          $uri = '';
 169  
 170          // weak type checks to also accept null until we can add scalar type hints
 171          if ($scheme != '') {
 172              $uri .= $scheme . ':';
 173          }
 174  
 175          if ($authority != '' || $scheme === 'file') {
 176              $uri .= '//' . $authority;
 177          }
 178  
 179          if ($authority != '' && $path != '' && $path[0] != '/') {
 180              $path = '/' . $path;
 181          }
 182  
 183          $uri .= $path;
 184  
 185          if ($query != '') {
 186              $uri .= '?' . $query;
 187          }
 188  
 189          if ($fragment != '') {
 190              $uri .= '#' . $fragment;
 191          }
 192  
 193          return $uri;
 194      }
 195  
 196      /**
 197       * Whether the URI has the default port of the current scheme.
 198       *
 199       * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used
 200       * independently of the implementation.
 201       */
 202      public static function isDefaultPort(UriInterface $uri): bool
 203      {
 204          return $uri->getPort() === null
 205              || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]);
 206      }
 207  
 208      /**
 209       * Whether the URI is absolute, i.e. it has a scheme.
 210       *
 211       * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
 212       * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
 213       * to another URI, the base URI. Relative references can be divided into several forms:
 214       * - network-path references, e.g. '//example.com/path'
 215       * - absolute-path references, e.g. '/path'
 216       * - relative-path references, e.g. 'subpath'
 217       *
 218       * @see Uri::isNetworkPathReference
 219       * @see Uri::isAbsolutePathReference
 220       * @see Uri::isRelativePathReference
 221       * @link https://tools.ietf.org/html/rfc3986#section-4
 222       */
 223      public static function isAbsolute(UriInterface $uri): bool
 224      {
 225          return $uri->getScheme() !== '';
 226      }
 227  
 228      /**
 229       * Whether the URI is a network-path reference.
 230       *
 231       * A relative reference that begins with two slash characters is termed an network-path reference.
 232       *
 233       * @link https://tools.ietf.org/html/rfc3986#section-4.2
 234       */
 235      public static function isNetworkPathReference(UriInterface $uri): bool
 236      {
 237          return $uri->getScheme() === '' && $uri->getAuthority() !== '';
 238      }
 239  
 240      /**
 241       * Whether the URI is a absolute-path reference.
 242       *
 243       * A relative reference that begins with a single slash character is termed an absolute-path reference.
 244       *
 245       * @link https://tools.ietf.org/html/rfc3986#section-4.2
 246       */
 247      public static function isAbsolutePathReference(UriInterface $uri): bool
 248      {
 249          return $uri->getScheme() === ''
 250              && $uri->getAuthority() === ''
 251              && isset($uri->getPath()[0])
 252              && $uri->getPath()[0] === '/';
 253      }
 254  
 255      /**
 256       * Whether the URI is a relative-path reference.
 257       *
 258       * A relative reference that does not begin with a slash character is termed a relative-path reference.
 259       *
 260       * @link https://tools.ietf.org/html/rfc3986#section-4.2
 261       */
 262      public static function isRelativePathReference(UriInterface $uri): bool
 263      {
 264          return $uri->getScheme() === ''
 265              && $uri->getAuthority() === ''
 266              && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/');
 267      }
 268  
 269      /**
 270       * Whether the URI is a same-document reference.
 271       *
 272       * A same-document reference refers to a URI that is, aside from its fragment
 273       * component, identical to the base URI. When no base URI is given, only an empty
 274       * URI reference (apart from its fragment) is considered a same-document reference.
 275       *
 276       * @param UriInterface      $uri  The URI to check
 277       * @param UriInterface|null $base An optional base URI to compare against
 278       *
 279       * @link https://tools.ietf.org/html/rfc3986#section-4.4
 280       */
 281      public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool
 282      {
 283          if ($base !== null) {
 284              $uri = UriResolver::resolve($base, $uri);
 285  
 286              return ($uri->getScheme() === $base->getScheme())
 287                  && ($uri->getAuthority() === $base->getAuthority())
 288                  && ($uri->getPath() === $base->getPath())
 289                  && ($uri->getQuery() === $base->getQuery());
 290          }
 291  
 292          return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === '';
 293      }
 294  
 295      /**
 296       * Creates a new URI with a specific query string value removed.
 297       *
 298       * Any existing query string values that exactly match the provided key are
 299       * removed.
 300       *
 301       * @param UriInterface $uri URI to use as a base.
 302       * @param string       $key Query string key to remove.
 303       */
 304      public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface
 305      {
 306          $result = self::getFilteredQueryString($uri, [$key]);
 307  
 308          return $uri->withQuery(implode('&', $result));
 309      }
 310  
 311      /**
 312       * Creates a new URI with a specific query string value.
 313       *
 314       * Any existing query string values that exactly match the provided key are
 315       * removed and replaced with the given key value pair.
 316       *
 317       * A value of null will set the query string key without a value, e.g. "key"
 318       * instead of "key=value".
 319       *
 320       * @param UriInterface $uri   URI to use as a base.
 321       * @param string       $key   Key to set.
 322       * @param string|null  $value Value to set
 323       */
 324      public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface
 325      {
 326          $result = self::getFilteredQueryString($uri, [$key]);
 327  
 328          $result[] = self::generateQueryString($key, $value);
 329  
 330          return $uri->withQuery(implode('&', $result));
 331      }
 332  
 333      /**
 334       * Creates a new URI with multiple specific query string values.
 335       *
 336       * It has the same behavior as withQueryValue() but for an associative array of key => value.
 337       *
 338       * @param UriInterface               $uri           URI to use as a base.
 339       * @param array<string, string|null> $keyValueArray Associative array of key and values
 340       */
 341      public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface
 342      {
 343          $result = self::getFilteredQueryString($uri, array_keys($keyValueArray));
 344  
 345          foreach ($keyValueArray as $key => $value) {
 346              $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null);
 347          }
 348  
 349          return $uri->withQuery(implode('&', $result));
 350      }
 351  
 352      /**
 353       * Creates a URI from a hash of `parse_url` components.
 354       *
 355       * @link http://php.net/manual/en/function.parse-url.php
 356       *
 357       * @throws MalformedUriException If the components do not form a valid URI.
 358       */
 359      public static function fromParts(array $parts): UriInterface
 360      {
 361          $uri = new self();
 362          $uri->applyParts($parts);
 363          $uri->validateState();
 364  
 365          return $uri;
 366      }
 367  
 368      public function getScheme(): string
 369      {
 370          return $this->scheme;
 371      }
 372  
 373      public function getAuthority(): string
 374      {
 375          $authority = $this->host;
 376          if ($this->userInfo !== '') {
 377              $authority = $this->userInfo . '@' . $authority;
 378          }
 379  
 380          if ($this->port !== null) {
 381              $authority .= ':' . $this->port;
 382          }
 383  
 384          return $authority;
 385      }
 386  
 387      public function getUserInfo(): string
 388      {
 389          return $this->userInfo;
 390      }
 391  
 392      public function getHost(): string
 393      {
 394          return $this->host;
 395      }
 396  
 397      public function getPort(): ?int
 398      {
 399          return $this->port;
 400      }
 401  
 402      public function getPath(): string
 403      {
 404          return $this->path;
 405      }
 406  
 407      public function getQuery(): string
 408      {
 409          return $this->query;
 410      }
 411  
 412      public function getFragment(): string
 413      {
 414          return $this->fragment;
 415      }
 416  
 417      public function withScheme($scheme): UriInterface
 418      {
 419          $scheme = $this->filterScheme($scheme);
 420  
 421          if ($this->scheme === $scheme) {
 422              return $this;
 423          }
 424  
 425          $new = clone $this;
 426          $new->scheme = $scheme;
 427          $new->composedComponents = null;
 428          $new->removeDefaultPort();
 429          $new->validateState();
 430  
 431          return $new;
 432      }
 433  
 434      public function withUserInfo($user, $password = null): UriInterface
 435      {
 436          $info = $this->filterUserInfoComponent($user);
 437          if ($password !== null) {
 438              $info .= ':' . $this->filterUserInfoComponent($password);
 439          }
 440  
 441          if ($this->userInfo === $info) {
 442              return $this;
 443          }
 444  
 445          $new = clone $this;
 446          $new->userInfo = $info;
 447          $new->composedComponents = null;
 448          $new->validateState();
 449  
 450          return $new;
 451      }
 452  
 453      public function withHost($host): UriInterface
 454      {
 455          $host = $this->filterHost($host);
 456  
 457          if ($this->host === $host) {
 458              return $this;
 459          }
 460  
 461          $new = clone $this;
 462          $new->host = $host;
 463          $new->composedComponents = null;
 464          $new->validateState();
 465  
 466          return $new;
 467      }
 468  
 469      public function withPort($port): UriInterface
 470      {
 471          $port = $this->filterPort($port);
 472  
 473          if ($this->port === $port) {
 474              return $this;
 475          }
 476  
 477          $new = clone $this;
 478          $new->port = $port;
 479          $new->composedComponents = null;
 480          $new->removeDefaultPort();
 481          $new->validateState();
 482  
 483          return $new;
 484      }
 485  
 486      public function withPath($path): UriInterface
 487      {
 488          $path = $this->filterPath($path);
 489  
 490          if ($this->path === $path) {
 491              return $this;
 492          }
 493  
 494          $new = clone $this;
 495          $new->path = $path;
 496          $new->composedComponents = null;
 497          $new->validateState();
 498  
 499          return $new;
 500      }
 501  
 502      public function withQuery($query): UriInterface
 503      {
 504          $query = $this->filterQueryAndFragment($query);
 505  
 506          if ($this->query === $query) {
 507              return $this;
 508          }
 509  
 510          $new = clone $this;
 511          $new->query = $query;
 512          $new->composedComponents = null;
 513  
 514          return $new;
 515      }
 516  
 517      public function withFragment($fragment): UriInterface
 518      {
 519          $fragment = $this->filterQueryAndFragment($fragment);
 520  
 521          if ($this->fragment === $fragment) {
 522              return $this;
 523          }
 524  
 525          $new = clone $this;
 526          $new->fragment = $fragment;
 527          $new->composedComponents = null;
 528  
 529          return $new;
 530      }
 531  
 532      public function jsonSerialize(): string
 533      {
 534          return $this->__toString();
 535      }
 536  
 537      /**
 538       * Apply parse_url parts to a URI.
 539       *
 540       * @param array $parts Array of parse_url parts to apply.
 541       */
 542      private function applyParts(array $parts): void
 543      {
 544          $this->scheme = isset($parts['scheme'])
 545              ? $this->filterScheme($parts['scheme'])
 546              : '';
 547          $this->userInfo = isset($parts['user'])
 548              ? $this->filterUserInfoComponent($parts['user'])
 549              : '';
 550          $this->host = isset($parts['host'])
 551              ? $this->filterHost($parts['host'])
 552              : '';
 553          $this->port = isset($parts['port'])
 554              ? $this->filterPort($parts['port'])
 555              : null;
 556          $this->path = isset($parts['path'])
 557              ? $this->filterPath($parts['path'])
 558              : '';
 559          $this->query = isset($parts['query'])
 560              ? $this->filterQueryAndFragment($parts['query'])
 561              : '';
 562          $this->fragment = isset($parts['fragment'])
 563              ? $this->filterQueryAndFragment($parts['fragment'])
 564              : '';
 565          if (isset($parts['pass'])) {
 566              $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']);
 567          }
 568  
 569          $this->removeDefaultPort();
 570      }
 571  
 572      /**
 573       * @param mixed $scheme
 574       *
 575       * @throws \InvalidArgumentException If the scheme is invalid.
 576       */
 577      private function filterScheme($scheme): string
 578      {
 579          if (!is_string($scheme)) {
 580              throw new \InvalidArgumentException('Scheme must be a string');
 581          }
 582  
 583          return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
 584      }
 585  
 586      /**
 587       * @param mixed $component
 588       *
 589       * @throws \InvalidArgumentException If the user info is invalid.
 590       */
 591      private function filterUserInfoComponent($component): string
 592      {
 593          if (!is_string($component)) {
 594              throw new \InvalidArgumentException('User info must be a string');
 595          }
 596  
 597          return preg_replace_callback(
 598              '/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/',
 599              [$this, 'rawurlencodeMatchZero'],
 600              $component
 601          );
 602      }
 603  
 604      /**
 605       * @param mixed $host
 606       *
 607       * @throws \InvalidArgumentException If the host is invalid.
 608       */
 609      private function filterHost($host): string
 610      {
 611          if (!is_string($host)) {
 612              throw new \InvalidArgumentException('Host must be a string');
 613          }
 614  
 615          return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
 616      }
 617  
 618      /**
 619       * @param mixed $port
 620       *
 621       * @throws \InvalidArgumentException If the port is invalid.
 622       */
 623      private function filterPort($port): ?int
 624      {
 625          if ($port === null) {
 626              return null;
 627          }
 628  
 629          $port = (int) $port;
 630          if (0 > $port || 0xffff < $port) {
 631              throw new \InvalidArgumentException(
 632                  sprintf('Invalid port: %d. Must be between 0 and 65535', $port)
 633              );
 634          }
 635  
 636          return $port;
 637      }
 638  
 639      /**
 640       * @param string[] $keys
 641       *
 642       * @return string[]
 643       */
 644      private static function getFilteredQueryString(UriInterface $uri, array $keys): array
 645      {
 646          $current = $uri->getQuery();
 647  
 648          if ($current === '') {
 649              return [];
 650          }
 651  
 652          $decodedKeys = array_map('rawurldecode', $keys);
 653  
 654          return array_filter(explode('&', $current), function ($part) use ($decodedKeys) {
 655              return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true);
 656          });
 657      }
 658  
 659      private static function generateQueryString(string $key, ?string $value): string
 660      {
 661          // Query string separators ("=", "&") within the key or value need to be encoded
 662          // (while preventing double-encoding) before setting the query string. All other
 663          // chars that need percent-encoding will be encoded by withQuery().
 664          $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT);
 665  
 666          if ($value !== null) {
 667              $queryString .= '=' . strtr($value, self::QUERY_SEPARATORS_REPLACEMENT);
 668          }
 669  
 670          return $queryString;
 671      }
 672  
 673      private function removeDefaultPort(): void
 674      {
 675          if ($this->port !== null && self::isDefaultPort($this)) {
 676              $this->port = null;
 677          }
 678      }
 679  
 680      /**
 681       * Filters the path of a URI
 682       *
 683       * @param mixed $path
 684       *
 685       * @throws \InvalidArgumentException If the path is invalid.
 686       */
 687      private function filterPath($path): string
 688      {
 689          if (!is_string($path)) {
 690              throw new \InvalidArgumentException('Path must be a string');
 691          }
 692  
 693          return preg_replace_callback(
 694              '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
 695              [$this, 'rawurlencodeMatchZero'],
 696              $path
 697          );
 698      }
 699  
 700      /**
 701       * Filters the query string or fragment of a URI.
 702       *
 703       * @param mixed $str
 704       *
 705       * @throws \InvalidArgumentException If the query or fragment is invalid.
 706       */
 707      private function filterQueryAndFragment($str): string
 708      {
 709          if (!is_string($str)) {
 710              throw new \InvalidArgumentException('Query and fragment must be a string');
 711          }
 712  
 713          return preg_replace_callback(
 714              '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
 715              [$this, 'rawurlencodeMatchZero'],
 716              $str
 717          );
 718      }
 719  
 720      private function rawurlencodeMatchZero(array $match): string
 721      {
 722          return rawurlencode($match[0]);
 723      }
 724  
 725      private function validateState(): void
 726      {
 727          if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) {
 728              $this->host = self::HTTP_DEFAULT_HOST;
 729          }
 730  
 731          if ($this->getAuthority() === '') {
 732              if (0 === strpos($this->path, '//')) {
 733                  throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"');
 734              }
 735              if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) {
 736                  throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon');
 737              }
 738          }
 739      }
 740  }