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