MediaWiki  master
MediaWiki.php
Go to the documentation of this file.
1 <?php
23 use Liuggio\StatsdClient\Sender\SocketSender;
24 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
28 use Psr\Log\LoggerInterface;
31 use Wikimedia\ScopedCallback;
32 
36 class MediaWiki {
37  use ProtectedHookAccessorTrait;
38 
40  private $context;
42  private $config;
43 
45  private $action;
48 
50  private const DEFER_FASTCGI_FINISH_REQUEST = 1;
52  private const DEFER_SET_LENGTH_AND_FLUSH = 2;
54  private const DEFER_CLI_MODE = 3;
55 
59  public function __construct( IContextSource $context = null ) {
60  $this->context = $context ?: RequestContext::getMain();
61  $this->config = $this->context->getConfig();
62 
63  if ( $this->config->get( 'CommandLineMode' ) ) {
64  $this->postSendStrategy = self::DEFER_CLI_MODE;
65  } elseif ( function_exists( 'fastcgi_finish_request' ) ) {
66  $this->postSendStrategy = self::DEFER_FASTCGI_FINISH_REQUEST;
67  } else {
68  $this->postSendStrategy = self::DEFER_SET_LENGTH_AND_FLUSH;
69  }
70  }
71 
78  private function parseTitle() {
79  $request = $this->context->getRequest();
80  $curid = $request->getInt( 'curid' );
81  $title = $request->getVal( 'title' );
82  $action = $request->getVal( 'action' );
83 
84  if ( $curid ) {
85  // URLs like this are generated by RC, because rc_title isn't always accurate
86  $ret = Title::newFromID( $curid );
87  } else {
88  $ret = Title::newFromURL( $title );
89  if ( $ret !== null ) {
90  // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
91  // in wikitext links to tell Parser to make a direct file link
92  if ( $ret->getNamespace() === NS_MEDIA ) {
93  $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
94  }
95  // Check variant links so that interwiki links don't have to worry
96  // about the possible different language variants
97  $services = MediaWikiServices::getInstance();
98  $languageConverter = $services
99  ->getLanguageConverterFactory()
100  ->getLanguageConverter( $services->getContentLanguage() );
101  if ( $languageConverter->hasVariants() && !$ret->exists() ) {
102  $languageConverter->findVariantLink( $title, $ret );
103  }
104  }
105  }
106 
107  // If title is not provided, always allow oldid and diff to set the title.
108  // If title is provided, allow oldid and diff to override the title, unless
109  // we are talking about a special page which might use these parameters for
110  // other purposes.
111  if ( $ret === null || !$ret->isSpecialPage() ) {
112  // We can have urls with just ?diff=,?oldid= or even just ?diff=
113  $oldid = $request->getInt( 'oldid' );
114  $oldid = $oldid ?: $request->getInt( 'diff' );
115  // Allow oldid to override a changed or missing title
116  if ( $oldid ) {
117  $revRecord = MediaWikiServices::getInstance()
118  ->getRevisionLookup()
119  ->getRevisionById( $oldid );
120  if ( $revRecord ) {
122  $revRecord->getPageAsLinkTarget()
123  );
124  }
125  }
126  }
127 
128  if ( $ret === null && $request->getCheck( 'search' ) ) {
129  // Compatibility with old search URLs which didn't use Special:Search
130  // Just check for presence here, so blank requests still
131  // show the search page when using ugly URLs (T10054).
132  $ret = SpecialPage::getTitleFor( 'Search' );
133  }
134 
135  // Use the main page as default title if nothing else has been provided
136  if ( $ret === null
137  && strval( $title ) === ''
138  && !$request->getCheck( 'curid' )
139  && $action !== 'delete'
140  ) {
141  $ret = Title::newMainPage();
142  }
143 
144  if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
145  // If we get here, we definitely don't have a valid title; throw an exception.
146  // Try to get detailed invalid title exception first, fall back to MalformedTitleException.
148  throw new MalformedTitleException( 'badtitletext', $title );
149  }
150 
151  return $ret;
152  }
153 
158  public function getTitle() {
159  if ( !$this->context->hasTitle() ) {
160  try {
161  $this->context->setTitle( $this->parseTitle() );
162  } catch ( MalformedTitleException $ex ) {
163  $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
164  }
165  }
166  return $this->context->getTitle();
167  }
168 
174  public function getAction(): string {
175  if ( $this->action === null ) {
176  $this->action = Action::getActionName( $this->context );
177  }
178 
179  return $this->action;
180  }
181 
194  private function performRequest() {
195  global $wgTitle;
196 
197  $request = $this->context->getRequest();
198  $requestTitle = $title = $this->context->getTitle();
199  $output = $this->context->getOutput();
200  $user = $this->context->getUser();
201 
202  if ( $request->getVal( 'printable' ) === 'yes' ) {
203  $output->setPrintable();
204  }
205 
206  $this->getHookRunner()->onBeforeInitialize( $title, null, $output, $user, $request, $this );
207 
208  // Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
209  if ( $title === null || ( $title->getDBkey() == '' && !$title->isExternal() )
210  || $title->isSpecial( 'Badtitle' )
211  ) {
212  $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
213  try {
214  $this->parseTitle();
215  } catch ( MalformedTitleException $ex ) {
216  throw new BadTitleError( $ex );
217  }
218  throw new BadTitleError();
219  }
220 
221  // Check user's permissions to read this page.
222  // We have to check here to catch special pages etc.
223  // We will check again in Article::view().
224  $permissionStatus = PermissionStatus::newEmpty();
225  if ( !$this->context->getAuthority()->authorizeRead( 'read', $title, $permissionStatus ) ) {
226  // T34276: allowing the skin to generate output with $wgTitle or
227  // $this->context->title set to the input title would allow anonymous users to
228  // determine whether a page exists, potentially leaking private data. In fact, the
229  // curid and oldid request parameters would allow page titles to be enumerated even
230  // when they are not guessable. So we reset the title to Special:Badtitle before the
231  // permissions error is displayed.
232 
233  // The skin mostly uses $this->context->getTitle() these days, but some extensions
234  // still use $wgTitle.
235  $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
236  $this->context->setTitle( $badTitle );
237  $wgTitle = $badTitle;
238 
239  throw new PermissionsError( 'read', $permissionStatus );
240  }
241 
242  // Interwiki redirects
243  if ( $title->isExternal() ) {
244  $rdfrom = $request->getVal( 'rdfrom' );
245  if ( $rdfrom ) {
246  $url = $title->getFullURL( [ 'rdfrom' => $rdfrom ] );
247  } else {
248  $query = $request->getValues();
249  unset( $query['title'] );
250  $url = $title->getFullURL( $query );
251  }
252  // Check for a redirect loop
253  if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
254  && $title->isLocal()
255  ) {
256  // 301 so google et al report the target as the actual url.
257  $output->redirect( $url, 301 );
258  } else {
259  $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
260  try {
261  $this->parseTitle();
262  } catch ( MalformedTitleException $ex ) {
263  throw new BadTitleError( $ex );
264  }
265  throw new BadTitleError();
266  }
267  // Handle any other redirects.
268  // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
269  } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
270  // Prevent information leak via Special:MyPage et al (T109724)
271  $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
272  if ( $title->isSpecialPage() ) {
273  $specialPage = $spFactory->getPage( $title->getDBkey() );
274  if ( $specialPage instanceof RedirectSpecialPage ) {
275  $specialPage->setContext( $this->context );
276  if ( $this->config->get( 'HideIdentifiableRedirects' )
277  && $specialPage->personallyIdentifiableTarget()
278  ) {
279  list( , $subpage ) = $spFactory->resolveAlias( $title->getDBkey() );
280  $target = $specialPage->getRedirect( $subpage );
281  // Target can also be true. We let that case fall through to normal processing.
282  if ( $target instanceof Title ) {
283  if ( $target->isExternal() ) {
284  // Handle interwiki redirects
285  $target = SpecialPage::getTitleFor(
286  'GoToInterwiki',
287  'force/' . $target->getPrefixedDBkey()
288  );
289  }
290 
291  $query = $specialPage->getRedirectQuery( $subpage ) ?: [];
292  $request = new DerivativeRequest( $this->context->getRequest(), $query );
293  $request->setRequestURL( $this->context->getRequest()->getRequestURL() );
294  $this->context->setRequest( $request );
295  // Do not varnish cache these. May vary even for anons
296  $this->context->getOutput()->lowerCdnMaxage( 0 );
297  $this->context->setTitle( $target );
298  $wgTitle = $target;
299  // Reset action type cache. (Special pages have only view)
300  $this->action = null;
301  $title = $target;
302  $output->addJsConfigVars( [
303  'wgInternalRedirectTargetUrl' => $target->getLinkURL( $query ),
304  ] );
305  $output->addModules( 'mediawiki.action.view.redirect' );
306  }
307  }
308  }
309  }
310 
311  // Special pages ($title may have changed since if statement above)
312  if ( $title->isSpecialPage() ) {
313  // Actions that need to be made when we have a special pages
314  $spFactory->executePath( $title, $this->context );
315  } else {
316  // ...otherwise treat it as an article view. The article
317  // may still be a wikipage redirect to another article or URL.
318  $article = $this->initializeArticle();
319  if ( is_object( $article ) ) {
320  $this->performAction( $article, $requestTitle );
321  } elseif ( is_string( $article ) ) {
322  $output->redirect( $article );
323  } else {
324  throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
325  . " returned neither an object nor a URL" );
326  }
327  }
328  $output->considerCacheSettingsFinal();
329  }
330  }
331 
354  private function tryNormaliseRedirect( Title $title ) {
355  $request = $this->context->getRequest();
356  $output = $this->context->getOutput();
357 
358  if ( $request->getVal( 'action', 'view' ) != 'view'
359  || $request->wasPosted()
360  || ( $request->getCheck( 'title' )
361  && $title->getPrefixedDBkey() == $request->getVal( 'title' ) )
362  || count( $request->getValueNames( [ 'action', 'title' ] ) )
363  || !$this->getHookRunner()->onTestCanonicalRedirect( $request, $title, $output )
364  ) {
365  return false;
366  }
367 
368  if ( $this->config->get( 'MainPageIsDomainRoot' ) && $request->getRequestURL() === '/' ) {
369  return false;
370  }
371 
372  if ( $title->isSpecialPage() ) {
373  list( $name, $subpage ) = MediaWikiServices::getInstance()->getSpecialPageFactory()->
374  resolveAlias( $title->getDBkey() );
375  if ( $name ) {
376  $title = SpecialPage::getTitleFor( $name, $subpage );
377  }
378  }
379  // Redirect to canonical url, make it a 301 to allow caching
380  $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
381  if ( $targetUrl == $request->getFullRequestURL() ) {
382  $message = "Redirect loop detected!\n\n" .
383  "This means the wiki got confused about what page was " .
384  "requested; this sometimes happens when moving a wiki " .
385  "to a new server or changing the server configuration.\n\n";
386 
387  if ( $this->config->get( 'UsePathInfo' ) ) {
388  $message .= "The wiki is trying to interpret the page " .
389  "title from the URL path portion (PATH_INFO), which " .
390  "sometimes fails depending on the web server. Try " .
391  "setting \"\$wgUsePathInfo = false;\" in your " .
392  "LocalSettings.php, or check that \$wgArticlePath " .
393  "is correct.";
394  } else {
395  $message .= "Your web server was detected as possibly not " .
396  "supporting URL path components (PATH_INFO) correctly; " .
397  "check your LocalSettings.php for a customized " .
398  "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
399  "to true.";
400  }
401  throw new HttpError( 500, $message );
402  }
403  $output->setCdnMaxage( 1200 );
404  $output->redirect( $targetUrl, '301' );
405  return true;
406  }
407 
414  private function initializeArticle() {
415  $title = $this->context->getTitle();
416  $services = MediaWikiServices::getInstance();
417  if ( $this->context->canUseWikiPage() ) {
418  // Try to use request context wiki page, as there
419  // is already data from db saved in per process
420  // cache there from this->getAction() call.
421  $page = $this->context->getWikiPage();
422  } else {
423  // This case should not happen, but just in case.
424  // @TODO: remove this or use an exception
425  $page = $services->getWikiPageFactory()->newFromTitle( $title );
426  $this->context->setWikiPage( $page );
427  wfWarn( "RequestContext::canUseWikiPage() returned false" );
428  }
429 
430  // Make GUI wrapper for the WikiPage
431  $article = Article::newFromWikiPage( $page, $this->context );
432 
433  // Skip some unnecessary code if the content model doesn't support redirects
434  if ( !$services->getContentHandlerFactory()
435  ->getContentHandler( $title->getContentModel() )
436  ->supportsRedirects()
437  ) {
438  return $article;
439  }
440 
441  $request = $this->context->getRequest();
442 
443  // Namespace might change when using redirects
444  // Check for redirects ...
445  $action = $request->getVal( 'action', 'view' );
446  $file = ( $page instanceof WikiFilePage ) ? $page->getFile() : null;
447  if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
448  && !$request->getVal( 'oldid' ) // ... and are not old revisions
449  && !$request->getVal( 'diff' ) // ... and not when showing diff
450  && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
451  // ... and the article is not a non-redirect image page with associated file
452  && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
453  ) {
454  // Give extensions a change to ignore/handle redirects as needed
455  $ignoreRedirect = $target = false;
456 
457  $this->getHookRunner()->onInitializeArticleMaybeRedirect( $title, $request,
458  $ignoreRedirect, $target, $article );
459  $page = $article->getPage(); // reflect any hook changes
460 
461  // Follow redirects only for... redirects.
462  // If $target is set, then a hook wanted to redirect.
463  if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) {
464  // Is the target already set by an extension?
465  $target = $target ?: $page->followRedirect();
466  if ( is_string( $target ) && !$this->config->get( 'DisableHardRedirects' ) ) {
467  // we'll need to redirect
468  return $target;
469  }
470  if ( is_object( $target ) ) {
471  // Rewrite environment to redirected article
472  $rpage = $services->getWikiPageFactory()->newFromTitle( $target );
473  $rpage->loadPageData();
474  if ( $rpage->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
475  $rarticle = Article::newFromWikiPage( $rpage, $this->context );
476  $rarticle->setRedirectedFrom( $title );
477 
478  $article = $rarticle;
479  $this->context->setTitle( $target );
480  $this->context->setWikiPage( $article->getPage() );
481  }
482  }
483  } else {
484  // Article may have been changed by hook
485  $this->context->setTitle( $article->getTitle() );
486  $this->context->setWikiPage( $article->getPage() );
487  }
488  }
489 
490  return $article;
491  }
492 
499  private function performAction( Article $article, Title $requestTitle ) {
500  $request = $this->context->getRequest();
501  $output = $this->context->getOutput();
502  $title = $this->context->getTitle();
503  $user = $this->context->getUser();
504  $services = MediaWikiServices::getInstance();
505 
506  if ( !$this->getHookRunner()->onMediaWikiPerformAction(
507  $output, $article, $title, $user, $request, $this )
508  ) {
509  return;
510  }
511 
512  $t = microtime( true );
513  $actionName = $this->getAction();
514  $action = Action::factory( $actionName, $article, $this->context );
515 
516  if ( $action instanceof Action ) {
517  // Narrow DB query expectations for this HTTP request
518  $trxLimits = $this->config->get( 'TrxProfilerLimits' );
519  $trxProfiler = Profiler::instance()->getTransactionProfiler();
520  if ( $request->wasPosted() && !$action->doesWrites() ) {
521  $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
522  $request->markAsSafeRequest();
523  }
524 
525  # Let CDN cache things if we can purge them.
526  if ( $this->config->get( 'UseCdn' ) ) {
527  $htmlCacheUpdater = $services->getHtmlCacheUpdater();
528  if ( in_array(
529  // Use PROTO_INTERNAL because that's what HtmlCacheUpdater::getUrls() uses
530  wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
531  $htmlCacheUpdater->getUrls( $requestTitle )
532  )
533  ) {
534  $output->setCdnMaxage( $this->config->get( 'CdnMaxAge' ) );
535  }
536  }
537 
538  $action->show();
539 
540  $runTime = microtime( true ) - $t;
541  $services->getStatsdDataFactory()->timing(
542  'action.' . strtr( $actionName, '.', '_' ) . '.executeTiming',
543  1000 * $runTime
544  );
545  return;
546  }
547 
548  // If we've not found out which action it is by now, it's unknown
549  $output->setStatusCode( 404 );
550  $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
551  }
552 
556  public function run() {
557  try {
558  $this->setDBProfilingAgent();
559  $this->main();
560  } catch ( Exception $e ) {
562  $action = $context->getRequest()->getVal( 'action', 'view' );
563  if (
564  $e instanceof DBConnectionError &&
565  $context->hasTitle() &&
566  $context->getTitle()->canExist() &&
567  in_array( $action, [ 'view', 'history' ], true ) &&
569  ) {
570  // Try to use any (even stale) file during outages...
572  if ( $cache->isCached() ) {
573  $cache->loadFromFileCache( $context, HTMLFileCache::MODE_OUTAGE );
574  print MWExceptionRenderer::getHTML( $e );
575  exit;
576  }
577  }
578  MWExceptionHandler::handleException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
579  } catch ( Throwable $e ) {
580  // Type errors and such: at least handle it now and clean up the LBFactory state
581  MWExceptionHandler::handleException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
582  }
583 
584  $this->doPostOutputShutdown();
585  }
586 
590  private function setDBProfilingAgent() {
591  $services = MediaWikiServices::getInstance();
592  $name = $this->context->getUser()->getName();
593  $services->getDBLoadBalancerFactory()->setAgentName(
594  mb_strlen( $name ) > 15 ? mb_substr( $name, 0, 15 ) . '...' : $name
595  );
596  }
597 
601  private function schedulePostSendJobs() {
602  $jobRunRate = $this->config->get( 'JobRunRate' );
603  if (
604  // Recursion guard
605  $this->getTitle()->isSpecial( 'RunJobs' ) ||
606  // Short circuit if there is nothing to do
607  ( $jobRunRate <= 0 || wfReadOnly() ) ||
608  // Avoid blocking the client on stock apache; see doPostOutputShutdown()
609  (
610  $this->context->getRequest()->getMethod() === 'HEAD' ||
611  $this->context->getRequest()->getHeader( 'If-Modified-Since' )
612  )
613  ) {
614  return;
615  }
616 
617  if ( $jobRunRate < 1 ) {
618  $max = mt_getrandmax();
619  if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
620  return; // the higher the job run rate, the less likely we return here
621  }
622  $n = 1;
623  } else {
624  $n = intval( $jobRunRate );
625  }
626 
627  if ( wfReadOnly() ) {
628  return;
629  }
630 
631  // Note that DeferredUpdates will catch and log any errors (T88312)
632  DeferredUpdates::addUpdate( new TransactionRoundDefiningUpdate( function () use ( $n ) {
633  $logger = LoggerFactory::getInstance( 'runJobs' );
634  if ( $this->config->get( 'RunJobsAsync' ) ) {
635  // Send an HTTP request to the job RPC entry point if possible
636  $invokedWithSuccess = $this->triggerAsyncJobs( $n, $logger );
637  if ( !$invokedWithSuccess ) {
638  // Fall back to blocking on running the job(s)
639  $logger->warning( "Jobs switched to blocking; Special:RunJobs disabled" );
640  $this->triggerSyncJobs( $n );
641  }
642  } else {
643  $this->triggerSyncJobs( $n );
644  }
645  }, __METHOD__ ) );
646  }
647 
653  public function doPreOutputCommit( callable $postCommitWork = null ) {
654  self::preOutputCommit( $this->context, $postCommitWork );
655  }
656 
668  public static function preOutputCommit(
669  IContextSource $context, callable $postCommitWork = null
670  ) {
672  $request = $context->getRequest();
673  $output = $context->getOutput();
674  $services = MediaWikiServices::getInstance();
675  $lbFactory = $services->getDBLoadBalancerFactory();
676 
677  // Try to make sure that all RDBMs, session, and other storage updates complete
678  ignore_user_abort( true );
679 
680  // Commit all RDBMs changes from the main transaction round
681  $lbFactory->commitMasterChanges(
682  __METHOD__,
683  // Abort if any transaction was too big
684  [ 'maxWriteDuration' => $config->get( 'MaxUserDBWriteDuration' ) ]
685  );
686  wfDebug( __METHOD__ . ': primary transaction round committed' );
687 
688  // Run updates that need to block the client or affect output (this is the last chance)
689  DeferredUpdates::doUpdates( 'run', DeferredUpdates::PRESEND );
690  wfDebug( __METHOD__ . ': pre-send deferred updates completed' );
691 
692  // Persist the session to avoid race conditions on subsequent requests by the client
693  $request->getSession()->save(); // T214471
694  wfDebug( __METHOD__ . ': session changes committed' );
695 
696  // Subsequent requests by the client should see the DB replication positions written
697  // during the shutdown() call below, even if the position store itself has asynchronous
698  // replication. Setting the cpPosIndex cookie is normally enough. However, this might not
699  // work for cross-domain redirects to foreign wikis, so set the ?cpPoxIndex in that case.
700  $isCrossWikiRedirect = (
701  $output->getRedirect() &&
702  $lbFactory->hasOrMadeRecentMasterChanges( INF ) &&
703  self::getUrlDomainDistance( $output->getRedirect() ) === 'remote'
704  );
705 
706  // Persist replication positions for DBs modified by this request (at this point).
707  // These help provide "session consistency" for the client on their next requests.
708  $cpIndex = null;
709  $cpClientId = null;
710  $lbFactory->shutdown(
711  $lbFactory::SHUTDOWN_NORMAL,
712  $postCommitWork,
713  $cpIndex,
714  $cpClientId
715  );
716  $now = time();
717 
718  $allowHeaders = !( $output->isDisabled() || headers_sent() );
719 
720  if ( $cpIndex > 0 ) {
721  if ( $allowHeaders ) {
722  $expires = $now + ChronologyProtector::POSITION_COOKIE_TTL;
723  $options = [ 'prefix' => '' ];
724  $value = $lbFactory::makeCookieValueFromCPIndex( $cpIndex, $now, $cpClientId );
725  $request->response()->setCookie( 'cpPosIndex', $value, $expires, $options );
726  }
727 
728  if ( $isCrossWikiRedirect ) {
729  if ( $output->getRedirect() ) { // sanity
730  $safeUrl = $lbFactory->appendShutdownCPIndexAsQuery(
731  $output->getRedirect(),
732  $cpIndex
733  );
734  $output->redirect( $safeUrl );
735  } else {
737  new LogicException( "No redirect; cannot append cpPosIndex parameter." ),
738  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
739  );
740  }
741  }
742  }
743 
744  if ( $allowHeaders ) {
745  // Set a cookie to tell all CDN edge nodes to "stick" the user to the DC that
746  // handles this POST request (e.g. the "primary" data center). Also have the user
747  // briefly bypass CDN so ChronologyProtector works for cacheable URLs.
748  if ( $request->wasPosted() && $lbFactory->hasOrMadeRecentMasterChanges() ) {
749  $expires = $now + max(
750  ChronologyProtector::POSITION_COOKIE_TTL,
751  $config->get( 'DataCenterUpdateStickTTL' )
752  );
753  $options = [ 'prefix' => '' ];
754  $request->response()->setCookie( 'UseDC', 'master', $expires, $options );
755  $request->response()->setCookie( 'UseCDNCache', 'false', $expires, $options );
756  }
757 
758  // Avoid letting a few seconds of replica DB lag cause a month of stale data.
759  // This logic is also intimately related to the value of $wgCdnReboundPurgeDelay.
760  if ( $lbFactory->laggedReplicaUsed() ) {
761  $maxAge = $config->get( 'CdnMaxageLagged' );
762  $output->lowerCdnMaxage( $maxAge );
763  $request->response()->header( "X-Database-Lagged: true" );
764  wfDebugLog( 'replication',
765  "Lagged DB used; CDN cache TTL limited to $maxAge seconds" );
766  }
767 
768  // Avoid long-term cache pollution due to message cache rebuild timeouts (T133069)
769  if ( $services->getMessageCache()->isDisabled() ) {
770  $maxAge = $config->get( 'CdnMaxageSubstitute' );
771  $output->lowerCdnMaxage( $maxAge );
772  $request->response()->header( "X-Response-Substitute: true" );
773  }
774 
775  if ( !$output->couldBePublicCached() || $output->haveCacheVaryCookies() ) {
776  // Autoblocks: If this user is autoblocked (and the cookie block feature is enabled
777  // for autoblocks), then set a cookie to track this block.
778  // This has to be done on all logged-in page loads (not just upon saving edits),
779  // because an autoblocked editor might not edit again from the same IP address.
780  //
781  // IP blocks: For anons, if their IP is blocked (and cookie block feature is enabled
782  // for IP blocks), we also want to set the cookie whenever it is safe to do.
783  // Basically from any url that are definitely not publicly cacheable (like viewing
784  // EditPage), or when the HTTP response is personalised for other reasons (e.g. viewing
785  // articles within the same browsing session after making an edit).
786  $user = $context->getUser();
787  $services->getBlockManager()
788  ->trackBlockWithCookie( $user, $request->response() );
789  }
790  }
791  }
792 
797  private static function getUrlDomainDistance( $url ) {
798  $clusterWiki = WikiMap::getWikiFromUrl( $url );
799  if ( WikiMap::isCurrentWikiId( $clusterWiki ) ) {
800  return 'local'; // the current wiki
801  }
802  if ( $clusterWiki !== false ) {
803  return 'remote'; // another wiki in this cluster/farm
804  }
805 
806  return 'external';
807  }
808 
818  public function doPostOutputShutdown() {
819  // Record backend request timing
820  $timing = $this->context->getTiming();
821  $timing->mark( 'requestShutdown' );
822 
823  // Defer everything else if possible...
824  if ( $this->postSendStrategy === self::DEFER_FASTCGI_FINISH_REQUEST ) {
825  // Flush the output to the client, continue processing, and avoid further output
826  fastcgi_finish_request();
827  } elseif ( $this->postSendStrategy === self::DEFER_SET_LENGTH_AND_FLUSH ) {
828  // Flush the output to the client, continue processing, and avoid further output
829  if ( ob_get_level() ) {
830  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
831  @ob_end_flush();
832  }
833  // Flush the web server output buffer to the client/proxy if possible
834  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
835  @flush();
836  }
837 
838  // Since the headers and output where already flushed, disable WebResponse setters
839  // during post-send processing to warnings and unexpected behavior (T191537)
841  // Run post-send updates while preventing further output for sanity...
842  ob_start( static function () {
843  return ''; // do not output uncaught exceptions
844  } );
845  try {
846  $this->restInPeace();
847  } catch ( Throwable $e ) {
849  $e,
850  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
851  );
852  }
853  $length = ob_get_length();
854  if ( $length > 0 ) {
855  trigger_error( __METHOD__ . ": suppressed $length byte(s)", E_USER_NOTICE );
856  }
857  ob_end_clean();
858  }
859 
863  private function main() {
864  global $wgTitle;
865 
866  $output = $this->context->getOutput();
867  $request = $this->context->getRequest();
868 
869  // Send Ajax requests to the Ajax dispatcher.
870  if ( $request->getVal( 'action' ) === 'ajax' ) {
871  // Set a dummy title, because $wgTitle == null might break things
872  $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
873  . __METHOD__
874  );
875  $this->context->setTitle( $title );
876  $wgTitle = $title;
877 
878  $dispatcher = new AjaxDispatcher( $this->config );
879  $dispatcher->performAction( $this->context->getUser() );
880 
881  return;
882  }
883 
884  // Get title from request parameters,
885  // is set on the fly by parseTitle the first time.
886  $title = $this->getTitle();
887  $action = $this->getAction();
888  $wgTitle = $title;
889 
890  // Set DB query expectations for this HTTP request
891  $trxLimits = $this->config->get( 'TrxProfilerLimits' );
892  $trxProfiler = Profiler::instance()->getTransactionProfiler();
893  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
894  if ( $request->hasSafeMethod() ) {
895  $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__ );
896  } else {
897  $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__ );
898  }
899 
900  if ( $this->maybeDoHttpsRedirect() ) {
901  return;
902  }
903 
904  if ( $title->canExist() && HTMLFileCache::useFileCache( $this->context ) ) {
905  // Try low-level file cache hit
907  if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
908  // Check incoming headers to see if client has this cached
909  $timestamp = $cache->cacheTimestamp();
910  if ( !$output->checkLastModified( $timestamp ) ) {
911  $cache->loadFromFileCache( $this->context );
912  }
913  // Do any stats increment/watchlist stuff, assuming user is viewing the
914  // latest revision (which should always be the case for file cache)
915  $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
916  // Tell OutputPage that output is taken care of
917  $output->disable();
918 
919  return;
920  }
921  }
922 
923  try {
924  // Actually do the work of the request and build up any output
925  $this->performRequest();
926  } catch ( ErrorPageError $e ) {
927  // TODO: Should ErrorPageError::report accept a OutputPage parameter?
929  $output->considerCacheSettingsFinal();
930  // T64091: while exceptions are convenient to bubble up GUI errors,
931  // they are not internal application faults. As with normal requests, this
932  // should commit, print the output, do deferred updates, jobs, and profiling.
933  }
934 
935  // GUI-ify and stash the page output in MediaWiki::doPreOutputCommit()
936  $buffer = null;
937  $outputWork = static function () use ( $output, &$buffer ) {
938  if ( $buffer === null ) {
939  $buffer = $output->output( true );
940  }
941 
942  return $buffer;
943  };
944 
945  // Commit any changes in the current transaction round so that:
946  // a) the transaction is not rolled back after success output was already sent
947  // b) error output is not jumbled together with success output in the response
948  $this->doPreOutputCommit( $outputWork );
949  // If needed, push a deferred update to run jobs after the output is send
950  $this->schedulePostSendJobs();
951  // If no exceptions occurred then send the output since it is safe now
952  $this->outputResponsePayload( $outputWork() );
953  }
954 
961  private function shouldDoHttpRedirect() {
962  $request = $this->context->getRequest();
963 
964  // Don't redirect if we're already on HTTPS
965  if ( $request->getProtocol() !== 'http' ) {
966  return false;
967  }
968 
969  $force = $this->config->get( 'ForceHTTPS' );
970 
971  // Don't redirect if $wgServer is explicitly HTTP. We test for this here
972  // by checking whether wfExpandUrl() is able to force HTTPS.
973  if ( !preg_match( '#^https://#', wfExpandUrl( $request->getRequestURL(), PROTO_HTTPS ) ) ) {
974  if ( $force ) {
975  throw new RuntimeException( '$wgForceHTTPS is true but the server is not HTTPS' );
976  }
977  return false;
978  }
979 
980  // Configured $wgForceHTTPS overrides the remaining conditions
981  if ( $force ) {
982  return true;
983  }
984 
985  // Check if HTTPS is required by the session or user preferences
986  return $request->getSession()->shouldForceHTTPS() ||
987  // Check the cookie manually, for paranoia
988  $request->getCookie( 'forceHTTPS', '' ) ||
989  // Avoid checking the user and groups unless it's enabled.
990  (
991  $this->context->getUser()->isRegistered()
992  && $this->context->getUser()->requiresHTTPS()
993  );
994  }
995 
1005  private function maybeDoHttpsRedirect() {
1006  if ( !$this->shouldDoHttpRedirect() ) {
1007  return false;
1008  }
1009 
1010  $request = $this->context->getRequest();
1011  $oldUrl = $request->getFullRequestURL();
1012  $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
1013 
1014  if ( $request->wasPosted() ) {
1015  // This is weird and we'd hope it almost never happens. This
1016  // means that a POST came in via HTTP and policy requires us
1017  // redirecting to HTTPS. It's likely such a request is going
1018  // to fail due to post data being lost, but let's try anyway
1019  // and just log the instance.
1020 
1021  // @todo FIXME: See if we could issue a 307 or 308 here, need
1022  // to see how clients (automated & browser) behave when we do
1023  wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
1024  }
1025  // Setup dummy Title, otherwise OutputPage::redirect will fail
1026  $title = Title::newFromText( 'REDIR', NS_MAIN );
1027  $this->context->setTitle( $title );
1028  // Since we only do this redir to change proto, always send a vary header
1029  $output = $this->context->getOutput();
1030  $output->addVaryHeader( 'X-Forwarded-Proto' );
1031  $output->redirect( $redirUrl );
1032  $output->output();
1033 
1034  return true;
1035  }
1036 
1046  private function outputResponsePayload( $content ) {
1047  // Append any visible profiling data in a manner appropriate for the Content-Type
1048  ob_start();
1049  try {
1050  Profiler::instance()->logDataPageOutputOnly();
1051  } finally {
1052  $content .= ob_get_clean();
1053  }
1054 
1055  // By default, usually one output buffer is active now, either the internal PHP buffer
1056  // started by "output_buffering" in php.ini or the buffer started by MW_SETUP_CALLBACK.
1057  // The MW_SETUP_CALLBACK buffer has an unlimited chunk size, while the internal PHP
1058  // buffer only has an unlimited chunk size if output_buffering="On". If the buffer was
1059  // filled up to the chunk size with printed data, then HTTP headers will have already
1060  // been sent. Also, if the entry point had to stream content to the client, then HTTP
1061  // headers will have already been sent as well, regardless of chunk size.
1062 
1063  // Disable mod_deflate compression since it interferes with the output buffer set
1064  // by MW_SETUP_CALLBACK and can also cause the client to wait on deferred updates
1065  if ( function_exists( 'apache_setenv' ) ) {
1066  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1067  @apache_setenv( 'no-gzip', 1 );
1068  }
1069 
1070  if (
1071  // "Content-Length" is used to prevent clients from waiting on deferred updates
1072  $this->postSendStrategy === self::DEFER_SET_LENGTH_AND_FLUSH &&
1073  // The HTTP response code clearly allows for a meaningful body
1074  in_array( http_response_code(), [ 200, 404 ], true ) &&
1075  // The queue of (post-send) deferred updates is non-empty
1077  // Any buffered output is not spread out accross multiple output buffers
1078  ob_get_level() <= 1 &&
1079  // It is not too late to set additional HTTP headers
1080  !headers_sent()
1081  ) {
1082  $response = $this->context->getRequest()->response();
1083 
1084  $obStatus = ob_get_status();
1085  if ( !isset( $obStatus['name'] ) ) {
1086  // No output buffer is active
1087  $response->header( 'Content-Length: ' . strlen( $content ) );
1088  } elseif ( $obStatus['name'] === 'default output handler' ) {
1089  // Internal PHP "output_buffering" output buffer (note that the internal PHP
1090  // "zlib.output_compression" output buffer is named "zlib output compression")
1091  $response->header( 'Content-Length: ' . ( ob_get_length() + strlen( $content ) ) );
1092  }
1093 
1094  // The MW_SETUP_CALLBACK output buffer ("MediaWiki\OutputHandler::handle") sets
1095  // "Content-Length" where applicable. Other output buffer types might not set this
1096  // header, and since they might mangle or compress the payload, it is not possible
1097  // to determine the final payload size here.
1098 
1099  // Tell the client to immediately end the connection as soon as the response payload
1100  // has been read (informed by any "Content-Length" header). This prevents the client
1101  // from waiting on deferred updates.
1102  // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection
1103  if ( ( $_SERVER['SERVER_PROTOCOL'] ?? '' ) === 'HTTP/1.1' ) {
1104  $response->header( 'Connection: close' );
1105  }
1106  }
1107 
1108  // Print the content *after* adjusting HTTP headers and disabling mod_deflate since
1109  // calling "print" will send the output to the client if there is no output buffer or
1110  // if the output buffer chunk size is reached
1111  print $content;
1112  }
1113 
1117  public function restInPeace() {
1118  // Either all DB and deferred updates should happen or none.
1119  // The latter should not be cancelled due to client disconnect.
1120  ignore_user_abort( true );
1121 
1122  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1123  // Assure deferred updates are not in the main transaction
1124  $lbFactory->commitMasterChanges( __METHOD__ );
1125 
1126  // Loosen DB query expectations since the HTTP client is unblocked
1127  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1128  $trxProfiler->redefineExpectations(
1129  $this->context->getRequest()->hasSafeMethod()
1130  ? $this->config->get( 'TrxProfilerLimits' )['PostSend-GET']
1131  : $this->config->get( 'TrxProfilerLimits' )['PostSend-POST'],
1132  __METHOD__
1133  );
1134 
1135  // Do any deferred jobs; preferring to run them now if a client will not wait on them
1136  DeferredUpdates::doUpdates( 'run' );
1137 
1138  // Log profiling data, e.g. in the database or UDP
1140 
1141  // Commit and close up!
1142  $lbFactory->commitMasterChanges( __METHOD__ );
1143  $lbFactory->shutdown( $lbFactory::SHUTDOWN_NO_CHRONPROT );
1144 
1145  wfDebug( "Request ended normally" );
1146  }
1147 
1156  public static function emitBufferedStatsdData(
1158  ) {
1159  if ( $config->get( 'StatsdServer' ) && $stats->hasData() ) {
1160  try {
1161  $statsdServer = explode( ':', $config->get( 'StatsdServer' ), 2 );
1162  $statsdHost = $statsdServer[0];
1163  $statsdPort = $statsdServer[1] ?? 8125;
1164  $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1165  $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
1166  $statsdClient->setSamplingRates( $config->get( 'StatsdSamplingRates' ) );
1167  $statsdClient->send( $stats->getData() );
1168 
1169  $stats->clearData(); // empty buffer for the next round
1170  } catch ( Exception $e ) {
1171  MWExceptionHandler::logException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
1172  }
1173  }
1174  }
1175 
1179  private function triggerSyncJobs( $n ) {
1180  $scope = Profiler::instance()->getTransactionProfiler()->silenceForScope();
1181  $runner = MediaWikiServices::getInstance()->getJobRunner();
1182  $runner->run( [ 'maxJobs' => $n ] );
1183  ScopedCallback::consume( $scope );
1184  }
1185 
1191  private function triggerAsyncJobs( $n, LoggerInterface $runJobsLogger ) {
1192  $services = MediaWikiServices::getInstance();
1193  // Do not send request if there are probably no jobs
1194  $group = $services->getJobQueueGroupFactory()->makeJobQueueGroup();
1195  if ( !$group->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
1196  return true;
1197  }
1198 
1199  $query = [ 'title' => 'Special:RunJobs',
1200  'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 ];
1201  $query['signature'] = SpecialRunJobs::getQuerySignature(
1202  $query, $this->config->get( 'SecretKey' ) );
1203 
1204  $errno = $errstr = null;
1205  $info = wfParseUrl( $this->config->get( 'CanonicalServer' ) );
1206  $host = $info ? $info['host'] : null;
1207  $port = 80;
1208  if ( isset( $info['scheme'] ) && $info['scheme'] == 'https' ) {
1209  $host = "tls://" . $host;
1210  $port = 443;
1211  }
1212  if ( isset( $info['port'] ) ) {
1213  $port = $info['port'];
1214  }
1215 
1216  Wikimedia\suppressWarnings();
1217  $sock = $host ? fsockopen(
1218  $host,
1219  $port,
1220  $errno,
1221  $errstr,
1222  // If it takes more than 100ms to connect to ourselves there is a problem...
1223  0.100
1224  ) : false;
1225  Wikimedia\restoreWarnings();
1226 
1227  $invokedWithSuccess = true;
1228  if ( $sock ) {
1229  $special = $services->getSpecialPageFactory()->getPage( 'RunJobs' );
1230  $url = $special->getPageTitle()->getCanonicalURL( $query );
1231  $req = (
1232  "POST $url HTTP/1.1\r\n" .
1233  "Host: {$info['host']}\r\n" .
1234  "Connection: Close\r\n" .
1235  "Content-Length: 0\r\n\r\n"
1236  );
1237 
1238  $runJobsLogger->info( "Running $n job(s) via '$url'" );
1239  // Send a cron API request to be performed in the background.
1240  // Give up if this takes too long to send (which should be rare).
1241  stream_set_timeout( $sock, 2 );
1242  $bytes = fwrite( $sock, $req );
1243  if ( $bytes !== strlen( $req ) ) {
1244  $invokedWithSuccess = false;
1245  $runJobsLogger->error( "Failed to start cron API (socket write error)" );
1246  } else {
1247  // Do not wait for the response (the script should handle client aborts).
1248  // Make sure that we don't close before that script reaches ignore_user_abort().
1249  $start = microtime( true );
1250  $status = fgets( $sock );
1251  $sec = microtime( true ) - $start;
1252  if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
1253  $invokedWithSuccess = false;
1254  $runJobsLogger->error( "Failed to start cron API: received '$status' ($sec)" );
1255  }
1256  }
1257  fclose( $sock );
1258  } else {
1259  $invokedWithSuccess = false;
1260  $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
1261  }
1262 
1263  return $invokedWithSuccess;
1264  }
1265 }
Action\getActionName
static getActionName(IContextSource $context)
Get the action that will be executed, not necessarily the one passed passed through the "action" requ...
Definition: Action.php:108
DerivativeRequest
Similar to FauxRequest, but only fakes URL parameters and method (POST or GET) and use the base reque...
Definition: DerivativeRequest.php:36
IBufferingStatsdDataFactory\clearData
clearData()
Clear all buffered data from the factory.
HTMLFileCache\useFileCache
static useFileCache(IContextSource $context, $mode=self::MODE_NORMAL)
Check if pages can be cached for this request/user.
Definition: HTMLFileCache.php:94
MediaWiki\setDBProfilingAgent
setDBProfilingAgent()
Add a comment to future SQL queries for easy SHOW PROCESSLIST interpretation.
Definition: MediaWiki.php:590
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:415
MediaWiki\performAction
performAction(Article $article, Title $requestTitle)
Perform one of the "standard" actions.
Definition: MediaWiki.php:499
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1156
MWExceptionRenderer\getHTML
static getHTML(Throwable $e)
If $wgShowExceptionDetails is true, return a HTML message with a backtrace to the error,...
Definition: MWExceptionRenderer.php:185
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:193
Action\factory
static factory(string $action, Article $article, IContextSource $context=null)
Get an appropriate Action subclass for the given action.
Definition: Action.php:85
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
WikiMap\isCurrentWikiId
static isCurrentWikiId( $wikiId)
Definition: WikiMap.php:321
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:186
HTMLFileCache
Page view caching in the file system.
Definition: HTMLFileCache.php:35
MediaWiki\run
run()
Run the current MediaWiki instance; index.php just calls this.
Definition: MediaWiki.php:556
JobQueueGroup\TYPE_DEFAULT
const TYPE_DEFAULT
Definition: JobQueueGroup.php:64
MediaWiki\restInPeace
restInPeace()
Ends this task peacefully.
Definition: MediaWiki.php:1117
HTMLFileCache\MODE_OUTAGE
const MODE_OUTAGE
Definition: HTMLFileCache.php:37
MediaWiki\getTitle
getTitle()
Get the Title object that we'll be acting on, as specified in the WebRequest.
Definition: MediaWiki.php:158
WikiMap\getWikiFromUrl
static getWikiFromUrl( $url)
Definition: WikiMap.php:224
MediaWiki\main
main()
Determine and send the response headers and body for this web request.
Definition: MediaWiki.php:863
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:119
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
SpecialRunJobs\getQuerySignature
static getQuerySignature(array $query, $secretKey)
Definition: SpecialRunJobs.php:137
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1099
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:107
PermissionsError
Show an error when a user tries to do something they do not have the necessary permissions for.
Definition: PermissionsError.php:32
Title\newMainPage
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:742
RedirectSpecialPage
Shortcut to construct a special page alias.
Definition: RedirectSpecialPage.php:31
IBufferingStatsdDataFactory\hasData
hasData()
Check whether this data factory has any buffered data.
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:958
HttpError
Show an error that looks like an HTTP server error.
Definition: HttpError.php:32
ErrorPageError\report
report( $action=self::SEND_OUTPUT)
Definition: ErrorPageError.php:77
NS_MAIN
const NS_MAIN
Definition: Defines.php:64
Action
Actions are things which can be done to pages (edit, delete, rollback, etc).
Definition: Action.php:43
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:53
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:247
MWExceptionHandler\logException
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
Definition: MWExceptionHandler.php:684
MediaWiki\maybeDoHttpsRedirect
maybeDoHttpsRedirect()
If the stars are suitably aligned, do an HTTP->HTTPS redirect.
Definition: MediaWiki.php:1005
ErrorPageError\STAGE_OUTPUT
const STAGE_OUTPUT
Definition: ErrorPageError.php:32
Config
Interface for configuration instances.
Definition: Config.php:30
MediaWiki\$postSendStrategy
int $postSendStrategy
Class DEFER_* constant; how non-blocking post-response tasks should run.
Definition: MediaWiki.php:47
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:776
Article\newFromWikiPage
static newFromWikiPage(WikiPage $page, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition: Article.php:196
IBufferingStatsdDataFactory\getData
getData()
Return the buffered data from the factory.
MWException
MediaWiki exception.
Definition: MWException.php:29
MWExceptionHandler\handleException
static handleException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Exception handler which simulates the appropriate catch() handling:
Definition: MWExceptionHandler.php:184
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
MediaWiki\triggerSyncJobs
triggerSyncJobs( $n)
Definition: MediaWiki.php:1179
MediaWiki\parseTitle
parseTitle()
Parse the request to get the Title object.
Definition: MediaWiki.php:78
MediaWiki\schedulePostSendJobs
schedulePostSendJobs()
If enabled, after everything specific to this request is done, occasionally run jobs.
Definition: MediaWiki.php:601
MediaWiki
A helper class for throttling authentication attempts.
MediaWiki\DEFER_FASTCGI_FINISH_REQUEST
const DEFER_FASTCGI_FINISH_REQUEST
Call fastcgi_finish_request() to make post-send updates async.
Definition: MediaWiki.php:50
SamplingStatsdClient
A statsd client that applies the sampling rate to the data items before sending them.
Definition: SamplingStatsdClient.php:32
$title
$title
Definition: testCompression.php:38
MediaWiki\doPreOutputCommit
doPreOutputCommit(callable $postCommitWork=null)
Definition: MediaWiki.php:653
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:680
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
MediaWiki\triggerAsyncJobs
triggerAsyncJobs( $n, LoggerInterface $runJobsLogger)
Definition: MediaWiki.php:1191
$wgTitle
$wgTitle
Definition: Setup.php:825
Title\newFromTextThrow
static newFromTextThrow( $text, $defaultNamespace=NS_MAIN)
Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,...
Definition: Title.php:450
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:195
WebResponse\disableForPostSend
static disableForPostSend()
Disable setters for post-send processing.
Definition: WebResponse.php:49
AjaxDispatcher
Object-Oriented Ajax functions.
Definition: AjaxDispatcher.php:37
$content
$content
Definition: router.php:76
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:52
MediaWiki\preOutputCommit
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB and session changes as needed before the client can receive a response (...
Definition: MediaWiki.php:668
MediaWiki\tryNormaliseRedirect
tryNormaliseRedirect(Title $title)
Handle redirects for uncanonical title requests.
Definition: MediaWiki.php:354
MediaWiki\__construct
__construct(IContextSource $context=null)
Definition: MediaWiki.php:59
Title\newFromURL
static newFromURL( $url)
THIS IS NOT THE FUNCTION YOU WANT.
Definition: Title.php:512
IContextSource\getUser
getUser()
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
IContextSource\getTitle
getTitle()
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:327
PROTO_INTERNAL
const PROTO_INTERNAL
Definition: Defines.php:197
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:58
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Consume and execute all pending updates.
Definition: DeferredUpdates.php:173
MediaWiki\Permissions\PermissionStatus
A StatusValue for permission errors.
Definition: PermissionStatus.php:35
DeferredUpdates\pendingUpdatesCount
static pendingUpdatesCount()
Get the number of pending updates for the current execution context.
Definition: DeferredUpdates.php:322
IBufferingStatsdDataFactory
MediaWiki adaptation of StatsdDataFactory that provides buffering functionality.
Definition: IBufferingStatsdDataFactory.php:13
MediaWiki\performRequest
performRequest()
Performs the request.
Definition: MediaWiki.php:194
MediaWiki\$action
string $action
Cache what action this request is.
Definition: MediaWiki.php:45
MediaWiki\getAction
getAction()
Returns the name of the action that will be executed.
Definition: MediaWiki.php:174
Title
Represents a title within MediaWiki.
Definition: Title.php:49
MediaWiki\initializeArticle
initializeArticle()
Initialize the main Article object for "standard" actions (view, etc) Create an Article object for th...
Definition: MediaWiki.php:414
MWExceptionHandler\rollbackMasterChangesAndLog
static rollbackMasterChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Roll back any open database transactions and log the stack trace of the throwable.
Definition: MWExceptionHandler.php:126
$cache
$cache
Definition: mcc.php:33
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:26
Wikimedia\Rdbms\ChronologyProtector
Provide a given client with protection against visible database lag.
Definition: ChronologyProtector.php:136
IContextSource\getConfig
getConfig()
Get the site configuration.
MediaWiki\$config
Config $config
Definition: MediaWiki.php:42
MediaWiki\DEFER_CLI_MODE
const DEFER_CLI_MODE
Do not try to make post-send updates async (e.g.
Definition: MediaWiki.php:54
TransactionRoundDefiningUpdate
Deferrable update that must run outside of any explicit LBFactory transaction round.
Definition: TransactionRoundDefiningUpdate.php:10
Wikimedia\Rdbms\DBConnectionError
@newable
Definition: DBConnectionError.php:27
IContextSource\getRequest
getRequest()
WikiFilePage
Special handling for file pages.
Definition: WikiFilePage.php:31
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1043
$t
$t
Definition: testCompression.php:74
Article
Class for viewing MediaWiki article and history.
Definition: Article.php:50
NS_FILE
const NS_FILE
Definition: Defines.php:70
MediaWiki\shouldDoHttpRedirect
shouldDoHttpRedirect()
Check if an HTTP->HTTPS redirect should be done.
Definition: MediaWiki.php:961
MediaWiki\$context
IContextSource $context
Definition: MediaWiki.php:40
MediaWiki\doPostOutputShutdown
doPostOutputShutdown()
This function does work that can be done after the user gets the HTTP response so they don't block on...
Definition: MediaWiki.php:818
ErrorPageError
An error page which can definitely be safely rendered using the OutputPage.
Definition: ErrorPageError.php:30
MediaWiki\outputResponsePayload
outputResponsePayload( $content)
Print a response body to the current buffer (if there is one) or the server (otherwise)
Definition: MediaWiki.php:1046
MediaWiki\getUrlDomainDistance
static getUrlDomainDistance( $url)
Definition: MediaWiki.php:797
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:561
IContextSource\getOutput
getOutput()
BadTitleError
Show an error page on a badtitle.
Definition: BadTitleError.php:31
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:474
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1064
MediaWiki\DEFER_SET_LENGTH_AND_FLUSH
const DEFER_SET_LENGTH_AND_FLUSH
Set Content-Length and call ob_end_flush()/flush() to make post-send updates async.
Definition: MediaWiki.php:52