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