1<?php
2
3namespace MediaWiki\Rest;
4
5use GuzzleHttp\Psr7\LazyOpenStream;
6use GuzzleHttp\Psr7\ServerRequest;
7use GuzzleHttp\Psr7\Uri;
8
9// phpcs:disable MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
10
11/**
12 * This is a request class that gets data directly from the superglobals and
13 * other global PHP state, notably php://input.
14 */
15class RequestFromGlobals extends RequestBase {
16	private $uri;
17	private $protocol;
18	private $uploadedFiles;
19
20	/**
21	 * @param array $params Associative array of parameters:
22	 *   - cookiePrefix: The prefix for cookie names used by getCookie()
23	 */
24	public function __construct( $params = [] ) {
25		parent::__construct( $params['cookiePrefix'] ?? '' );
26	}
27
28	// RequestInterface
29
30	public function getMethod() {
31		return $_SERVER['REQUEST_METHOD'] ?? 'GET';
32	}
33
34	public function getUri() {
35		if ( $this->uri === null ) {
36			$requestUrl = \WebRequest::getGlobalRequestURL();
37
38			try {
39				$uriInstance = new Uri( $requestUrl );
40			} catch ( \InvalidArgumentException $e ) {
41				// Uri constructor will throw exception if the URL is
42				// relative and contains colon-number pattern that
43				// looks like a port.
44				//
45				// Since $requestUrl here is absolute-path references
46				// so all titles that contain colon followed by a
47				// number would be inacessible if the exception occurs.
48				$uriInstance = (
49					new Uri( '//HOST:80' . $requestUrl )
50				)->withScheme( '' )->withHost( '' )->withPort( null );
51			}
52			$this->uri = $uriInstance;
53		}
54		return $this->uri;
55	}
56
57	// MessageInterface
58
59	public function getProtocolVersion() {
60		if ( $this->protocol === null ) {
61			$serverProtocol = $_SERVER['SERVER_PROTOCOL'] ?? '';
62			$prefixLength = strlen( 'HTTP/' );
63			if ( strncmp( $serverProtocol, 'HTTP/', $prefixLength ) === 0 ) {
64				$this->protocol = substr( $serverProtocol, $prefixLength );
65			} else {
66				$this->protocol = '1.1';
67			}
68		}
69		return $this->protocol;
70	}
71
72	protected function initHeaders() {
73		$this->setHeaders( getallheaders() );
74	}
75
76	public function getBody() {
77		return new LazyOpenStream( 'php://input', 'r' );
78	}
79
80	// ServerRequestInterface
81
82	public function getServerParams() {
83		return $_SERVER;
84	}
85
86	public function getCookieParams() {
87		return $_COOKIE;
88	}
89
90	public function getQueryParams() {
91		return $_GET;
92	}
93
94	public function getUploadedFiles() {
95		if ( $this->uploadedFiles === null ) {
96			$this->uploadedFiles = ServerRequest::normalizeFiles( $_FILES );
97		}
98		return $this->uploadedFiles;
99	}
100
101	public function getPostParams() {
102		return $_POST;
103	}
104}
105