MediaWiki  1.32.0
WebResponse.php
Go to the documentation of this file.
1 <?php
28 class WebResponse {
29 
33  protected static $setCookies = [];
34 
36  protected static $disableForPostSend = false;
37 
47  public static function disableForPostSend() {
48  self::$disableForPostSend = true;
49  }
50 
57  public function header( $string, $replace = true, $http_response_code = null ) {
58  if ( self::$disableForPostSend ) {
59  wfDebugLog( 'header', 'ignored post-send header {header}', 'all', [
60  'header' => $string,
61  'replace' => $replace,
62  'http_response_code' => $http_response_code,
63  'exception' => new RuntimeException( 'Ignored post-send header' ),
64  ] );
65  return;
66  }
67 
69  if ( $http_response_code ) {
70  header( $string, $replace, $http_response_code );
71  } else {
72  header( $string, $replace );
73  }
74  }
75 
82  public function getHeader( $key ) {
83  foreach ( headers_list() as $header ) {
84  list( $name, $val ) = explode( ':', $header, 2 );
85  if ( !strcasecmp( $name, $key ) ) {
86  return trim( $val );
87  }
88  }
89  return null;
90  }
91 
97  public function statusHeader( $code ) {
98  if ( self::$disableForPostSend ) {
99  wfDebugLog( 'header', 'ignored post-send status header {code}', 'all', [
100  'code' => $code,
101  'exception' => new RuntimeException( 'Ignored post-send status header' ),
102  ] );
103  return;
104  }
105 
107  }
108 
114  public function headersSent() {
115  return headers_sent();
116  }
117 
133  public function setCookie( $name, $value, $expire = 0, $options = [] ) {
136 
137  $options = array_filter( $options, function ( $a ) {
138  return $a !== null;
139  } ) + [
140  'prefix' => $wgCookiePrefix,
141  'domain' => $wgCookieDomain,
142  'path' => $wgCookiePath,
143  'secure' => $wgCookieSecure,
144  'httpOnly' => $wgCookieHttpOnly,
145  'raw' => false,
146  ];
147 
148  if ( $expire === null ) {
149  $expire = 0; // Session cookie
150  } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
151  $expire = time() + $wgCookieExpiration;
152  }
153 
154  if ( self::$disableForPostSend ) {
155  $cookie = $options['prefix'] . $name;
156  wfDebugLog( 'cookie', 'ignored post-send cookie {cookie}', 'all', [
157  'cookie' => $cookie,
158  'data' => [
159  'name' => (string)$cookie,
160  'value' => (string)$value,
161  'expire' => (int)$expire,
162  'path' => (string)$options['path'],
163  'domain' => (string)$options['domain'],
164  'secure' => (bool)$options['secure'],
165  'httpOnly' => (bool)$options['httpOnly'],
166  ],
167  'exception' => new RuntimeException( 'Ignored post-send cookie' ),
168  ] );
169  return;
170  }
171 
172  $func = $options['raw'] ? 'setrawcookie' : 'setcookie';
173 
174  if ( Hooks::run( 'WebResponseSetCookie', [ &$name, &$value, &$expire, &$options ] ) ) {
175  // Note: Don't try to move this earlier to reuse it for self::$disableForPostSend,
176  // we need to use the altered values from the hook here. (T198525)
177  $cookie = $options['prefix'] . $name;
178  $data = [
179  'name' => (string)$cookie,
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  ];
187 
188  // Per RFC 6265, key is name + domain + path
189  $key = "{$data['name']}\n{$data['domain']}\n{$data['path']}";
190 
191  // If this cookie name was in the request, fake an entry in
192  // self::$setCookies for it so the deleting check works right.
193  if ( isset( $_COOKIE[$cookie] ) && !array_key_exists( $key, self::$setCookies ) ) {
194  self::$setCookies[$key] = [];
195  }
196 
197  // PHP deletes if value is the empty string; also, a past expiry is deleting
198  $deleting = ( $data['value'] === '' || $data['expire'] > 0 && $data['expire'] <= time() );
199 
200  if ( $deleting && !isset( self::$setCookies[$key] ) ) { // isset( null ) is false
201  wfDebugLog( 'cookie', 'already deleted ' . $func . ': "' . implode( '", "', $data ) . '"' );
202  } elseif ( !$deleting && isset( self::$setCookies[$key] ) &&
203  self::$setCookies[$key] === [ $func, $data ]
204  ) {
205  wfDebugLog( 'cookie', 'already set ' . $func . ': "' . implode( '", "', $data ) . '"' );
206  } else {
207  wfDebugLog( 'cookie', $func . ': "' . implode( '", "', $data ) . '"' );
208  if ( call_user_func_array( $func, array_values( $data ) ) ) {
209  self::$setCookies[$key] = $deleting ? null : [ $func, $data ];
210  }
211  }
212  }
213  }
214 
224  public function clearCookie( $name, $options = [] ) {
225  $this->setCookie( $name, '', time() - 31536000 /* 1 year */, $options );
226  }
227 
234  public function hasCookies() {
235  return (bool)self::$setCookies;
236  }
237 }
238 
242 class FauxResponse extends WebResponse {
243  private $headers;
244  private $cookies = [];
245  private $code;
246 
253  public function header( $string, $replace = true, $http_response_code = null ) {
254  if ( substr( $string, 0, 5 ) == 'HTTP/' ) {
255  $parts = explode( ' ', $string, 3 );
256  $this->code = intval( $parts[1] );
257  } else {
258  list( $key, $val ) = array_map( 'trim', explode( ":", $string, 2 ) );
259 
260  $key = strtoupper( $key );
261 
262  if ( $replace || !isset( $this->headers[$key] ) ) {
263  $this->headers[$key] = $val;
264  }
265  }
266 
267  if ( $http_response_code !== null ) {
268  $this->code = intval( $http_response_code );
269  }
270  }
271 
276  public function statusHeader( $code ) {
277  $this->code = intval( $code );
278  }
279 
280  public function headersSent() {
281  return false;
282  }
283 
288  public function getHeader( $key ) {
289  $key = strtoupper( $key );
290 
291  return $this->headers[$key] ?? null;
292  }
293 
299  public function getStatusCode() {
300  return $this->code;
301  }
302 
309  public function setCookie( $name, $value, $expire = 0, $options = [] ) {
312 
313  $options = array_filter( $options, function ( $a ) {
314  return $a !== null;
315  } ) + [
316  'prefix' => $wgCookiePrefix,
317  'domain' => $wgCookieDomain,
318  'path' => $wgCookiePath,
319  'secure' => $wgCookieSecure,
320  'httpOnly' => $wgCookieHttpOnly,
321  'raw' => false,
322  ];
323 
324  if ( $expire === null ) {
325  $expire = 0; // Session cookie
326  } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
327  $expire = time() + $wgCookieExpiration;
328  }
329 
330  $this->cookies[$options['prefix'] . $name] = [
331  'value' => (string)$value,
332  'expire' => (int)$expire,
333  'path' => (string)$options['path'],
334  'domain' => (string)$options['domain'],
335  'secure' => (bool)$options['secure'],
336  'httpOnly' => (bool)$options['httpOnly'],
337  'raw' => (bool)$options['raw'],
338  ];
339  }
340 
345  public function getCookie( $name ) {
346  if ( isset( $this->cookies[$name] ) ) {
347  return $this->cookies[$name]['value'];
348  }
349  return null;
350  }
351 
356  public function getCookieData( $name ) {
357  return $this->cookies[$name] ?? null;
358  }
359 
363  public function getCookies() {
364  return $this->cookies;
365  }
366 }
FauxResponse\getCookieData
getCookieData( $name)
Definition: WebResponse.php:356
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:33
FauxResponse\getCookies
getCookies()
Definition: WebResponse.php:363
FauxResponse\$code
$code
Definition: WebResponse.php:245
$wgCookiePath
$wgCookiePath
Set this variable if you want to restrict cookies to a certain path within the domain specified by $w...
Definition: DefaultSettings.php:6024
WebResponse\getHeader
getHeader( $key)
Get a response header.
Definition: WebResponse.php:82
WebResponse\$disableForPostSend
static bool $disableForPostSend
Used to disable setters before running jobs post-request (T191537)
Definition: WebResponse.php:36
WebResponse\header
header( $string, $replace=true, $http_response_code=null)
Output an HTTP header, wrapper for PHP's header()
Definition: WebResponse.php:57
WebResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
Definition: WebResponse.php:133
WebResponse\hasCookies
hasCookies()
Checks whether this request is performing cookie operations.
Definition: WebResponse.php:234
WebResponse\statusHeader
statusHeader( $code)
Output an HTTP status code header.
Definition: WebResponse.php:97
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:1082
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:35
FauxResponse\getHeader
getHeader( $key)
Definition: WebResponse.php:288
FauxResponse\$headers
$headers
Definition: WebResponse.php:243
WebResponse\clearCookie
clearCookie( $name, $options=[])
Unset a browser cookie.
Definition: WebResponse.php:224
FauxResponse\header
header( $string, $replace=true, $http_response_code=null)
Stores a HTTP header.
Definition: WebResponse.php:253
$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:813
WebResponse\headersSent
headersSent()
Test if headers have been sent.
Definition: WebResponse.php:114
$wgCookieHttpOnly
$wgCookieHttpOnly
Set authentication cookies to HttpOnly to prevent access by JavaScript, in browsers that support this...
Definition: DefaultSettings.php:6054
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
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:175
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
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
WebResponse\disableForPostSend
static disableForPostSend()
Disable setters for post-send processing.
Definition: WebResponse.php:47
FauxResponse\getCookie
getCookie( $name)
Definition: WebResponse.php:345
$wgCookieExpiration
$wgCookieExpiration
Default cookie lifetime, in seconds.
Definition: DefaultSettings.php:6004
FauxResponse\statusHeader
statusHeader( $code)
Definition: WebResponse.php:276
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:23
$value
$value
Definition: styleTest.css.php:49
$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:6018
FauxResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Definition: WebResponse.php:309
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
FauxResponse
Definition: WebResponse.php:242
$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:2036
FauxResponse\headersSent
headersSent()
Test if headers have been sent.
Definition: WebResponse.php:280
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:9
FauxResponse\getStatusCode
getStatusCode()
Get the HTTP response code, null if not set.
Definition: WebResponse.php:299
$wgCookieSecure
$wgCookieSecure
Whether the "secure" flag should be set on the cookie.
Definition: DefaultSettings.php:6032
WebResponse
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:28
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
FauxResponse\$cookies
$cookies
Definition: WebResponse.php:244
$wgCookiePrefix
$wgCookiePrefix
Cookies generated by MediaWiki have names starting with this prefix.
Definition: DefaultSettings.php:6047
MediaWiki\HeaderCallback\warnIfHeadersSent
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
Definition: HeaderCallback.php:57