Merge "phpunit: Fix OutputPage::__construct warning in SkinTemplateTest"
[lhc/web/wiklou.git] / includes / WebResponse.php
1 <?php
2 /**
3 * Classes used to send headers and cookies back to the user
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Allow programs to request this object from WebRequest::response()
25 * and handle all outputting (or lack of outputting) via it.
26 * @ingroup HTTP
27 */
28 class WebResponse {
29
30 /** @var array Used to record set cookies, because PHP's setcookie() will
31 * happily send an identical Set-Cookie to the client.
32 */
33 protected static $setCookies = [];
34
35 /**
36 * Output an HTTP header, wrapper for PHP's header()
37 * @param string $string Header to output
38 * @param bool $replace Replace current similar header
39 * @param null|int $http_response_code Forces the HTTP response code to the specified value.
40 */
41 public function header( $string, $replace = true, $http_response_code = null ) {
42 if ( headers_sent() ) {
43 MWDebug::warning( 'Headers already sent, should send headers earlier than ' . wfGetCaller() );
44 }
45 if ( $http_response_code ) {
46 header( $string, $replace, $http_response_code );
47 } else {
48 header( $string, $replace );
49 }
50 }
51
52 /**
53 * Get a response header
54 * @param string $key The name of the header to get (case insensitive).
55 * @return string|null The header value (if set); null otherwise.
56 * @since 1.25
57 */
58 public function getHeader( $key ) {
59 foreach ( headers_list() as $header ) {
60 list( $name, $val ) = explode( ':', $header, 2 );
61 if ( !strcasecmp( $name, $key ) ) {
62 return trim( $val );
63 }
64 }
65 return null;
66 }
67
68 /**
69 * Output an HTTP status code header
70 * @since 1.26
71 * @param int $code Status code
72 */
73 public function statusHeader( $code ) {
74 HttpStatus::header( $code );
75 }
76
77 /**
78 * Test if headers have been sent
79 * @since 1.27
80 * @return bool
81 */
82 public function headersSent() {
83 return headers_sent();
84 }
85
86 /**
87 * Set the browser cookie
88 * @param string $name The name of the cookie.
89 * @param string $value The value to be stored in the cookie.
90 * @param int|null $expire Unix timestamp (in seconds) when the cookie should expire.
91 * 0 (the default) causes it to expire $wgCookieExpiration seconds from now.
92 * null causes it to be a session cookie.
93 * @param array $options Assoc of additional cookie options:
94 * prefix: string, name prefix ($wgCookiePrefix)
95 * domain: string, cookie domain ($wgCookieDomain)
96 * path: string, cookie path ($wgCookiePath)
97 * secure: bool, secure attribute ($wgCookieSecure)
98 * httpOnly: bool, httpOnly attribute ($wgCookieHttpOnly)
99 * @since 1.22 Replaced $prefix, $domain, and $forceSecure with $options
100 */
101 public function setCookie( $name, $value, $expire = 0, $options = [] ) {
102 global $wgCookiePath, $wgCookiePrefix, $wgCookieDomain;
103 global $wgCookieSecure, $wgCookieExpiration, $wgCookieHttpOnly;
104
105 $options = array_filter( $options, function ( $a ) {
106 return $a !== null;
107 } ) + [
108 'prefix' => $wgCookiePrefix,
109 'domain' => $wgCookieDomain,
110 'path' => $wgCookiePath,
111 'secure' => $wgCookieSecure,
112 'httpOnly' => $wgCookieHttpOnly,
113 'raw' => false,
114 ];
115
116 if ( $expire === null ) {
117 $expire = 0; // Session cookie
118 } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
119 $expire = time() + $wgCookieExpiration;
120 }
121
122 $func = $options['raw'] ? 'setrawcookie' : 'setcookie';
123
124 if ( Hooks::run( 'WebResponseSetCookie', [ &$name, &$value, &$expire, &$options ] ) ) {
125 $cookie = $options['prefix'] . $name;
126 $data = [
127 'name' => (string)$cookie,
128 'value' => (string)$value,
129 'expire' => (int)$expire,
130 'path' => (string)$options['path'],
131 'domain' => (string)$options['domain'],
132 'secure' => (bool)$options['secure'],
133 'httpOnly' => (bool)$options['httpOnly'],
134 ];
135
136 // Per RFC 6265, key is name + domain + path
137 $key = "{$data['name']}\n{$data['domain']}\n{$data['path']}";
138
139 // If this cookie name was in the request, fake an entry in
140 // self::$setCookies for it so the deleting check works right.
141 if ( isset( $_COOKIE[$cookie] ) && !array_key_exists( $key, self::$setCookies ) ) {
142 self::$setCookies[$key] = [];
143 }
144
145 // PHP deletes if value is the empty string; also, a past expiry is deleting
146 $deleting = ( $data['value'] === '' || $data['expire'] > 0 && $data['expire'] <= time() );
147
148 if ( $deleting && !isset( self::$setCookies[$key] ) ) { // isset( null ) is false
149 wfDebugLog( 'cookie', 'already deleted ' . $func . ': "' . implode( '", "', $data ) . '"' );
150 } elseif ( !$deleting && isset( self::$setCookies[$key] ) &&
151 self::$setCookies[$key] === [ $func, $data ]
152 ) {
153 wfDebugLog( 'cookie', 'already set ' . $func . ': "' . implode( '", "', $data ) . '"' );
154 } else {
155 wfDebugLog( 'cookie', $func . ': "' . implode( '", "', $data ) . '"' );
156 if ( call_user_func_array( $func, array_values( $data ) ) ) {
157 self::$setCookies[$key] = $deleting ? null : [ $func, $data ];
158 }
159 }
160 }
161 }
162
163 /**
164 * Unset a browser cookie.
165 * This sets the cookie with an empty value and an expiry set to a time in the past,
166 * which will cause the browser to remove any cookie with the given name, domain and
167 * path from its cookie store. Options other than these (and prefix) have no effect.
168 * @param string $name Cookie name
169 * @param array $options Cookie options, see {@link setCookie()}
170 * @since 1.27
171 */
172 public function clearCookie( $name, $options = [] ) {
173 $this->setCookie( $name, '', time() - 31536000 /* 1 year */, $options );
174 }
175
176 /**
177 * Checks whether this request is performing cookie operations
178 *
179 * @return bool
180 * @since 1.27
181 */
182 public function hasCookies() {
183 return (bool)self::$setCookies;
184 }
185 }
186
187 /**
188 * @ingroup HTTP
189 */
190 class FauxResponse extends WebResponse {
191 private $headers;
192 private $cookies = [];
193 private $code;
194
195 /**
196 * Stores a HTTP header
197 * @param string $string Header to output
198 * @param bool $replace Replace current similar header
199 * @param null|int $http_response_code Forces the HTTP response code to the specified value.
200 */
201 public function header( $string, $replace = true, $http_response_code = null ) {
202 if ( substr( $string, 0, 5 ) == 'HTTP/' ) {
203 $parts = explode( ' ', $string, 3 );
204 $this->code = intval( $parts[1] );
205 } else {
206 list( $key, $val ) = array_map( 'trim', explode( ":", $string, 2 ) );
207
208 $key = strtoupper( $key );
209
210 if ( $replace || !isset( $this->headers[$key] ) ) {
211 $this->headers[$key] = $val;
212 }
213 }
214
215 if ( $http_response_code !== null ) {
216 $this->code = intval( $http_response_code );
217 }
218 }
219
220 /**
221 * @since 1.26
222 * @param int $code Status code
223 */
224 public function statusHeader( $code ) {
225 $this->code = intval( $code );
226 }
227
228 public function headersSent() {
229 return false;
230 }
231
232 /**
233 * @param string $key The name of the header to get (case insensitive).
234 * @return string|null The header value (if set); null otherwise.
235 */
236 public function getHeader( $key ) {
237 $key = strtoupper( $key );
238
239 if ( isset( $this->headers[$key] ) ) {
240 return $this->headers[$key];
241 }
242 return null;
243 }
244
245 /**
246 * Get the HTTP response code, null if not set
247 *
248 * @return int|null
249 */
250 public function getStatusCode() {
251 return $this->code;
252 }
253
254 /**
255 * @param string $name The name of the cookie.
256 * @param string $value The value to be stored in the cookie.
257 * @param int|null $expire Ignored in this faux subclass.
258 * @param array $options Ignored in this faux subclass.
259 */
260 public function setCookie( $name, $value, $expire = 0, $options = [] ) {
261 global $wgCookiePath, $wgCookiePrefix, $wgCookieDomain;
262 global $wgCookieSecure, $wgCookieExpiration, $wgCookieHttpOnly;
263
264 $options = array_filter( $options, function ( $a ) {
265 return $a !== null;
266 } ) + [
267 'prefix' => $wgCookiePrefix,
268 'domain' => $wgCookieDomain,
269 'path' => $wgCookiePath,
270 'secure' => $wgCookieSecure,
271 'httpOnly' => $wgCookieHttpOnly,
272 'raw' => false,
273 ];
274
275 if ( $expire === null ) {
276 $expire = 0; // Session cookie
277 } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
278 $expire = time() + $wgCookieExpiration;
279 }
280
281 $this->cookies[$options['prefix'] . $name] = [
282 'value' => (string)$value,
283 'expire' => (int)$expire,
284 'path' => (string)$options['path'],
285 'domain' => (string)$options['domain'],
286 'secure' => (bool)$options['secure'],
287 'httpOnly' => (bool)$options['httpOnly'],
288 'raw' => (bool)$options['raw'],
289 ];
290 }
291
292 /**
293 * @param string $name
294 * @return string|null
295 */
296 public function getCookie( $name ) {
297 if ( isset( $this->cookies[$name] ) ) {
298 return $this->cookies[$name]['value'];
299 }
300 return null;
301 }
302
303 /**
304 * @param string $name
305 * @return array|null
306 */
307 public function getCookieData( $name ) {
308 if ( isset( $this->cookies[$name] ) ) {
309 return $this->cookies[$name];
310 }
311 return null;
312 }
313
314 /**
315 * @return array
316 */
317 public function getCookies() {
318 return $this->cookies;
319 }
320 }