MediaWiki  1.29.1
WebResponse.php
Go to the documentation of this file.
1 <?php
28 class WebResponse {
29 
33  protected static $setCookies = [];
34 
41  public function header( $string, $replace = true, $http_response_code = null ) {
43  if ( $http_response_code ) {
44  header( $string, $replace, $http_response_code );
45  } else {
46  header( $string, $replace );
47  }
48  }
49 
56  public function getHeader( $key ) {
57  foreach ( headers_list() as $header ) {
58  list( $name, $val ) = explode( ':', $header, 2 );
59  if ( !strcasecmp( $name, $key ) ) {
60  return trim( $val );
61  }
62  }
63  return null;
64  }
65 
71  public function statusHeader( $code ) {
73  }
74 
80  public function headersSent() {
81  return headers_sent();
82  }
83 
99  public function setCookie( $name, $value, $expire = 0, $options = [] ) {
100  global $wgCookiePath, $wgCookiePrefix, $wgCookieDomain;
101  global $wgCookieSecure, $wgCookieExpiration, $wgCookieHttpOnly;
102 
103  $options = array_filter( $options, function ( $a ) {
104  return $a !== null;
105  } ) + [
106  'prefix' => $wgCookiePrefix,
107  'domain' => $wgCookieDomain,
108  'path' => $wgCookiePath,
109  'secure' => $wgCookieSecure,
110  'httpOnly' => $wgCookieHttpOnly,
111  'raw' => false,
112  ];
113 
114  if ( $expire === null ) {
115  $expire = 0; // Session cookie
116  } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
117  $expire = time() + $wgCookieExpiration;
118  }
119 
120  $func = $options['raw'] ? 'setrawcookie' : 'setcookie';
121 
122  if ( Hooks::run( 'WebResponseSetCookie', [ &$name, &$value, &$expire, &$options ] ) ) {
123  $cookie = $options['prefix'] . $name;
124  $data = [
125  'name' => (string)$cookie,
126  'value' => (string)$value,
127  'expire' => (int)$expire,
128  'path' => (string)$options['path'],
129  'domain' => (string)$options['domain'],
130  'secure' => (bool)$options['secure'],
131  'httpOnly' => (bool)$options['httpOnly'],
132  ];
133 
134  // Per RFC 6265, key is name + domain + path
135  $key = "{$data['name']}\n{$data['domain']}\n{$data['path']}";
136 
137  // If this cookie name was in the request, fake an entry in
138  // self::$setCookies for it so the deleting check works right.
139  if ( isset( $_COOKIE[$cookie] ) && !array_key_exists( $key, self::$setCookies ) ) {
140  self::$setCookies[$key] = [];
141  }
142 
143  // PHP deletes if value is the empty string; also, a past expiry is deleting
144  $deleting = ( $data['value'] === '' || $data['expire'] > 0 && $data['expire'] <= time() );
145 
146  if ( $deleting && !isset( self::$setCookies[$key] ) ) { // isset( null ) is false
147  wfDebugLog( 'cookie', 'already deleted ' . $func . ': "' . implode( '", "', $data ) . '"' );
148  } elseif ( !$deleting && isset( self::$setCookies[$key] ) &&
149  self::$setCookies[$key] === [ $func, $data ]
150  ) {
151  wfDebugLog( 'cookie', 'already set ' . $func . ': "' . implode( '", "', $data ) . '"' );
152  } else {
153  wfDebugLog( 'cookie', $func . ': "' . implode( '", "', $data ) . '"' );
154  if ( call_user_func_array( $func, array_values( $data ) ) ) {
155  self::$setCookies[$key] = $deleting ? null : [ $func, $data ];
156  }
157  }
158  }
159  }
160 
170  public function clearCookie( $name, $options = [] ) {
171  $this->setCookie( $name, '', time() - 31536000 /* 1 year */, $options );
172  }
173 
180  public function hasCookies() {
181  return (bool)self::$setCookies;
182  }
183 }
184 
188 class FauxResponse extends WebResponse {
189  private $headers;
190  private $cookies = [];
191  private $code;
192 
199  public function header( $string, $replace = true, $http_response_code = null ) {
200  if ( substr( $string, 0, 5 ) == 'HTTP/' ) {
201  $parts = explode( ' ', $string, 3 );
202  $this->code = intval( $parts[1] );
203  } else {
204  list( $key, $val ) = array_map( 'trim', explode( ":", $string, 2 ) );
205 
206  $key = strtoupper( $key );
207 
208  if ( $replace || !isset( $this->headers[$key] ) ) {
209  $this->headers[$key] = $val;
210  }
211  }
212 
213  if ( $http_response_code !== null ) {
214  $this->code = intval( $http_response_code );
215  }
216  }
217 
222  public function statusHeader( $code ) {
223  $this->code = intval( $code );
224  }
225 
226  public function headersSent() {
227  return false;
228  }
229 
234  public function getHeader( $key ) {
235  $key = strtoupper( $key );
236 
237  if ( isset( $this->headers[$key] ) ) {
238  return $this->headers[$key];
239  }
240  return null;
241  }
242 
248  public function getStatusCode() {
249  return $this->code;
250  }
251 
258  public function setCookie( $name, $value, $expire = 0, $options = [] ) {
259  global $wgCookiePath, $wgCookiePrefix, $wgCookieDomain;
260  global $wgCookieSecure, $wgCookieExpiration, $wgCookieHttpOnly;
261 
262  $options = array_filter( $options, function ( $a ) {
263  return $a !== null;
264  } ) + [
265  'prefix' => $wgCookiePrefix,
266  'domain' => $wgCookieDomain,
267  'path' => $wgCookiePath,
268  'secure' => $wgCookieSecure,
269  'httpOnly' => $wgCookieHttpOnly,
270  'raw' => false,
271  ];
272 
273  if ( $expire === null ) {
274  $expire = 0; // Session cookie
275  } elseif ( $expire == 0 && $wgCookieExpiration != 0 ) {
276  $expire = time() + $wgCookieExpiration;
277  }
278 
279  $this->cookies[$options['prefix'] . $name] = [
280  'value' => (string)$value,
281  'expire' => (int)$expire,
282  'path' => (string)$options['path'],
283  'domain' => (string)$options['domain'],
284  'secure' => (bool)$options['secure'],
285  'httpOnly' => (bool)$options['httpOnly'],
286  'raw' => (bool)$options['raw'],
287  ];
288  }
289 
294  public function getCookie( $name ) {
295  if ( isset( $this->cookies[$name] ) ) {
296  return $this->cookies[$name]['value'];
297  }
298  return null;
299  }
300 
305  public function getCookieData( $name ) {
306  if ( isset( $this->cookies[$name] ) ) {
307  return $this->cookies[$name];
308  }
309  return null;
310  }
311 
315  public function getCookies() {
316  return $this->cookies;
317  }
318 }
FauxResponse\getCookieData
getCookieData( $name)
Definition: WebResponse.php:305
cookies
it sets a lot of them automatically from cookies
Definition: design.txt:93
$wgCookiePrefix
if( $wgLocalInterwiki) if( $wgSharedPrefix===false) if( $wgSharedSchema===false) if(! $wgCookiePrefix) $wgCookiePrefix
Definition: Setup.php:326
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:315
FauxResponse\$code
$code
Definition: WebResponse.php:191
WebResponse\getHeader
getHeader( $key)
Get a response header.
Definition: WebResponse.php:56
WebResponse\header
header( $string, $replace=true, $http_response_code=null)
Output an HTTP header, wrapper for PHP's header()
Definition: WebResponse.php:41
WebResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
Definition: WebResponse.php:99
WebResponse\hasCookies
hasCookies()
Checks whether this request is performing cookie operations.
Definition: WebResponse.php:180
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
WebResponse\statusHeader
statusHeader( $code)
Output an HTTP status code header.
Definition: WebResponse.php:71
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:1092
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:234
FauxResponse\$headers
$headers
Definition: WebResponse.php:189
WebResponse\clearCookie
clearCookie( $name, $options=[])
Unset a browser cookie.
Definition: WebResponse.php:170
FauxResponse\header
header( $string, $replace=true, $http_response_code=null)
Stores a HTTP header.
Definition: WebResponse.php:199
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
WebResponse\headersSent
headersSent()
Test if headers have been sent.
Definition: WebResponse.php:80
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
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:177
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
FauxResponse\getCookie
getCookie( $name)
Definition: WebResponse.php:294
FauxResponse\statusHeader
statusHeader( $code)
Definition: WebResponse.php:222
$value
$value
Definition: styleTest.css.php:45
$header
$header
Definition: updateCredits.php:35
FauxResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Definition: WebResponse.php:258
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
FauxResponse
Definition: WebResponse.php:188
$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:783
FauxResponse\headersSent
headersSent()
Test if headers have been sent.
Definition: WebResponse.php:226
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:248
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:131
FauxResponse\$cookies
$cookies
Definition: WebResponse.php:190
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:12
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
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