MediaWiki  master
MediaWiki.php
Go to the documentation of this file.
1 <?php
23 use Liuggio\StatsdClient\Sender\SocketSender;
26 use Psr\Log\LoggerInterface;
27 use Wikimedia\AtEase;
31 
35 class MediaWiki {
37  private $context;
39  private $config;
40 
42  private $action;
45 
47  private const DEFER_FASTCGI_FINISH_REQUEST = 1;
49  private const DEFER_SET_LENGTH_AND_FLUSH = 2;
50 
54  public function __construct( IContextSource $context = null ) {
55  $this->context = $context ?: RequestContext::getMain();
56  $this->config = $this->context->getConfig();
57  if ( function_exists( 'fastcgi_finish_request' ) ) {
58  $this->postSendStrategy = self::DEFER_FASTCGI_FINISH_REQUEST;
59  } else {
60  $this->postSendStrategy = self::DEFER_SET_LENGTH_AND_FLUSH;
61  }
62  }
63 
70  private function parseTitle() {
71  $request = $this->context->getRequest();
72  $curid = $request->getInt( 'curid' );
73  $title = $request->getVal( 'title' );
74  $action = $request->getVal( 'action' );
75 
76  if ( $request->getCheck( 'search' ) ) {
77  // Compatibility with old search URLs which didn't use Special:Search
78  // Just check for presence here, so blank requests still
79  // show the search page when using ugly URLs (T10054).
80  $ret = SpecialPage::getTitleFor( 'Search' );
81  } elseif ( $curid ) {
82  // URLs like this are generated by RC, because rc_title isn't always accurate
83  $ret = Title::newFromID( $curid );
84  } else {
85  $ret = Title::newFromURL( $title );
86  // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
87  // in wikitext links to tell Parser to make a direct file link
88  if ( $ret !== null && $ret->getNamespace() == NS_MEDIA ) {
89  $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
90  }
91  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
92  // Check variant links so that interwiki links don't have to worry
93  // about the possible different language variants
94  if (
95  $contLang->hasVariants() && $ret !== null && $ret->getArticleID() == 0
96  ) {
97  $contLang->findVariantLink( $title, $ret );
98  }
99  }
100 
101  // If title is not provided, always allow oldid and diff to set the title.
102  // If title is provided, allow oldid and diff to override the title, unless
103  // we are talking about a special page which might use these parameters for
104  // other purposes.
105  if ( $ret === null || !$ret->isSpecialPage() ) {
106  // We can have urls with just ?diff=,?oldid= or even just ?diff=
107  $oldid = $request->getInt( 'oldid' );
108  $oldid = $oldid ?: $request->getInt( 'diff' );
109  // Allow oldid to override a changed or missing title
110  if ( $oldid ) {
111  $rev = Revision::newFromId( $oldid );
112  $ret = $rev ? $rev->getTitle() : $ret;
113  }
114  }
115 
116  // Use the main page as default title if nothing else has been provided
117  if ( $ret === null
118  && strval( $title ) === ''
119  && !$request->getCheck( 'curid' )
120  && $action !== 'delete'
121  ) {
122  $ret = Title::newMainPage();
123  }
124 
125  if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
126  // If we get here, we definitely don't have a valid title; throw an exception.
127  // Try to get detailed invalid title exception first, fall back to MalformedTitleException.
129  throw new MalformedTitleException( 'badtitletext', $title );
130  }
131 
132  return $ret;
133  }
134 
139  public function getTitle() {
140  if ( !$this->context->hasTitle() ) {
141  try {
142  $this->context->setTitle( $this->parseTitle() );
143  } catch ( MalformedTitleException $ex ) {
144  $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
145  }
146  }
147  return $this->context->getTitle();
148  }
149 
155  public function getAction() : string {
156  if ( $this->action === null ) {
157  $this->action = Action::getActionName( $this->context );
158  }
159 
160  return $this->action;
161  }
162 
175  private function performRequest() {
176  global $wgTitle;
177 
178  $request = $this->context->getRequest();
179  $requestTitle = $title = $this->context->getTitle();
180  $output = $this->context->getOutput();
181  $user = $this->context->getUser();
182 
183  if ( $request->getVal( 'printable' ) === 'yes' ) {
184  $output->setPrintable();
185  }
186 
187  $unused = null; // To pass it by reference
188  Hooks::run( 'BeforeInitialize', [ &$title, &$unused, &$output, &$user, $request, $this ] );
189 
190  // Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
191  if ( $title === null || ( $title->getDBkey() == '' && !$title->isExternal() )
192  || $title->isSpecial( 'Badtitle' )
193  ) {
194  $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
195  try {
196  $this->parseTitle();
197  } catch ( MalformedTitleException $ex ) {
198  throw new BadTitleError( $ex );
199  }
200  throw new BadTitleError();
201  }
202 
203  // Check user's permissions to read this page.
204  // We have to check here to catch special pages etc.
205  // We will check again in Article::view().
206  $permErrors = $title->isSpecial( 'RunJobs' )
207  ? [] // relies on HMAC key signature alone
208  : MediaWikiServices::getInstance()->getPermissionManager()
209  ->getPermissionErrors( 'read', $user, $title );
210  if ( count( $permErrors ) ) {
211  // T34276: allowing the skin to generate output with $wgTitle or
212  // $this->context->title set to the input title would allow anonymous users to
213  // determine whether a page exists, potentially leaking private data. In fact, the
214  // curid and oldid request parameters would allow page titles to be enumerated even
215  // when they are not guessable. So we reset the title to Special:Badtitle before the
216  // permissions error is displayed.
217 
218  // The skin mostly uses $this->context->getTitle() these days, but some extensions
219  // still use $wgTitle.
220  $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
221  $this->context->setTitle( $badTitle );
222  $wgTitle = $badTitle;
223 
224  throw new PermissionsError( 'read', $permErrors );
225  }
226 
227  // Interwiki redirects
228  if ( $title->isExternal() ) {
229  $rdfrom = $request->getVal( 'rdfrom' );
230  if ( $rdfrom ) {
231  $url = $title->getFullURL( [ 'rdfrom' => $rdfrom ] );
232  } else {
233  $query = $request->getValues();
234  unset( $query['title'] );
235  $url = $title->getFullURL( $query );
236  }
237  // Check for a redirect loop
238  if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
239  && $title->isLocal()
240  ) {
241  // 301 so google et al report the target as the actual url.
242  $output->redirect( $url, 301 );
243  } else {
244  $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
245  try {
246  $this->parseTitle();
247  } catch ( MalformedTitleException $ex ) {
248  throw new BadTitleError( $ex );
249  }
250  throw new BadTitleError();
251  }
252  // Handle any other redirects.
253  // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
254  } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
255  // Prevent information leak via Special:MyPage et al (T109724)
256  $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
257  if ( $title->isSpecialPage() ) {
258  $specialPage = $spFactory->getPage( $title->getDBkey() );
259  if ( $specialPage instanceof RedirectSpecialPage ) {
260  $specialPage->setContext( $this->context );
261  if ( $this->config->get( 'HideIdentifiableRedirects' )
262  && $specialPage->personallyIdentifiableTarget()
263  ) {
264  list( , $subpage ) = $spFactory->resolveAlias( $title->getDBkey() );
265  $target = $specialPage->getRedirect( $subpage );
266  // Target can also be true. We let that case fall through to normal processing.
267  if ( $target instanceof Title ) {
268  if ( $target->isExternal() ) {
269  // Handle interwiki redirects
270  $target = SpecialPage::getTitleFor(
271  'GoToInterwiki',
272  'force/' . $target->getPrefixedDBkey()
273  );
274  }
275 
276  $query = $specialPage->getRedirectQuery( $subpage ) ?: [];
277  $request = new DerivativeRequest( $this->context->getRequest(), $query );
278  $request->setRequestURL( $this->context->getRequest()->getRequestURL() );
279  $this->context->setRequest( $request );
280  // Do not varnish cache these. May vary even for anons
281  $this->context->getOutput()->lowerCdnMaxage( 0 );
282  $this->context->setTitle( $target );
283  $wgTitle = $target;
284  // Reset action type cache. (Special pages have only view)
285  $this->action = null;
286  $title = $target;
287  $output->addJsConfigVars( [
288  'wgInternalRedirectTargetUrl' => $target->getFullURL( $query ),
289  ] );
290  $output->addModules( 'mediawiki.action.view.redirect' );
291  }
292  }
293  }
294  }
295 
296  // Special pages ($title may have changed since if statement above)
297  if ( $title->isSpecialPage() ) {
298  // Actions that need to be made when we have a special pages
299  $spFactory->executePath( $title, $this->context );
300  } else {
301  // ...otherwise treat it as an article view. The article
302  // may still be a wikipage redirect to another article or URL.
303  $article = $this->initializeArticle();
304  if ( is_object( $article ) ) {
305  $this->performAction( $article, $requestTitle );
306  } elseif ( is_string( $article ) ) {
307  $output->redirect( $article );
308  } else {
309  throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
310  . " returned neither an object nor a URL" );
311  }
312  }
313  $output->considerCacheSettingsFinal();
314  }
315  }
316 
339  private function tryNormaliseRedirect( Title $title ) {
340  $request = $this->context->getRequest();
341  $output = $this->context->getOutput();
342 
343  if ( $request->getVal( 'action', 'view' ) != 'view'
344  || $request->wasPosted()
345  || ( $request->getCheck( 'title' )
346  && $title->getPrefixedDBkey() == $request->getVal( 'title' ) )
347  || count( $request->getValueNames( [ 'action', 'title' ] ) )
348  || !Hooks::run( 'TestCanonicalRedirect', [ $request, $title, $output ] )
349  ) {
350  return false;
351  }
352 
353  if ( $this->config->get( 'MainPageIsDomainRoot' ) && $request->getRequestURL() === '/' ) {
354  return false;
355  }
356 
357  if ( $title->isSpecialPage() ) {
358  list( $name, $subpage ) = MediaWikiServices::getInstance()->getSpecialPageFactory()->
359  resolveAlias( $title->getDBkey() );
360  if ( $name ) {
361  $title = SpecialPage::getTitleFor( $name, $subpage );
362  }
363  }
364  // Redirect to canonical url, make it a 301 to allow caching
365  $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
366  if ( $targetUrl == $request->getFullRequestURL() ) {
367  $message = "Redirect loop detected!\n\n" .
368  "This means the wiki got confused about what page was " .
369  "requested; this sometimes happens when moving a wiki " .
370  "to a new server or changing the server configuration.\n\n";
371 
372  if ( $this->config->get( 'UsePathInfo' ) ) {
373  $message .= "The wiki is trying to interpret the page " .
374  "title from the URL path portion (PATH_INFO), which " .
375  "sometimes fails depending on the web server. Try " .
376  "setting \"\$wgUsePathInfo = false;\" in your " .
377  "LocalSettings.php, or check that \$wgArticlePath " .
378  "is correct.";
379  } else {
380  $message .= "Your web server was detected as possibly not " .
381  "supporting URL path components (PATH_INFO) correctly; " .
382  "check your LocalSettings.php for a customized " .
383  "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
384  "to true.";
385  }
386  throw new HttpError( 500, $message );
387  }
388  $output->setCdnMaxage( 1200 );
389  $output->redirect( $targetUrl, '301' );
390  return true;
391  }
392 
399  private function initializeArticle() {
400  $title = $this->context->getTitle();
401  if ( $this->context->canUseWikiPage() ) {
402  // Try to use request context wiki page, as there
403  // is already data from db saved in per process
404  // cache there from this->getAction() call.
405  $page = $this->context->getWikiPage();
406  } else {
407  // This case should not happen, but just in case.
408  // @TODO: remove this or use an exception
409  $page = WikiPage::factory( $title );
410  $this->context->setWikiPage( $page );
411  wfWarn( "RequestContext::canUseWikiPage() returned false" );
412  }
413 
414  // Make GUI wrapper for the WikiPage
415  $article = Article::newFromWikiPage( $page, $this->context );
416 
417  // Skip some unnecessary code if the content model doesn't support redirects
419  ->getContentHandlerFactory()
420  ->getContentHandler( $title->getContentModel() )
421  ->supportsRedirects()
422  ) {
423  return $article;
424  }
425 
426  $request = $this->context->getRequest();
427 
428  // Namespace might change when using redirects
429  // Check for redirects ...
430  $action = $request->getVal( 'action', 'view' );
431  $file = ( $page instanceof WikiFilePage ) ? $page->getFile() : null;
432  if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
433  && !$request->getVal( 'oldid' ) // ... and are not old revisions
434  && !$request->getVal( 'diff' ) // ... and not when showing diff
435  && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
436  // ... and the article is not a non-redirect image page with associated file
437  && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
438  ) {
439  // Give extensions a change to ignore/handle redirects as needed
440  $ignoreRedirect = $target = false;
441 
442  Hooks::run( 'InitializeArticleMaybeRedirect',
443  [ &$title, &$request, &$ignoreRedirect, &$target, &$article ] );
444  $page = $article->getPage(); // reflect any hook changes
445 
446  // Follow redirects only for... redirects.
447  // If $target is set, then a hook wanted to redirect.
448  if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) {
449  // Is the target already set by an extension?
450  $target = $target ?: $page->followRedirect();
451  if ( is_string( $target ) && !$this->config->get( 'DisableHardRedirects' ) ) {
452  // we'll need to redirect
453  return $target;
454  }
455  if ( is_object( $target ) ) {
456  // Rewrite environment to redirected article
457  $rpage = WikiPage::factory( $target );
458  $rpage->loadPageData();
459  if ( $rpage->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
460  $rarticle = Article::newFromWikiPage( $rpage, $this->context );
461  $rarticle->setRedirectedFrom( $title );
462 
463  $article = $rarticle;
464  $this->context->setTitle( $target );
465  $this->context->setWikiPage( $article->getPage() );
466  }
467  }
468  } else {
469  // Article may have been changed by hook
470  $this->context->setTitle( $article->getTitle() );
471  $this->context->setWikiPage( $article->getPage() );
472  }
473  }
474 
475  return $article;
476  }
477 
484  private function performAction( Article $article, Title $requestTitle ) {
485  $request = $this->context->getRequest();
486  $output = $this->context->getOutput();
487  $title = $this->context->getTitle();
488  $user = $this->context->getUser();
489 
490  if ( !Hooks::run( 'MediaWikiPerformAction',
491  [ $output, $article, $title, $user, $request, $this ] )
492  ) {
493  return;
494  }
495 
496  $act = $this->getAction();
497  $action = Action::factory( $act, $article, $this->context );
498 
499  if ( $action instanceof Action ) {
500  // Narrow DB query expectations for this HTTP request
501  $trxLimits = $this->config->get( 'TrxProfilerLimits' );
502  $trxProfiler = Profiler::instance()->getTransactionProfiler();
503  if ( $request->wasPosted() && !$action->doesWrites() ) {
504  $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
505  $request->markAsSafeRequest();
506  }
507 
508  # Let CDN cache things if we can purge them.
509  if ( $this->config->get( 'UseCdn' ) &&
510  in_array(
511  // Use PROTO_INTERNAL because that's what getCdnUrls() uses
512  wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
513  $requestTitle->getCdnUrls()
514  )
515  ) {
516  $output->setCdnMaxage( $this->config->get( 'CdnMaxAge' ) );
517  }
518 
519  $action->show();
520  return;
521  }
522 
523  // If we've not found out which action it is by now, it's unknown
524  $output->setStatusCode( 404 );
525  $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
526  }
527 
531  public function run() {
532  try {
533  $this->setDBProfilingAgent();
534  try {
535  $this->main();
536  } catch ( ErrorPageError $e ) {
537  $out = $this->context->getOutput();
538  // TODO: Should ErrorPageError::report accept a OutputPage parameter?
540  $out->considerCacheSettingsFinal();
541 
542  // T64091: while exceptions are convenient to bubble up GUI errors,
543  // they are not internal application faults. As with normal requests, this
544  // should commit, print the output, do deferred updates, jobs, and profiling.
545  $this->doPreOutputCommit();
546  $out->output(); // display the GUI error
547  }
548  } catch ( Exception $e ) {
550  $action = $context->getRequest()->getVal( 'action', 'view' );
551  if (
552  $e instanceof DBConnectionError &&
553  $context->hasTitle() &&
554  $context->getTitle()->canExist() &&
555  in_array( $action, [ 'view', 'history' ], true ) &&
557  ) {
558  // Try to use any (even stale) file during outages...
560  if ( $cache->isCached() ) {
561  $cache->loadFromFileCache( $context, HTMLFileCache::MODE_OUTAGE );
563  exit;
564  }
565  }
566  // GUI-ify and stash the page output in MediaWiki::doPreOutputCommit() while
567  // ChronologyProtector synchronizes DB positions or replicas across all datacenters.
568  MWExceptionHandler::handleException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
569  } catch ( Throwable $e ) {
570  // Type errors and such: at least handle it now and clean up the LBFactory state
571  MWExceptionHandler::handleException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
572  }
573 
574  $this->doPostOutputShutdown();
575  }
576 
580  private function setDBProfilingAgent() {
581  $services = MediaWikiServices::getInstance();
582  $name = $this->context->getUser()->getName();
583  $services->getDBLoadBalancerFactory()->setAgentName(
584  mb_strlen( $name ) > 15 ? mb_substr( $name, 0, 15 ) . '...' : $name
585  );
586  }
587 
591  private function schedulePostSendJobs() {
592  $jobRunRate = $this->config->get( 'JobRunRate' );
593  if (
594  // Recursion guard
595  $this->getTitle()->isSpecial( 'RunJobs' ) ||
596  // Short circuit if there is nothing to do
597  ( $jobRunRate <= 0 || wfReadOnly() ) ||
598  // Avoid blocking the client on stock apache; see doPostOutputShutdown()
599  (
600  $this->context->getRequest()->getMethod() === 'HEAD' ||
601  $this->context->getRequest()->getHeader( 'If-Modified-Since' )
602  )
603  ) {
604  return;
605  }
606 
607  if ( $jobRunRate < 1 ) {
608  $max = mt_getrandmax();
609  if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
610  return; // the higher the job run rate, the less likely we return here
611  }
612  $n = 1;
613  } else {
614  $n = intval( $jobRunRate );
615  }
616 
617  // Note that DeferredUpdates will catch and log an errors (T88312)
618  DeferredUpdates::addUpdate( new TransactionRoundDefiningUpdate( function () use ( $n ) {
619  $logger = LoggerFactory::getInstance( 'runJobs' );
620  if ( $this->config->get( 'RunJobsAsync' ) ) {
621  // Send an HTTP request to the job RPC entry point if possible
622  $invokedWithSuccess = $this->triggerAsyncJobs( $n, $logger );
623  if ( !$invokedWithSuccess ) {
624  // Fall back to blocking on running the job(s)
625  $logger->warning( "Jobs switched to blocking; Special:RunJobs disabled" );
626  $this->triggerSyncJobs( $n );
627  }
628  } else {
629  $this->triggerSyncJobs( $n );
630  }
631  }, __METHOD__ ) );
632  }
633 
639  public function doPreOutputCommit( callable $postCommitWork = null ) {
640  self::preOutputCommit( $this->context, $postCommitWork );
641  }
642 
654  public static function preOutputCommit(
655  IContextSource $context, callable $postCommitWork = null
656  ) {
658  $request = $context->getRequest();
659  $output = $context->getOutput();
660  $services = MediaWikiServices::getInstance();
661  $lbFactory = $services->getDBLoadBalancerFactory();
662 
663  // Try to make sure that all RDBMs, session, and other storage updates complete
664  ignore_user_abort( true );
665 
666  // Commit all RDBMs changes from the main transaction round
667  $lbFactory->commitMasterChanges(
668  __METHOD__,
669  // Abort if any transaction was too big
670  [ 'maxWriteDuration' => $config->get( 'MaxUserDBWriteDuration' ) ]
671  );
672  wfDebug( __METHOD__ . ': primary transaction round committed' );
673 
674  // Run updates that need to block the client or affect output (this is the last chance)
676  wfDebug( __METHOD__ . ': pre-send deferred updates completed' );
677  // Persist the session to avoid race conditions on subsequent requests by the client
678  $request->getSession()->save(); // T214471
679  wfDebug( __METHOD__ . ': session changes committed' );
680 
681  // Figure out whether to wait for DB replication now or to use some method that assures
682  // that subsequent requests by the client will use the DB replication positions written
683  // during the shutdown() call below; the later requires working around replication lag
684  // of the store containing DB replication positions (e.g. dynomite, mcrouter).
685  list( $flags, $strategy ) = self::getChronProtStrategy( $lbFactory, $output );
686  // Record ChronologyProtector positions for DBs affected in this request at this point
687  $cpIndex = null;
688  $cpClientId = null;
689  $lbFactory->shutdown( $flags, $postCommitWork, $cpIndex, $cpClientId );
690  wfDebug( __METHOD__ . ': LBFactory shutdown completed' );
691 
692  $allowHeaders = !( $output->isDisabled() || headers_sent() );
693  if ( $cpIndex > 0 ) {
694  if ( $allowHeaders ) {
695  $now = time();
696  $expires = $now + ChronologyProtector::POSITION_COOKIE_TTL;
697  $options = [ 'prefix' => '' ];
698  $value = $lbFactory::makeCookieValueFromCPIndex( $cpIndex, $now, $cpClientId );
699  $request->response()->setCookie( 'cpPosIndex', $value, $expires, $options );
700  }
701 
702  if ( $strategy === 'cookie+url' ) {
703  if ( $output->getRedirect() ) { // sanity
704  $safeUrl = $lbFactory->appendShutdownCPIndexAsQuery(
705  $output->getRedirect(),
706  $cpIndex
707  );
708  $output->redirect( $safeUrl );
709  } else {
711  new LogicException( "No redirect; cannot append cpPosIndex parameter." ),
712  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
713  );
714  }
715  }
716  }
717 
718  if ( $allowHeaders ) {
719  // Set a cookie to tell all CDN edge nodes to "stick" the user to the DC that
720  // handles this POST request (e.g. the "master" data center). Also have the user
721  // briefly bypass CDN so ChronologyProtector works for cacheable URLs.
722  if ( $request->wasPosted() && $lbFactory->hasOrMadeRecentMasterChanges() ) {
723  $expires = time() + $config->get( 'DataCenterUpdateStickTTL' );
724  $options = [ 'prefix' => '' ];
725  $request->response()->setCookie( 'UseDC', 'master', $expires, $options );
726  $request->response()->setCookie( 'UseCDNCache', 'false', $expires, $options );
727  }
728 
729  // Avoid letting a few seconds of replica DB lag cause a month of stale data.
730  // This logic is also intimately related to the value of $wgCdnReboundPurgeDelay.
731  if ( $lbFactory->laggedReplicaUsed() ) {
732  $maxAge = $config->get( 'CdnMaxageLagged' );
733  $output->lowerCdnMaxage( $maxAge );
734  $request->response()->header( "X-Database-Lagged: true" );
735  wfDebugLog( 'replication',
736  "Lagged DB used; CDN cache TTL limited to $maxAge seconds" );
737  }
738 
739  // Avoid long-term cache pollution due to message cache rebuild timeouts (T133069)
740  if ( $services->getMessageCache()->isDisabled() ) {
741  $maxAge = $config->get( 'CdnMaxageSubstitute' );
742  $output->lowerCdnMaxage( $maxAge );
743  $request->response()->header( "X-Response-Substitute: true" );
744  }
745 
746  if ( !$output->couldBePublicCached() || $output->haveCacheVaryCookies() ) {
747  // Autoblocks: If this user is autoblocked (and the cookie block feature is enabled
748  // for autoblocks), then set a cookie to track this block.
749  // This has to be done on all logged-in page loads (not just upon saving edits),
750  // because an autoblocked editor might not edit again from the same IP address.
751  //
752  // IP blocks: For anons, if their IP is blocked (and cookie block feature is enabled
753  // for IP blocks), we also want to set the cookie whenever it is safe to do.
754  // Basically from any url that are definitely not publicly cacheable (like viewing
755  // EditPage), or when the HTTP response is personalised for other reasons (e.g. viewing
756  // articles within the same browsing session after making an edit).
757  $user = $context->getUser();
758  $services->getBlockManager()
759  ->trackBlockWithCookie( $user, $request->response() );
760  }
761  }
762  }
763 
769  private static function getChronProtStrategy( ILBFactory $lbFactory, OutputPage $output ) {
770  // Should the client return, their request should observe the new ChronologyProtector
771  // DB positions. This request might be on a foreign wiki domain, so synchronously update
772  // the DB positions in all datacenters to be safe. If this output is not a redirect,
773  // then OutputPage::output() will be relatively slow, meaning that running it in
774  // $postCommitWork should help mask the latency of those updates.
775  $flags = $lbFactory::SHUTDOWN_CHRONPROT_SYNC;
776  $strategy = 'cookie+sync';
777 
778  $allowHeaders = !( $output->isDisabled() || headers_sent() );
779  if ( $output->getRedirect() && $lbFactory->hasOrMadeRecentMasterChanges( INF ) ) {
780  // OutputPage::output() will be fast, so $postCommitWork is useless for masking
781  // the latency of synchronously updating the DB positions in all datacenters.
782  // Try to make use of the time the client spends following redirects instead.
783  $domainDistance = self::getUrlDomainDistance( $output->getRedirect() );
784  if ( $domainDistance === 'local' && $allowHeaders ) {
785  $flags = $lbFactory::SHUTDOWN_CHRONPROT_ASYNC;
786  $strategy = 'cookie'; // use same-domain cookie and keep the URL uncluttered
787  } elseif ( $domainDistance === 'remote' ) {
788  $flags = $lbFactory::SHUTDOWN_CHRONPROT_ASYNC;
789  $strategy = 'cookie+url'; // cross-domain cookie might not work
790  }
791  }
792 
793  return [ $flags, $strategy ];
794  }
795 
800  private static function getUrlDomainDistance( $url ) {
801  $clusterWiki = WikiMap::getWikiFromUrl( $url );
802  if ( WikiMap::isCurrentWikiId( $clusterWiki ) ) {
803  return 'local'; // the current wiki
804  }
805  if ( $clusterWiki !== false ) {
806  return 'remote'; // another wiki in this cluster/farm
807  }
808 
809  return 'external';
810  }
811 
821  public function doPostOutputShutdown() {
822  // Record backend request timing
823  $timing = $this->context->getTiming();
824  $timing->mark( 'requestShutdown' );
825 
826  // Perform the last synchronous operations...
827  try {
828  // Show visible profiling data if enabled (which cannot be post-send)
829  Profiler::instance()->logDataPageOutputOnly();
830  } catch ( Throwable $e ) {
831  // An error may already have been shown in run(), so just log it to be safe
832  MWExceptionHandler::logException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
833  }
834 
835  // Disable WebResponse setters for post-send processing (T191537).
837 
838  // Defer everything else if possible...
839  $callback = function () {
840  try {
841  $this->restInPeace();
842  } catch ( Throwable $e ) {
843  // If this is post-send, then displaying errors can cause broken HTML
845  $e,
846  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
847  );
848  }
849  };
850 
851  if ( $this->postSendStrategy === self::DEFER_FASTCGI_FINISH_REQUEST ) {
852  fastcgi_finish_request();
853  $callback();
854  } else {
855  // Flush PHP and web server output buffers
856  if ( !$this->config->get( 'CommandLineMode' ) ) {
857  AtEase\AtEase::suppressWarnings();
858  if ( ob_get_status() ) {
859  ob_end_flush();
860  }
861  flush();
862  AtEase\AtEase::restoreWarnings();
863  }
864  $callback();
865  }
866  }
867 
871  private function main() {
872  global $wgTitle;
873 
874  $output = $this->context->getOutput();
875  $request = $this->context->getRequest();
876 
877  // Send Ajax requests to the Ajax dispatcher.
878  if ( $request->getVal( 'action' ) === 'ajax' ) {
879  // Set a dummy title, because $wgTitle == null might break things
880  $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
881  . __METHOD__
882  );
883  $this->context->setTitle( $title );
884  $wgTitle = $title;
885 
886  $dispatcher = new AjaxDispatcher( $this->config );
887  $dispatcher->performAction( $this->context->getUser() );
888 
889  return;
890  }
891 
892  // Get title from request parameters,
893  // is set on the fly by parseTitle the first time.
894  $title = $this->getTitle();
895  $action = $this->getAction();
896  $wgTitle = $title;
897 
898  // Set DB query expectations for this HTTP request
899  $trxLimits = $this->config->get( 'TrxProfilerLimits' );
900  $trxProfiler = Profiler::instance()->getTransactionProfiler();
901  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
902  if ( $request->hasSafeMethod() ) {
903  $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__ );
904  } else {
905  $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__ );
906  }
907 
908  // If the user has forceHTTPS set to true, or if the user
909  // is in a group requiring HTTPS, or if they have the HTTPS
910  // preference set, redirect them to HTTPS.
911  // Note: Do this after $wgTitle is setup, otherwise the hooks run from
912  // isLoggedIn() will do all sorts of weird stuff.
913  if (
914  $request->getProtocol() == 'http' &&
915  // switch to HTTPS only when supported by the server
916  preg_match( '#^https://#', wfExpandUrl( $request->getRequestURL(), PROTO_HTTPS ) ) &&
917  (
918  $request->getSession()->shouldForceHTTPS() ||
919  // Check the cookie manually, for paranoia
920  $request->getCookie( 'forceHTTPS', '' ) ||
921  // check for prefixed version that was used for a time in older MW versions
922  $request->getCookie( 'forceHTTPS' ) ||
923  // Avoid checking the user and groups unless it's enabled.
924  (
925  $this->context->getUser()->isLoggedIn()
926  && $this->context->getUser()->requiresHTTPS()
927  )
928  )
929  ) {
930  $oldUrl = $request->getFullRequestURL();
931  $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
932 
933  // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
934  if ( Hooks::run( 'BeforeHttpsRedirect', [ $this->context, &$redirUrl ] ) ) {
935  if ( $request->wasPosted() ) {
936  // This is weird and we'd hope it almost never happens. This
937  // means that a POST came in via HTTP and policy requires us
938  // redirecting to HTTPS. It's likely such a request is going
939  // to fail due to post data being lost, but let's try anyway
940  // and just log the instance.
941 
942  // @todo FIXME: See if we could issue a 307 or 308 here, need
943  // to see how clients (automated & browser) behave when we do
944  wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
945  }
946  // Setup dummy Title, otherwise OutputPage::redirect will fail
947  $title = Title::newFromText( 'REDIR', NS_MAIN );
948  $this->context->setTitle( $title );
949  // Since we only do this redir to change proto, always send a vary header
950  $output->addVaryHeader( 'X-Forwarded-Proto' );
951  $output->redirect( $redirUrl );
952  $output->output();
953 
954  return;
955  }
956  }
957 
958  if ( $title->canExist() && HTMLFileCache::useFileCache( $this->context ) ) {
959  // Try low-level file cache hit
961  if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
962  // Check incoming headers to see if client has this cached
963  $timestamp = $cache->cacheTimestamp();
964  if ( !$output->checkLastModified( $timestamp ) ) {
965  $cache->loadFromFileCache( $this->context );
966  }
967  // Do any stats increment/watchlist stuff, assuming user is viewing the
968  // latest revision (which should always be the case for file cache)
969  $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
970  // Tell OutputPage that output is taken care of
971  $output->disable();
972 
973  return;
974  }
975  }
976 
977  // Actually do the work of the request and build up any output
978  $this->performRequest();
979 
980  // GUI-ify and stash the page output in MediaWiki::doPreOutputCommit() while
981  // ChronologyProtector synchronizes DB positions or replicas across all datacenters.
982  $buffer = null;
983  $outputWork = function () use ( $output, &$buffer ) {
984  if ( $buffer === null ) {
985  $buffer = $output->output( true );
986  }
987 
988  return $buffer;
989  };
990 
991  // Commit any changes in the current transaction round so that:
992  // a) the transaction is not rolled back after success output was already sent
993  // b) error output is not jumbled together with success output in the response
994  $this->doPreOutputCommit( $outputWork );
995  // If needed, push a deferred update to run jobs after the output is send
996  $this->schedulePostSendJobs();
997  // If no exceptions occurred then send the output since it is safe now
998  $this->outputResponsePayload( $outputWork() );
999  }
1000 
1008  private function outputResponsePayload( $content ) {
1009  if (
1010  $this->postSendStrategy === self::DEFER_SET_LENGTH_AND_FLUSH &&
1012  !headers_sent()
1013  ) {
1014  $response = $this->context->getRequest()->response();
1015  // Make the browser indicate the page as "loaded" as soon as it gets all the content
1016  $response->header( 'Connection: close' );
1017  // The client should not be blocked on "post-send" updates. If apache or ob_* decide
1018  // that a response should be gzipped, the entire script will have to finish before
1019  // any data can be sent. Disable compression if there are any post-send updates.
1020  $response->header( 'Content-Encoding: none' );
1021  AtEase\AtEase::suppressWarnings();
1022  ini_set( 'zlib.output_compression', 0 );
1023  if ( function_exists( 'apache_setenv' ) ) {
1024  apache_setenv( 'no-gzip', '1' );
1025  }
1026  AtEase\AtEase::restoreWarnings();
1027  // Also set the Content-Length so that apache does not block waiting on PHP to finish.
1028  // If OutputPage is disabled, then either there is no body (e.g. HTTP 304) and thus no
1029  // Content-Length, or it was taken care of already.
1030  if ( !$this->context->getOutput()->isDisabled() ) {
1031  ob_start();
1032  print $content;
1033  $response->header( 'Content-Length: ' . ob_get_length() );
1034  ob_end_flush();
1035  }
1036  // @TODO: this still blocks on HEAD responses and 304 responses to GETs
1037  } else {
1038  print $content;
1039  }
1040  }
1041 
1045  public function restInPeace() {
1046  // Either all DB and deferred updates should happen or none.
1047  // The latter should not be cancelled due to client disconnect.
1048  ignore_user_abort( true );
1049 
1050  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1051  // Assure deferred updates are not in the main transaction
1052  $lbFactory->commitMasterChanges( __METHOD__ );
1053 
1054  // Loosen DB query expectations since the HTTP client is unblocked
1055  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1056  $trxProfiler->redefineExpectations(
1057  $this->context->getRequest()->hasSafeMethod()
1058  ? $this->config->get( 'TrxProfilerLimits' )['PostSend-GET']
1059  : $this->config->get( 'TrxProfilerLimits' )['PostSend-POST'],
1060  __METHOD__
1061  );
1062 
1063  // Do any deferred jobs; preferring to run them now if a client will not wait on them
1064  DeferredUpdates::doUpdates( 'run' );
1065 
1066  // Log profiling data, e.g. in the database or UDP
1068 
1069  // Commit and close up!
1070  $lbFactory->commitMasterChanges( __METHOD__ );
1071  $lbFactory->shutdown( $lbFactory::SHUTDOWN_NO_CHRONPROT );
1072 
1073  wfDebug( "Request ended normally\n" );
1074  }
1075 
1084  public static function emitBufferedStatsdData(
1086  ) {
1087  if ( $config->get( 'StatsdServer' ) && $stats->hasData() ) {
1088  try {
1089  $statsdServer = explode( ':', $config->get( 'StatsdServer' ), 2 );
1090  $statsdHost = $statsdServer[0];
1091  $statsdPort = $statsdServer[1] ?? 8125;
1092  $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1093  $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
1094  $statsdClient->setSamplingRates( $config->get( 'StatsdSamplingRates' ) );
1095  $statsdClient->send( $stats->getData() );
1096 
1097  $stats->clearData(); // empty buffer for the next round
1098  } catch ( Exception $e ) {
1099  MWExceptionHandler::logException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
1100  }
1101  }
1102  }
1103 
1110  public function triggerJobs() {
1111  $jobRunRate = $this->config->get( 'JobRunRate' );
1112  if ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
1113  return; // recursion guard
1114  } elseif ( $jobRunRate <= 0 || wfReadOnly() ) {
1115  return;
1116  }
1117 
1118  if ( $jobRunRate < 1 ) {
1119  $max = mt_getrandmax();
1120  if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
1121  return; // the higher the job run rate, the less likely we return here
1122  }
1123  $n = 1;
1124  } else {
1125  $n = intval( $jobRunRate );
1126  }
1127 
1128  $logger = LoggerFactory::getInstance( 'runJobs' );
1129 
1130  try {
1131  if ( $this->config->get( 'RunJobsAsync' ) ) {
1132  // Send an HTTP request to the job RPC entry point if possible
1133  $invokedWithSuccess = $this->triggerAsyncJobs( $n, $logger );
1134  if ( !$invokedWithSuccess ) {
1135  // Fall back to blocking on running the job(s)
1136  $logger->warning( "Jobs switched to blocking; Special:RunJobs disabled" );
1137  $this->triggerSyncJobs( $n );
1138  }
1139  } else {
1140  $this->triggerSyncJobs( $n );
1141  }
1142  } catch ( JobQueueError $e ) {
1143  // Do not make the site unavailable (T88312)
1144  MWExceptionHandler::logException( $e, MWExceptionHandler::CAUGHT_BY_ENTRYPOINT );
1145  }
1146  }
1147 
1151  private function triggerSyncJobs( $n ) {
1152  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1153  $old = $trxProfiler->setSilenced( true );
1154  try {
1155  $runner = MediaWikiServices::getInstance()->getJobRunner();
1156  $runner->run( [ 'maxJobs' => $n ] );
1157  } finally {
1158  $trxProfiler->setSilenced( $old );
1159  }
1160  }
1161 
1167  private function triggerAsyncJobs( $n, LoggerInterface $runJobsLogger ) {
1168  // Do not send request if there are probably no jobs
1169  $group = JobQueueGroup::singleton();
1170  if ( !$group->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
1171  return true;
1172  }
1173 
1174  $query = [ 'title' => 'Special:RunJobs',
1175  'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 ];
1176  $query['signature'] = SpecialRunJobs::getQuerySignature(
1177  $query, $this->config->get( 'SecretKey' ) );
1178 
1179  $errno = $errstr = null;
1180  $info = wfParseUrl( $this->config->get( 'CanonicalServer' ) );
1181  $host = $info ? $info['host'] : null;
1182  $port = 80;
1183  if ( isset( $info['scheme'] ) && $info['scheme'] == 'https' ) {
1184  $host = "tls://" . $host;
1185  $port = 443;
1186  }
1187  if ( isset( $info['port'] ) ) {
1188  $port = $info['port'];
1189  }
1190 
1191  Wikimedia\suppressWarnings();
1192  $sock = $host ? fsockopen(
1193  $host,
1194  $port,
1195  $errno,
1196  $errstr,
1197  // If it takes more than 100ms to connect to ourselves there is a problem...
1198  0.100
1199  ) : false;
1200  Wikimedia\restoreWarnings();
1201 
1202  $invokedWithSuccess = true;
1203  if ( $sock ) {
1204  $special = MediaWikiServices::getInstance()->getSpecialPageFactory()->
1205  getPage( 'RunJobs' );
1206  $url = $special->getPageTitle()->getCanonicalURL( $query );
1207  $req = (
1208  "POST $url HTTP/1.1\r\n" .
1209  "Host: {$info['host']}\r\n" .
1210  "Connection: Close\r\n" .
1211  "Content-Length: 0\r\n\r\n"
1212  );
1213 
1214  $runJobsLogger->info( "Running $n job(s) via '$url'" );
1215  // Send a cron API request to be performed in the background.
1216  // Give up if this takes too long to send (which should be rare).
1217  stream_set_timeout( $sock, 2 );
1218  $bytes = fwrite( $sock, $req );
1219  if ( $bytes !== strlen( $req ) ) {
1220  $invokedWithSuccess = false;
1221  $runJobsLogger->error( "Failed to start cron API (socket write error)" );
1222  } else {
1223  // Do not wait for the response (the script should handle client aborts).
1224  // Make sure that we don't close before that script reaches ignore_user_abort().
1225  $start = microtime( true );
1226  $status = fgets( $sock );
1227  $sec = microtime( true ) - $start;
1228  if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
1229  $invokedWithSuccess = false;
1230  $runJobsLogger->error( "Failed to start cron API: received '$status' ($sec)" );
1231  }
1232  }
1233  fclose( $sock );
1234  } else {
1235  $invokedWithSuccess = false;
1236  $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
1237  }
1238 
1239  return $invokedWithSuccess;
1240  }
1241 }
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:150
DerivativeRequest
Similar to FauxRequest, but only fakes URL parameters and method (POST or GET) and use the base reque...
Definition: DerivativeRequest.php:34
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:93
MediaWiki\setDBProfilingAgent
setDBProfilingAgent()
Add a comment to future SQL queries for easy SHOW PROCESSLIST interpretation.
Definition: MediaWiki.php:580
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:332
MediaWiki\performAction
performAction(Article $article, Title $requestTitle)
Perform one of the "standard" actions.
Definition: MediaWiki.php:484
Revision\newFromId
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:118
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1084
PROTO_INTERNAL
const PROTO_INTERNAL
Definition: Defines.php:213
MWExceptionRenderer\getHTML
static getHTML(Throwable $e)
If $wgShowExceptionDetails is true, return a HTML message with a backtrace to the error,...
Definition: MWExceptionRenderer.php:180
$response
$response
Definition: opensearch_desc.php:44
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:63
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:144
HTMLFileCache
Page view caching in the file system.
Definition: HTMLFileCache.php:33
MediaWiki\run
run()
Run the current MediaWiki instance; index.php just calls this.
Definition: MediaWiki.php:531
JobQueueGroup\TYPE_DEFAULT
const TYPE_DEFAULT
Definition: JobQueueGroup.php:47
MediaWiki\restInPeace
restInPeace()
Ends this task peacefully.
Definition: MediaWiki.php:1045
HTMLFileCache\MODE_OUTAGE
const MODE_OUTAGE
Definition: HTMLFileCache.php:35
MediaWiki\getTitle
getTitle()
Get the Title object that we'll be acting on, as specified in the WebRequest.
Definition: MediaWiki.php:139
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:871
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:106
NS_FILE
const NS_FILE
Definition: Defines.php:75
$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:124
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1104
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:83
$wgTitle
if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition: api.php:59
PermissionsError
Show an error when a user tries to do something they do not have the necessary permissions for.
Definition: PermissionsError.php:30
Title\newMainPage
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:657
OutputPage\getRedirect
getRedirect()
Get the URL to redirect to, or an empty string if not redirect URL set.
Definition: OutputPage.php:369
Action\factory
static factory(?string $action, Page $article, IContextSource $context=null)
Get an appropriate Action subclass for the given action.
Definition: Action.php:111
RedirectSpecialPage
Shortcut to construct a special page alias.
Definition: RedirectSpecialPage.php:29
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:992
HttpError
Show an error that looks like an HTTP server error.
Definition: HttpError.php:30
ErrorPageError\report
report( $action=self::SEND_OUTPUT)
Definition: ErrorPageError.php:65
Action
Actions are things which can be done to pages (edit, delete, rollback, etc).
Definition: Action.php:39
MediaWiki\getChronProtStrategy
static getChronProtStrategy(ILBFactory $lbFactory, OutputPage $output)
Definition: MediaWiki.php:769
NS_MAIN
const NS_MAIN
Definition: Defines.php:69
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:175
MWExceptionHandler\logException
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
Definition: MWExceptionHandler.php:645
ErrorPageError\STAGE_OUTPUT
const STAGE_OUTPUT
Definition: ErrorPageError.php:29
Config
Interface for configuration instances.
Definition: Config.php:28
Title\getCdnUrls
getCdnUrls()
Get a list of URLs to purge from the CDN cache when this page changes.
Definition: Title.php:3561
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:58
MediaWiki\$postSendStrategy
int $postSendStrategy
Class DEFER_* constant; how non-blocking post-response tasks should run.
Definition: MediaWiki.php:44
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:793
Article\newFromWikiPage
static newFromWikiPage(WikiPage $page, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition: Article.php:224
IBufferingStatsdDataFactory\getData
getData()
Return the buffered data from the factory.
MWException
MediaWiki exception.
Definition: MWException.php:26
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:143
MWExceptionHandler\handleException
static handleException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Exception handler which simulates the appropriate catch() handling:
Definition: MWExceptionHandler.php:182
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:1151
MediaWiki\parseTitle
parseTitle()
Parse the request to get the Title object.
Definition: MediaWiki.php:70
MediaWiki\schedulePostSendJobs
schedulePostSendJobs()
If enabled, after everything specific to this request is done, occasionally run jobs.
Definition: MediaWiki.php:591
OutputPage\isDisabled
isDisabled()
Return whether the output will be completely disabled.
Definition: OutputPage.php:1151
MediaWiki
A helper class for throttling authentication attempts.
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:211
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:639
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:595
JobQueueError
Definition: JobQueueError.php:28
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:913
OutputPage
This is one of the Core classes and should be read at least once by any new developers.
Definition: OutputPage.php:46
MediaWiki\triggerAsyncJobs
triggerAsyncJobs( $n, LoggerInterface $runJobsLogger)
Definition: MediaWiki.php:1167
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:209
Title\newFromTextThrow
static newFromTextThrow( $text, $defaultNamespace=NS_MAIN)
Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,...
Definition: Title.php:367
MediaWiki\triggerJobs
triggerJobs()
Potentially open a socket and sent an HTTP request back to the server to run a specified number of jo...
Definition: MediaWiki.php:1110
WebResponse\disableForPostSend
static disableForPostSend()
Disable setters for post-send processing.
Definition: WebResponse.php:47
AjaxDispatcher
Object-Oriented Ajax functions.
Definition: AjaxDispatcher.php:37
$content
$content
Definition: router.php:76
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:654
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:57
MediaWiki\tryNormaliseRedirect
tryNormaliseRedirect(Title $title)
Handle redirects for uncanonical title requests.
Definition: MediaWiki.php:339
MediaWiki\__construct
__construct(IContextSource $context=null)
Definition: MediaWiki.php:54
Title\newFromURL
static newFromURL( $url)
THIS IS NOT THE FUNCTION YOU WANT.
Definition: Title.php:417
IContextSource\getUser
getUser()
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:451
IContextSource\getTitle
getTitle()
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:53
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Consume the list of deferred updates and execute them.
Definition: DeferredUpdates.php:171
DeferredUpdates\pendingUpdatesCount
static pendingUpdatesCount()
Get the number of currently enqueued updates in the top-queues.
Definition: DeferredUpdates.php:534
IBufferingStatsdDataFactory
MediaWiki adaptation of StatsdDataFactory that provides buffering functionality.
Definition: IBufferingStatsdDataFactory.php:11
MediaWiki\performRequest
performRequest()
Performs the request.
Definition: MediaWiki.php:175
MediaWiki\$action
string $action
Cache what action this request is.
Definition: MediaWiki.php:42
print
print
Definition: opensearch_desc.php:53
MediaWiki\getAction
getAction()
Returns the name of the action that will be executed.
Definition: MediaWiki.php:155
Title
Represents a title within MediaWiki.
Definition: Title.php:42
MediaWiki\initializeArticle
initializeArticle()
Initialize the main Article object for "standard" actions (view, etc) Create an Article object for th...
Definition: MediaWiki.php:399
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:124
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
$cache
$cache
Definition: mcc.php:33
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:25
DeferredUpdates\PRESEND
const PRESEND
Definition: DeferredUpdates.php:84
Wikimedia\Rdbms\ChronologyProtector
Helper class for mitigating DB replication lag in order to provide "session consistency".
Definition: ChronologyProtector.php:39
IContextSource\getConfig
getConfig()
Get the site configuration.
MediaWiki\$config
Config $config
Definition: MediaWiki.php:39
TransactionRoundDefiningUpdate
Deferrable update that must run outside of any explicit LBFactory transaction round.
Definition: TransactionRoundDefiningUpdate.php:8
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
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:1051
Article
Class for viewing MediaWiki article and history.
Definition: Article.php:45
MediaWiki\$context
IContextSource $context
Definition: MediaWiki.php:37
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:821
Wikimedia\Rdbms\ILBFactory\hasOrMadeRecentMasterChanges
hasOrMadeRecentMasterChanges( $age=null)
Determine if any master connection has pending/written changes from this request.
ErrorPageError
An error page which can definitely be safely rendered using the OutputPage.
Definition: ErrorPageError.php:27
MediaWiki\outputResponsePayload
outputResponsePayload( $content)
Set the actual output and attempt to flush it to the client if necessary.
Definition: MediaWiki.php:1008
MediaWiki\getUrlDomainDistance
static getUrlDomainDistance( $url)
Definition: MediaWiki.php:800
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:476
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:133
IContextSource\getOutput
getOutput()
BadTitleError
Show an error page on a badtitle.
Definition: BadTitleError.php:30
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:491
Wikimedia\Rdbms\ILBFactory
An interface for generating database load balancers.
Definition: ILBFactory.php:33
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1072