MediaWiki  master
AjaxResponse.php
Go to the documentation of this file.
1 <?php
24 
31 class AjaxResponse {
36  private $mCacheDuration;
37 
42  private $mContentType;
43 
48  private $mDisabled;
49 
54  private $mLastModified;
55 
60  private $mResponseCode;
61 
66  private $mVary;
67 
72  private $mText;
73 
77  private $mConfig;
78 
83  function __construct( $text = null, Config $config = null ) {
84  $this->mCacheDuration = null;
85  $this->mVary = null;
86  $this->mConfig = $config ?: MediaWikiServices::getInstance()->getMainConfig();
87 
88  $this->mDisabled = false;
89  $this->mText = '';
90  $this->mResponseCode = 200;
91  $this->mLastModified = false;
92  $this->mContentType = 'application/x-wiki';
93 
94  if ( $text ) {
95  $this->addText( $text );
96  }
97  }
98 
103  function setCacheDuration( $duration ) {
104  $this->mCacheDuration = $duration;
105  }
106 
111  function setVary( $vary ) {
112  $this->mVary = $vary;
113  }
114 
119  function setResponseCode( $code ) {
120  $this->mResponseCode = $code;
121  }
122 
127  function setContentType( $type ) {
128  $this->mContentType = $type;
129  }
130 
134  function disable() {
135  $this->mDisabled = true;
136  }
137 
142  function addText( $text ) {
143  if ( !$this->mDisabled && $text ) {
144  $this->mText .= $text;
145  }
146  }
147 
151  function printText() {
152  if ( !$this->mDisabled ) {
154  }
155  }
156 
160  function sendHeaders() {
161  if ( $this->mResponseCode ) {
162  // For back-compat, it is supported that mResponseCode be a string like " 200 OK"
163  // (with leading space and the status message after). Cast response code to an integer
164  // to take advantage of PHP's conversion rules which will turn " 200 OK" into 200.
165  // https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
166  $n = intval( trim( $this->mResponseCode ) );
167  HttpStatus::header( $n );
168  }
169 
170  header( "Content-Type: " . $this->mContentType );
171 
172  if ( $this->mLastModified ) {
173  header( "Last-Modified: " . $this->mLastModified );
174  } else {
175  header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
176  }
177 
178  if ( $this->mCacheDuration ) {
179  # If CDN caches are configured, tell them to cache the response,
180  # and tell the client to always check with the CDN. Otherwise,
181  # tell the client to use a cached copy, without a way to purge it.
182 
183  if ( $this->mConfig->get( 'UseSquid' ) ) {
184  # Expect explicit purge of the proxy cache, but require end user agents
185  # to revalidate against the proxy on each visit.
186  # Surrogate-Control controls our CDN, Cache-Control downstream caches
187 
188  if ( $this->mConfig->get( 'UseESI' ) ) {
189  wfDeprecated( '$wgUseESI = true', '1.33' );
190  header( 'Surrogate-Control: max-age=' . $this->mCacheDuration . ', content="ESI/1.0"' );
191  header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
192  } else {
193  header( 'Cache-Control: s-maxage=' . $this->mCacheDuration . ', must-revalidate, max-age=0' );
194  }
195 
196  } else {
197  # Let the client do the caching. Cache is not purged.
198  header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $this->mCacheDuration ) . " GMT" );
199  header( "Cache-Control: s-maxage={$this->mCacheDuration}," .
200  "public,max-age={$this->mCacheDuration}" );
201  }
202 
203  } else {
204  # always expired, always modified
205  header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); // Date in the past
206  header( "Cache-Control: no-cache, must-revalidate" ); // HTTP/1.1
207  header( "Pragma: no-cache" ); // HTTP/1.0
208  }
209 
210  if ( $this->mVary ) {
211  header( "Vary: " . $this->mVary );
212  }
213  }
214 
223  function checkLastModified( $timestamp ) {
224  global $wgCachePages, $wgCacheEpoch, $wgUser;
225  $fname = 'AjaxResponse::checkLastModified';
226 
227  if ( !$timestamp || $timestamp == '19700101000000' ) {
228  wfDebug( "$fname: CACHE DISABLED, NO TIMESTAMP", 'private' );
229  return false;
230  }
231 
232  if ( !$wgCachePages ) {
233  wfDebug( "$fname: CACHE DISABLED", 'private' );
234  return false;
235  }
236 
237  $timestamp = wfTimestamp( TS_MW, $timestamp );
238  $lastmod = wfTimestamp( TS_RFC2822, max( $timestamp, $wgUser->getTouched(), $wgCacheEpoch ) );
239 
240  if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
241  # IE sends sizes after the date like this:
242  # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
243  # this breaks strtotime().
244  $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
245  $modsinceTime = strtotime( $modsince );
246  $ismodsince = wfTimestamp( TS_MW, $modsinceTime ?: 1 );
247  wfDebug( "$fname: -- client send If-Modified-Since: $modsince", 'private' );
248  wfDebug( "$fname: -- we might send Last-Modified : $lastmod", 'private' );
249 
250  if ( ( $ismodsince >= $timestamp )
251  && $wgUser->validateCache( $ismodsince ) &&
252  $ismodsince >= $wgCacheEpoch
253  ) {
254  ini_set( 'zlib.output_compression', 0 );
255  $this->setResponseCode( 304 );
256  $this->disable();
257  $this->mLastModified = $lastmod;
258 
259  wfDebug( "$fname: CACHED client: $ismodsince ; user: {$wgUser->getTouched()} ; " .
260  "page: $timestamp ; site $wgCacheEpoch", 'private' );
261 
262  return true;
263  } else {
264  wfDebug( "$fname: READY client: $ismodsince ; user: {$wgUser->getTouched()} ; " .
265  "page: $timestamp ; site $wgCacheEpoch", 'private' );
266  $this->mLastModified = $lastmod;
267  }
268  } else {
269  wfDebug( "$fname: client did not send If-Modified-Since header", 'private' );
270  $this->mLastModified = $lastmod;
271  }
272  return false;
273  }
274 
280  function loadFromMemcached( $mckey, $touched ) {
281  if ( !$touched ) {
282  return false;
283  }
284 
285  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
286  $mcvalue = $cache->get( $mckey );
287  if ( $mcvalue ) {
288  # Check to see if the value has been invalidated
289  if ( $touched <= $mcvalue['timestamp'] ) {
290  wfDebug( "Got $mckey from cache" );
291  $this->mText = $mcvalue['value'];
292 
293  return true;
294  } else {
295  wfDebug( "$mckey has expired" );
296  }
297  }
298 
299  return false;
300  }
301 
307  function storeInMemcached( $mckey, $expiry = 86400 ) {
308  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
309  $cache->set( $mckey,
310  [
311  'timestamp' => wfTimestampNow(),
312  'value' => $this->mText
313  ],
314  $expiry
315  );
316 
317  return true;
318  }
319 }
sendHeaders()
Construct the header and output it.
printText()
Output text.
setCacheDuration( $duration)
Set the number of seconds to get the response cached by a proxy.
disable()
Disable output.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
setContentType( $type)
Set the HTTP header Content-Type.
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 MediaWikiServices
Definition: injection.txt:23
$mLastModified
Date for the HTTP header Last-modified.
Config $mConfig
$mResponseCode
HTTP response code.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
setVary( $vary)
Set the HTTP Vary header.
loadFromMemcached( $mckey, $touched)
$wgCachePages
Allow client-side caching of pages.
Interface for configuration instances.
Definition: Config.php:28
Handle responses for Ajax requests (send headers, print content, that sort of thing) ...
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$mText
Content of our HTTP response.
addText( $text)
Add content to the response.
$mDisabled
Disables output.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
$cache
Definition: mcc.php:33
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
$mVary
HTTP Vary header.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
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
checkLastModified( $timestamp)
checkLastModified tells the client to use the client-cached response if possible. ...
$mContentType
HTTP header Content-Type.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
storeInMemcached( $mckey, $expiry=86400)
__construct( $text=null, Config $config=null)
$wgCacheEpoch
Set this to current time to invalidate all prior cached pages.
$mCacheDuration
Number of seconds to get the response cached by a proxy.
setResponseCode( $code)
Set the HTTP response code.