MediaWiki  1.31.16
WebResponse.php
Go to the documentation of this file.
1 <?php
24 
30 class WebResponse {
31 
35  protected static $setCookies = [];
36 
38  protected static $disableForPostSend = false;
39 
49  public static function disableForPostSend() {
50  self::$disableForPostSend = true;
51  }
52 
59  public function header( $string, $replace = true, $http_response_code = null ) {
60  if ( self::$disableForPostSend ) {
61  wfDebugLog( 'header', 'ignored post-send header {header}', 'all', [
62  'header' => $string,
63  'replace' => $replace,
64  'http_response_code' => $http_response_code,
65  'exception' => new RuntimeException( 'Ignored post-send header' ),
66  ] );
67  return;
68  }
69 
71  if ( $http_response_code ) {
72  header( $string, $replace, $http_response_code );
73  } else {
74  header( $string, $replace );
75  }
76  }
77 
84  public function getHeader( $key ) {
85  foreach ( headers_list() as $header ) {
86  list( $name, $val ) = explode( ':', $header, 2 );
87  if ( !strcasecmp( $name, $key ) ) {
88  return trim( $val );
89  }
90  }
91  return null;
92  }
93 
99  public function statusHeader( $code ) {
100  if ( self::$disableForPostSend ) {
101  wfDebugLog( 'header', 'ignored post-send status header {code}', 'all', [
102  'code' => $code,
103  'exception' => new RuntimeException( 'Ignored post-send status header' ),
104  ] );
105  return;
106  }
107 
109  }
110 
116  public function headersSent() {
117  return headers_sent();
118  }
119 
141  public function setCookie( $name, $value, $expire = 0, $options = [] ) {
145 
146  $options = array_filter( $options, function ( $a ) {
147  return $a !== null;
148  } ) + [
149  'prefix' => $wgCookiePrefix,
150  'domain' => $wgCookieDomain,
151  'path' => $wgCookiePath,
152  'secure' => $wgCookieSecure,
153  'httpOnly' => $wgCookieHttpOnly,
154  'raw' => false,
155  'sameSite' => '',
156  'sameSiteLegacy' => $wgUseSameSiteLegacyCookies
157  ];
158 
159  if ( strcasecmp( $options['sameSite'], 'none' ) === 0
160  && !empty( $options['sameSiteLegacy'] )
161  ) {
162  $legacyOptions = $options;
163  $legacyOptions['sameSiteLegacy'] = false;
164  $legacyOptions['sameSite'] = '';
165  $this->setCookie( "ss0-$name", $value, $expire, $legacyOptions );
166  }
167 
168  if ( $expire === null ) {
169  $expire = 0; // Session cookie
170  } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
171  $expire = time() + $wgCookieExpiration;
172  }
173 
174  if ( self::$disableForPostSend ) {
175  $prefixedName = $options['prefix'] . $name;
176  wfDebugLog( 'cookie', 'ignored post-send cookie {cookie}', 'all', [
177  'cookie' => $prefixedName,
178  'data' => [
179  'name' => $prefixedName,
180  'value' => (string)$value,
181  'expire' => (int)$expire,
182  'path' => (string)$options['path'],
183  'domain' => (string)$options['domain'],
184  'secure' => (bool)$options['secure'],
185  'httpOnly' => (bool)$options['httpOnly'],
186  'sameSite' => (string)$options['sameSite']
187  ],
188  'exception' => new RuntimeException( 'Ignored post-send cookie' ),
189  ] );
190  return;
191  }
192 
193  if ( !Hooks::run( 'WebResponseSetCookie', [ &$name, &$value, &$expire, &$options ] ) ) {
194  return;
195  }
196 
197  // Note: Don't try to move this earlier to reuse it for self::$disableForPostSend,
198  // we need to use the altered values from the hook here. (T198525)
199  $prefixedName = $options['prefix'] . $name;
200  $value = (string)$value;
201  $func = $options['raw'] ? 'setrawcookie' : 'setcookie';
202  $setOptions = [
203  'expires' => (int)$expire,
204  'path' => (string)$options['path'],
205  'domain' => (string)$options['domain'],
206  'secure' => (bool)$options['secure'],
207  'httponly' => (bool)$options['httpOnly'],
208  'samesite' => (string)$options['sameSite'],
209  ];
210 
211  // Per RFC 6265, key is name + domain + path
212  $key = "{$prefixedName}\n{$setOptions['domain']}\n{$setOptions['path']}";
213 
214  // If this cookie name was in the request, fake an entry in
215  // self::$setCookies for it so the deleting check works right.
216  if ( isset( $_COOKIE[$prefixedName] ) && !array_key_exists( $key, self::$setCookies ) ) {
217  self::$setCookies[$key] = [];
218  }
219 
220  // PHP deletes if value is the empty string; also, a past expiry is deleting
221  $deleting = ( $value === '' || $setOptions['expires'] > 0 && $setOptions['expires'] <= time() );
222 
223  $logDesc = "$func: \"$prefixedName\", \"$value\", \"" .
224  implode( '", "', $setOptions ) . '"';
225  $optionsForDeduplication = [ $func, $prefixedName, $value, $setOptions ];
226 
227  if ( $deleting && !isset( self::$setCookies[$key] ) ) { // isset( null ) is false
228  wfDebugLog( 'cookie', "already deleted $logDesc" );
229  return;
230  } elseif ( !$deleting && isset( self::$setCookies[$key] ) &&
231  self::$setCookies[$key] === $optionsForDeduplication
232  ) {
233  wfDebugLog( 'cookie', "already set $logDesc" );
234  return;
235  }
236 
237  wfDebugLog( 'cookie', $logDesc );
238  if ( $func === 'setrawcookie' ) {
239  // @phan-suppress-next-line PhanAccessMethodInternal
240  SetCookieCompat::setrawcookie( $prefixedName, $value, $setOptions );
241  } else {
242  // @phan-suppress-next-line PhanAccessMethodInternal
243  SetCookieCompat::setcookie( $prefixedName, $value, $setOptions );
244  }
245  self::$setCookies[$key] = $deleting ? null : $optionsForDeduplication;
246  }
247 
257  public function clearCookie( $name, $options = [] ) {
258  $this->setCookie( $name, '', time() - 31536000 /* 1 year */, $options );
259  }
260 
267  public function hasCookies() {
268  return (bool)self::$setCookies;
269  }
270 }
271 
275 class FauxResponse extends WebResponse {
276  private $headers;
277  private $cookies = [];
278  private $code;
279 
286  public function header( $string, $replace = true, $http_response_code = null ) {
287  if ( substr( $string, 0, 5 ) == 'HTTP/' ) {
288  $parts = explode( ' ', $string, 3 );
289  $this->code = intval( $parts[1] );
290  } else {
291  list( $key, $val ) = array_map( 'trim', explode( ":", $string, 2 ) );
292 
293  $key = strtoupper( $key );
294 
295  if ( $replace || !isset( $this->headers[$key] ) ) {
296  $this->headers[$key] = $val;
297  }
298  }
299 
300  if ( $http_response_code !== null ) {
301  $this->code = intval( $http_response_code );
302  }
303  }
304 
309  public function statusHeader( $code ) {
310  $this->code = intval( $code );
311  }
312 
313  public function headersSent() {
314  return false;
315  }
316 
321  public function getHeader( $key ) {
322  $key = strtoupper( $key );
323 
324  if ( isset( $this->headers[$key] ) ) {
325  return $this->headers[$key];
326  }
327  return null;
328  }
329 
335  public function getStatusCode() {
336  return $this->code;
337  }
338 
345  public function setCookie( $name, $value, $expire = 0, $options = [] ) {
348 
349  $options = array_filter( $options, function ( $a ) {
350  return $a !== null;
351  } ) + [
352  'prefix' => $wgCookiePrefix,
353  'domain' => $wgCookieDomain,
354  'path' => $wgCookiePath,
355  'secure' => $wgCookieSecure,
356  'httpOnly' => $wgCookieHttpOnly,
357  'raw' => false,
358  ];
359 
360  if ( $expire === null ) {
361  $expire = 0; // Session cookie
362  } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
363  $expire = time() + $wgCookieExpiration;
364  }
365 
366  $this->cookies[$options['prefix'] . $name] = [
367  'value' => (string)$value,
368  'expire' => (int)$expire,
369  'path' => (string)$options['path'],
370  'domain' => (string)$options['domain'],
371  'secure' => (bool)$options['secure'],
372  'httpOnly' => (bool)$options['httpOnly'],
373  'raw' => (bool)$options['raw'],
374  ];
375  }
376 
381  public function getCookie( $name ) {
382  if ( isset( $this->cookies[$name] ) ) {
383  return $this->cookies[$name]['value'];
384  }
385  return null;
386  }
387 
392  public function getCookieData( $name ) {
393  if ( isset( $this->cookies[$name] ) ) {
394  return $this->cookies[$name];
395  }
396  return null;
397  }
398 
402  public function getCookies() {
403  return $this->cookies;
404  }
405 }
FauxResponse\getCookieData
getCookieData( $name)
Definition: WebResponse.php:392
cookies
it sets a lot of them automatically from cookies
Definition: design.txt:93
WebResponse\$setCookies
static array $setCookies
Used to record set cookies, because PHP's setcookie() will happily send an identical Set-Cookie to th...
Definition: WebResponse.php:35
FauxResponse\getCookies
getCookies()
Definition: WebResponse.php:402
FauxResponse\$code
$code
Definition: WebResponse.php:278
$wgCookiePath
$wgCookiePath
Set this variable if you want to restrict cookies to a certain path within the domain specified by $w...
Definition: DefaultSettings.php:6009
WebResponse\getHeader
getHeader( $key)
Get a response header.
Definition: WebResponse.php:84
Wikimedia\Http\SetCookieCompat
Definition: SetCookieCompat.php:9
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:11
WebResponse\$disableForPostSend
static bool $disableForPostSend
Used to disable setters before running jobs post-request (T191537)
Definition: WebResponse.php:38
WebResponse\header
header( $string, $replace=true, $http_response_code=null)
Output an HTTP header, wrapper for PHP's header()
Definition: WebResponse.php:59
WebResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
Definition: WebResponse.php:141
$wgUseSameSiteLegacyCookies
bool $wgUseSameSiteLegacyCookies
If true, when a cross-site cookie with SameSite=None is sent, a legacy cookie with an "ss0" prefix wi...
Definition: DefaultSettings.php:6065
WebResponse\hasCookies
hasCookies()
Checks whether this request is performing cookie operations.
Definition: WebResponse.php:267
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
WebResponse\statusHeader
statusHeader( $code)
Output an HTTP status code header.
Definition: WebResponse.php:99
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1087
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:37
FauxResponse\getHeader
getHeader( $key)
Definition: WebResponse.php:321
FauxResponse\$headers
$headers
Definition: WebResponse.php:276
WebResponse\clearCookie
clearCookie( $name, $options=[])
Unset a browser cookie.
Definition: WebResponse.php:257
FauxResponse\header
header( $string, $replace=true, $http_response_code=null)
Stores a HTTP header.
Definition: WebResponse.php:286
WebResponse\headersSent
headersSent()
Test if headers have been sent.
Definition: WebResponse.php:116
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
$wgCookieHttpOnly
$wgCookieHttpOnly
Set authentication cookies to HttpOnly to prevent access by JavaScript, in browsers that support this...
Definition: DefaultSettings.php:6043
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:181
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
WebResponse\disableForPostSend
static disableForPostSend()
Disable setters for post-send processing.
Definition: WebResponse.php:49
FauxResponse\getCookie
getCookie( $name)
Definition: WebResponse.php:381
$wgCookieExpiration
$wgCookieExpiration
Default cookie lifetime, in seconds.
Definition: DefaultSettings.php:5989
FauxResponse\statusHeader
statusHeader( $code)
Definition: WebResponse.php:309
code
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of or an object and a method hook function The function part of a third party developers and administrators to define code that will be run at certain points in the mainline code
Definition: hooks.txt:28
$value
$value
Definition: styleTest.css.php:45
$header
$header
Definition: updateCredits.php:35
$wgCookieDomain
$wgCookieDomain
Set to set an explicit domain on the login cookies eg, "justthis.domain.org" or "....
Definition: DefaultSettings.php:6003
FauxResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Definition: WebResponse.php:345
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
FauxResponse
Definition: WebResponse.php:275
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:2001
$code
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:865
FauxResponse\headersSent
headersSent()
Test if headers have been sent.
Definition: WebResponse.php:313
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:22
FauxResponse\getStatusCode
getStatusCode()
Get the HTTP response code, null if not set.
Definition: WebResponse.php:335
$wgCookieSecure
$wgCookieSecure
Whether the "secure" flag should be set on the cookie.
Definition: DefaultSettings.php:6021
WebResponse
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:30
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
FauxResponse\$cookies
$cookies
Definition: WebResponse.php:277
$wgCookiePrefix
$wgCookiePrefix
Cookies generated by MediaWiki have names starting with this prefix.
Definition: DefaultSettings.php:6036
headers
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add headers
Definition: design.txt:18
array
the array() calling protocol came about after MediaWiki 1.4rc1.
MediaWiki\HeaderCallback\warnIfHeadersSent
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
Definition: HeaderCallback.php:57