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