3 * Helper class for the index.php entry point.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
27 * The MediaWiki class is the helper class for the index.php entry point.
41 * @var String Cache what action this request is
46 * @param IContextSource|null $context
48 public function __construct( IContextSource
$context = null ) {
50 $context = RequestContext
::getMain();
53 $this->context
= $context;
54 $this->config
= $context->getConfig();
58 * Parse the request to get the Title object
60 * @throws MalformedTitleException If a title has been provided by the user, but is invalid.
61 * @return Title Title object to be $wgTitle
63 private function parseTitle() {
66 $request = $this->context
->getRequest();
67 $curid = $request->getInt( 'curid' );
68 $title = $request->getVal( 'title' );
69 $action = $request->getVal( 'action' );
71 if ( $request->getCheck( 'search' ) ) {
72 // Compatibility with old search URLs which didn't use Special:Search
73 // Just check for presence here, so blank requests still
74 // show the search page when using ugly URLs (bug 8054).
75 $ret = SpecialPage
::getTitleFor( 'Search' );
77 // URLs like this are generated by RC, because rc_title isn't always accurate
78 $ret = Title
::newFromID( $curid );
80 $ret = Title
::newFromURL( $title );
81 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
82 // in wikitext links to tell Parser to make a direct file link
83 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA
) {
84 $ret = Title
::makeTitle( NS_FILE
, $ret->getDBkey() );
86 // Check variant links so that interwiki links don't have to worry
87 // about the possible different language variants
88 if ( count( $wgContLang->getVariants() ) > 1
89 && !is_null( $ret ) && $ret->getArticleID() == 0
91 $wgContLang->findVariantLink( $title, $ret );
95 // If title is not provided, always allow oldid and diff to set the title.
96 // If title is provided, allow oldid and diff to override the title, unless
97 // we are talking about a special page which might use these parameters for
99 if ( $ret === null ||
!$ret->isSpecialPage() ) {
100 // We can have urls with just ?diff=,?oldid= or even just ?diff=
101 $oldid = $request->getInt( 'oldid' );
102 $oldid = $oldid ?
$oldid : $request->getInt( 'diff' );
103 // Allow oldid to override a changed or missing title
105 $rev = Revision
::newFromId( $oldid );
106 $ret = $rev ?
$rev->getTitle() : $ret;
110 // Use the main page as default title if nothing else has been provided
112 && strval( $title ) === ''
113 && !$request->getCheck( 'curid' )
114 && $action !== 'delete'
116 $ret = Title
::newMainPage();
119 if ( $ret === null ||
( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
120 // If we get here, we definitely don't have a valid title; throw an exception.
121 // Try to get detailed invalid title exception first, fall back to MalformedTitleException.
122 Title
::newFromTextThrow( $title );
123 throw new MalformedTitleException( 'badtitletext', $title );
130 * Get the Title object that we'll be acting on, as specified in the WebRequest
133 public function getTitle() {
134 if ( !$this->context
->hasTitle() ) {
136 $this->context
->setTitle( $this->parseTitle() );
137 } catch ( MalformedTitleException
$ex ) {
138 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
141 return $this->context
->getTitle();
145 * Returns the name of the action that will be executed.
147 * @return string Action
149 public function getAction() {
150 if ( $this->action
=== null ) {
151 $this->action
= Action
::getActionName( $this->context
);
154 return $this->action
;
158 * Performs the request.
161 * - local interwiki redirects
166 * @throws MWException|PermissionsError|BadTitleError|HttpError
169 private function performRequest() {
172 $request = $this->context
->getRequest();
173 $requestTitle = $title = $this->context
->getTitle();
174 $output = $this->context
->getOutput();
175 $user = $this->context
->getUser();
177 if ( $request->getVal( 'printable' ) === 'yes' ) {
178 $output->setPrintable();
181 $unused = null; // To pass it by reference
182 Hooks
::run( 'BeforeInitialize', [ &$title, &$unused, &$output, &$user, $request, $this ] );
184 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
185 if ( is_null( $title ) ||
( $title->getDBkey() == '' && !$title->isExternal() )
186 ||
$title->isSpecial( 'Badtitle' )
188 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
191 } catch ( MalformedTitleException
$ex ) {
192 throw new BadTitleError( $ex );
194 throw new BadTitleError();
197 // Check user's permissions to read this page.
198 // We have to check here to catch special pages etc.
199 // We will check again in Article::view().
200 $permErrors = $title->isSpecial( 'RunJobs' )
201 ?
[] // relies on HMAC key signature alone
202 : $title->getUserPermissionsErrors( 'read', $user );
203 if ( count( $permErrors ) ) {
204 // Bug 32276: allowing the skin to generate output with $wgTitle or
205 // $this->context->title set to the input title would allow anonymous users to
206 // determine whether a page exists, potentially leaking private data. In fact, the
207 // curid and oldid request parameters would allow page titles to be enumerated even
208 // when they are not guessable. So we reset the title to Special:Badtitle before the
209 // permissions error is displayed.
211 // The skin mostly uses $this->context->getTitle() these days, but some extensions
212 // still use $wgTitle.
213 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
214 $this->context
->setTitle( $badTitle );
215 $wgTitle = $badTitle;
217 throw new PermissionsError( 'read', $permErrors );
220 // Interwiki redirects
221 if ( $title->isExternal() ) {
222 $rdfrom = $request->getVal( 'rdfrom' );
224 $url = $title->getFullURL( [ 'rdfrom' => $rdfrom ] );
226 $query = $request->getValues();
227 unset( $query['title'] );
228 $url = $title->getFullURL( $query );
230 // Check for a redirect loop
231 if ( !preg_match( '/^' . preg_quote( $this->config
->get( 'Server' ), '/' ) . '/', $url )
234 // 301 so google et al report the target as the actual url.
235 $output->redirect( $url, 301 );
237 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
240 } catch ( MalformedTitleException
$ex ) {
241 throw new BadTitleError( $ex );
243 throw new BadTitleError();
245 // Handle any other redirects.
246 // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
247 } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
248 // Prevent information leak via Special:MyPage et al (T109724)
249 if ( $title->isSpecialPage() ) {
250 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
251 if ( $specialPage instanceof RedirectSpecialPage
) {
252 $specialPage->setContext( $this->context
);
253 if ( $this->config
->get( 'HideIdentifiableRedirects' )
254 && $specialPage->personallyIdentifiableTarget()
256 list( , $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
257 $target = $specialPage->getRedirect( $subpage );
258 // target can also be true. We let that case fall through to normal processing.
259 if ( $target instanceof Title
) {
260 $query = $specialPage->getRedirectQuery() ?
: [];
261 $request = new DerivativeRequest( $this->context
->getRequest(), $query );
262 $request->setRequestURL( $this->context
->getRequest()->getRequestURL() );
263 $this->context
->setRequest( $request );
264 // Do not varnish cache these. May vary even for anons
265 $this->context
->getOutput()->lowerCdnMaxage( 0 );
266 $this->context
->setTitle( $target );
268 // Reset action type cache. (Special pages have only view)
269 $this->action
= null;
271 $output->addJsConfigVars( [
272 'wgInternalRedirectTargetUrl' => $target->getFullURL( $query ),
274 $output->addModules( 'mediawiki.action.view.redirect' );
280 // Special pages ($title may have changed since if statement above)
281 if ( NS_SPECIAL
== $title->getNamespace() ) {
282 // Actions that need to be made when we have a special pages
283 SpecialPageFactory
::executePath( $title, $this->context
);
285 // ...otherwise treat it as an article view. The article
286 // may still be a wikipage redirect to another article or URL.
287 $article = $this->initializeArticle();
288 if ( is_object( $article ) ) {
289 $this->performAction( $article, $requestTitle );
290 } elseif ( is_string( $article ) ) {
291 $output->redirect( $article );
293 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
294 . " returned neither an object nor a URL" );
301 * Handle redirects for uncanonical title requests.
306 * - $wgUsePathInfo URLs.
307 * - URLs with a variant.
308 * - Other non-standard URLs (as long as they have no extra query parameters).
311 * - Normalise title values:
312 * /wiki/Foo%20Bar -> /wiki/Foo_Bar
313 * - Normalise empty title:
314 * /wiki/ -> /wiki/Main
315 * /w/index.php?title= -> /wiki/Main
316 * - Don't redirect anything with query parameters other than 'title' or 'action=view'.
318 * @param Title $title
319 * @return bool True if a redirect was set.
322 private function tryNormaliseRedirect( Title
$title ) {
323 $request = $this->context
->getRequest();
324 $output = $this->context
->getOutput();
326 if ( $request->getVal( 'action', 'view' ) != 'view'
327 ||
$request->wasPosted()
328 ||
( $request->getVal( 'title' ) !== null
329 && $title->getPrefixedDBkey() == $request->getVal( 'title' ) )
330 ||
count( $request->getValueNames( [ 'action', 'title' ] ) )
331 ||
!Hooks
::run( 'TestCanonicalRedirect', [ $request, $title, $output ] )
336 if ( $title->isSpecialPage() ) {
337 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
339 $title = SpecialPage
::getTitleFor( $name, $subpage );
342 // Redirect to canonical url, make it a 301 to allow caching
343 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
344 if ( $targetUrl == $request->getFullRequestURL() ) {
345 $message = "Redirect loop detected!\n\n" .
346 "This means the wiki got confused about what page was " .
347 "requested; this sometimes happens when moving a wiki " .
348 "to a new server or changing the server configuration.\n\n";
350 if ( $this->config
->get( 'UsePathInfo' ) ) {
351 $message .= "The wiki is trying to interpret the page " .
352 "title from the URL path portion (PATH_INFO), which " .
353 "sometimes fails depending on the web server. Try " .
354 "setting \"\$wgUsePathInfo = false;\" in your " .
355 "LocalSettings.php, or check that \$wgArticlePath " .
358 $message .= "Your web server was detected as possibly not " .
359 "supporting URL path components (PATH_INFO) correctly; " .
360 "check your LocalSettings.php for a customized " .
361 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
364 throw new HttpError( 500, $message );
366 $output->setSquidMaxage( 1200 );
367 $output->redirect( $targetUrl, '301' );
372 * Initialize the main Article object for "standard" actions (view, etc)
373 * Create an Article object for the page, following redirects if needed.
375 * @return Article|string An Article, or a string to redirect to another URL
377 private function initializeArticle() {
378 $title = $this->context
->getTitle();
379 if ( $this->context
->canUseWikiPage() ) {
380 // Try to use request context wiki page, as there
381 // is already data from db saved in per process
382 // cache there from this->getAction() call.
383 $page = $this->context
->getWikiPage();
385 // This case should not happen, but just in case.
386 // @TODO: remove this or use an exception
387 $page = WikiPage
::factory( $title );
388 $this->context
->setWikiPage( $page );
389 wfWarn( "RequestContext::canUseWikiPage() returned false" );
392 // Make GUI wrapper for the WikiPage
393 $article = Article
::newFromWikiPage( $page, $this->context
);
395 // Skip some unnecessary code if the content model doesn't support redirects
396 if ( !ContentHandler
::getForTitle( $title )->supportsRedirects() ) {
400 $request = $this->context
->getRequest();
402 // Namespace might change when using redirects
403 // Check for redirects ...
404 $action = $request->getVal( 'action', 'view' );
405 $file = ( $page instanceof WikiFilePage
) ?
$page->getFile() : null;
406 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
407 && !$request->getVal( 'oldid' ) // ... and are not old revisions
408 && !$request->getVal( 'diff' ) // ... and not when showing diff
409 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
410 // ... and the article is not a non-redirect image page with associated file
411 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
413 // Give extensions a change to ignore/handle redirects as needed
414 $ignoreRedirect = $target = false;
416 Hooks
::run( 'InitializeArticleMaybeRedirect',
417 [ &$title, &$request, &$ignoreRedirect, &$target, &$article ] );
418 $page = $article->getPage(); // reflect any hook changes
420 // Follow redirects only for... redirects.
421 // If $target is set, then a hook wanted to redirect.
422 if ( !$ignoreRedirect && ( $target ||
$page->isRedirect() ) ) {
423 // Is the target already set by an extension?
424 $target = $target ?
$target : $page->followRedirect();
425 if ( is_string( $target ) ) {
426 if ( !$this->config
->get( 'DisableHardRedirects' ) ) {
427 // we'll need to redirect
431 if ( is_object( $target ) ) {
432 // Rewrite environment to redirected article
433 $rpage = WikiPage
::factory( $target );
434 $rpage->loadPageData();
435 if ( $rpage->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
436 $rarticle = Article
::newFromWikiPage( $rpage, $this->context
);
437 $rarticle->setRedirectedFrom( $title );
439 $article = $rarticle;
440 $this->context
->setTitle( $target );
441 $this->context
->setWikiPage( $article->getPage() );
445 // Article may have been changed by hook
446 $this->context
->setTitle( $article->getTitle() );
447 $this->context
->setWikiPage( $article->getPage() );
455 * Perform one of the "standard" actions
458 * @param Title $requestTitle The original title, before any redirects were applied
460 private function performAction( Page
$page, Title
$requestTitle ) {
461 $request = $this->context
->getRequest();
462 $output = $this->context
->getOutput();
463 $title = $this->context
->getTitle();
464 $user = $this->context
->getUser();
466 if ( !Hooks
::run( 'MediaWikiPerformAction',
467 [ $output, $page, $title, $user, $request, $this ] )
472 $act = $this->getAction();
473 $action = Action
::factory( $act, $page, $this->context
);
475 if ( $action instanceof Action
) {
476 // Narrow DB query expectations for this HTTP request
477 $trxLimits = $this->config
->get( 'TrxProfilerLimits' );
478 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
479 if ( $request->wasPosted() && !$action->doesWrites() ) {
480 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
481 $request->markAsSafeRequest();
484 # Let CDN cache things if we can purge them.
485 if ( $this->config
->get( 'UseSquid' ) &&
487 // Use PROTO_INTERNAL because that's what getCdnUrls() uses
488 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL
),
489 $requestTitle->getCdnUrls()
492 $output->setCdnMaxage( $this->config
->get( 'SquidMaxage' ) );
498 // NOTE: deprecated hook. Add to $wgActions instead
502 $request->getVal( 'action', 'view' ),
507 $output->setStatusCode( 404 );
508 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
513 * Run the current MediaWiki instance; index.php just calls this
515 public function run() {
517 $this->setDBProfilingAgent();
520 } catch ( ErrorPageError
$e ) {
521 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
522 // they are not internal application faults. As with normal requests, this
523 // should commit, print the output, do deferred updates, jobs, and profiling.
524 $this->doPreOutputCommit();
525 $e->report(); // display the GUI error
527 } catch ( Exception
$e ) {
528 $context = $this->context
;
529 $action = $context->getRequest()->getVal( 'action', 'view' );
531 $e instanceof DBConnectionError
&&
532 $context->hasTitle() &&
533 $context->getTitle()->canExist() &&
534 in_array( $action, [ 'view', 'history' ], true ) &&
535 HTMLFileCache
::useFileCache( $this->context
, HTMLFileCache
::MODE_OUTAGE
)
537 // Try to use any (even stale) file during outages...
538 $cache = new HTMLFileCache( $context->getTitle(), 'view' );
539 if ( $cache->isCached() ) {
540 $cache->loadFromFileCache( $context, HTMLFileCache
::MODE_OUTAGE
);
541 print MWExceptionRenderer
::getHTML( $e );
547 MWExceptionHandler
::handleException( $e );
550 $this->doPostOutputShutdown( 'normal' );
553 private function setDBProfilingAgent() {
554 $services = MediaWikiServices
::getInstance();
555 // Add a comment for easy SHOW PROCESSLIST interpretation
556 $name = $this->context
->getUser()->getName();
557 $services->getDBLoadBalancerFactory()->setAgentName(
558 mb_strlen( $name ) > 15 ?
mb_substr( $name, 0, 15 ) . '...' : $name
563 * @see MediaWiki::preOutputCommit()
564 * @param callable $postCommitWork [default: null]
567 public function doPreOutputCommit( callable
$postCommitWork = null ) {
568 self
::preOutputCommit( $this->context
, $postCommitWork );
572 * This function commits all DB changes as needed before
573 * the user can receive a response (in case commit fails)
575 * @param IContextSource $context
576 * @param callable $postCommitWork [default: null]
579 public static function preOutputCommit(
580 IContextSource
$context, callable
$postCommitWork = null
582 // Either all DBs should commit or none
583 ignore_user_abort( true );
585 $config = $context->getConfig();
586 $request = $context->getRequest();
587 $output = $context->getOutput();
588 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
590 // Commit all changes
591 $lbFactory->commitMasterChanges(
593 // Abort if any transaction was too big
594 [ 'maxWriteDuration' => $config->get( 'MaxUserDBWriteDuration' ) ]
596 wfDebug( __METHOD__
. ': primary transaction round committed' );
598 // Run updates that need to block the user or affect output (this is the last chance)
599 DeferredUpdates
::doUpdates( 'enqueue', DeferredUpdates
::PRESEND
);
600 wfDebug( __METHOD__
. ': pre-send deferred updates completed' );
602 // Decide when clients block on ChronologyProtector DB position writes
603 $urlDomainDistance = (
604 $request->wasPosted() &&
605 $output->getRedirect() &&
606 $lbFactory->hasOrMadeRecentMasterChanges( INF
)
607 ) ? self
::getUrlDomainDistance( $output->getRedirect(), $context ) : false;
609 if ( $urlDomainDistance === 'local' ||
$urlDomainDistance === 'remote' ) {
610 // OutputPage::output() will be fast; $postCommitWork will not be useful for
611 // masking the latency of syncing DB positions accross all datacenters synchronously.
612 // Instead, make use of the RTT time of the client follow redirects.
613 $flags = $lbFactory::SHUTDOWN_CHRONPROT_ASYNC
;
614 $cpPosTime = microtime( true );
615 // Client's next request should see 1+ positions with this DBMasterPos::asOf() time
616 if ( $urlDomainDistance === 'local' ) {
617 // Client will stay on this domain, so set an unobtrusive cookie
618 $expires = time() + ChronologyProtector
::POSITION_TTL
;
619 $options = [ 'prefix' => '' ];
620 $request->response()->setCookie( 'cpPosTime', $cpPosTime, $expires, $options );
622 // Cookies may not work across wiki domains, so use a URL parameter
623 $safeUrl = $lbFactory->appendPreShutdownTimeAsQuery(
624 $output->getRedirect(),
627 $output->redirect( $safeUrl );
630 // OutputPage::output() is fairly slow; run it in $postCommitWork to mask
631 // the latency of syncing DB positions accross all datacenters synchronously
632 $flags = $lbFactory::SHUTDOWN_CHRONPROT_SYNC
;
633 if ( $lbFactory->hasOrMadeRecentMasterChanges( INF
) ) {
634 $cpPosTime = microtime( true );
635 // Set a cookie in case the DB position store cannot sync accross datacenters.
636 // This will at least cover the common case of the user staying on the domain.
637 $expires = time() + ChronologyProtector
::POSITION_TTL
;
638 $options = [ 'prefix' => '' ];
639 $request->response()->setCookie( 'cpPosTime', $cpPosTime, $expires, $options );
642 // Record ChronologyProtector positions for DBs affected in this request at this point
643 $lbFactory->shutdown( $flags, $postCommitWork );
644 wfDebug( __METHOD__
. ': LBFactory shutdown completed' );
646 // Set a cookie to tell all CDN edge nodes to "stick" the user to the DC that handles this
647 // POST request (e.g. the "master" data center). Also have the user briefly bypass CDN so
648 // ChronologyProtector works for cacheable URLs.
649 if ( $request->wasPosted() && $lbFactory->hasOrMadeRecentMasterChanges() ) {
650 $expires = time() +
$config->get( 'DataCenterUpdateStickTTL' );
651 $options = [ 'prefix' => '' ];
652 $request->response()->setCookie( 'UseDC', 'master', $expires, $options );
653 $request->response()->setCookie( 'UseCDNCache', 'false', $expires, $options );
656 // Avoid letting a few seconds of replica DB lag cause a month of stale data. This logic is
657 // also intimately related to the value of $wgCdnReboundPurgeDelay.
658 if ( $lbFactory->laggedReplicaUsed() ) {
659 $maxAge = $config->get( 'CdnMaxageLagged' );
660 $output->lowerCdnMaxage( $maxAge );
661 $request->response()->header( "X-Database-Lagged: true" );
662 wfDebugLog( 'replication', "Lagged DB used; CDN cache TTL limited to $maxAge seconds" );
665 // Avoid long-term cache pollution due to message cache rebuild timeouts (T133069)
666 if ( MessageCache
::singleton()->isDisabled() ) {
667 $maxAge = $config->get( 'CdnMaxageSubstitute' );
668 $output->lowerCdnMaxage( $maxAge );
669 $request->response()->header( "X-Response-Substitute: true" );
675 * @param IContextSource $context
676 * @return string Either "local", "remote" if in the farm, "external" otherwise
678 private static function getUrlDomainDistance( $url, IContextSource
$context ) {
679 static $relevantKeys = [ 'host' => true, 'port' => true ];
681 $infoCandidate = wfParseUrl( $url );
682 if ( $infoCandidate === false ) {
686 $infoCandidate = array_intersect_key( $infoCandidate, $relevantKeys );
687 $clusterHosts = array_merge(
688 // Local wiki host (the most common case)
689 [ $context->getConfig()->get( 'CanonicalServer' ) ],
690 // Any local/remote wiki virtual hosts for this wiki farm
691 $context->getConfig()->get( 'LocalVirtualHosts' )
694 foreach ( $clusterHosts as $i => $clusterHost ) {
695 $parseUrl = wfParseUrl( $clusterHost );
699 $infoHost = array_intersect_key( $parseUrl, $relevantKeys );
700 if ( $infoCandidate === $infoHost ) {
701 return ( $i === 0 ) ?
'local' : 'remote';
709 * This function does work that can be done *after* the
710 * user gets the HTTP response so they don't block on it
712 * This manages deferred updates, job insertion,
713 * final commit, and the logging of profiling data
715 * @param string $mode Use 'fast' to always skip job running
718 public function doPostOutputShutdown( $mode = 'normal' ) {
719 $timing = $this->context
->getTiming();
720 $timing->mark( 'requestShutdown' );
722 // Show visible profiling data if enabled (which cannot be post-send)
723 Profiler
::instance()->logDataPageOutputOnly();
725 $callback = function () use ( $mode ) {
727 $this->restInPeace( $mode );
728 } catch ( Exception
$e ) {
729 MWExceptionHandler
::handleException( $e );
733 // Defer everything else...
734 if ( function_exists( 'register_postsend_function' ) ) {
735 // https://github.com/facebook/hhvm/issues/1230
736 register_postsend_function( $callback );
738 if ( function_exists( 'fastcgi_finish_request' ) ) {
739 fastcgi_finish_request();
741 // Either all DB and deferred updates should happen or none.
742 // The latter should not be cancelled due to client disconnect.
743 ignore_user_abort( true );
750 private function main() {
753 $output = $this->context
->getOutput();
754 $request = $this->context
->getRequest();
756 // Send Ajax requests to the Ajax dispatcher.
757 if ( $this->config
->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
758 // Set a dummy title, because $wgTitle == null might break things
759 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/performing an AJAX call in '
762 $this->context
->setTitle( $title );
765 $dispatcher = new AjaxDispatcher( $this->config
);
766 $dispatcher->performAction( $this->context
->getUser() );
771 // Get title from request parameters,
772 // is set on the fly by parseTitle the first time.
773 $title = $this->getTitle();
774 $action = $this->getAction();
777 // Set DB query expectations for this HTTP request
778 $trxLimits = $this->config
->get( 'TrxProfilerLimits' );
779 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
780 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
781 if ( $request->hasSafeMethod() ) {
782 $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__
);
784 $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__
);
787 // If the user has forceHTTPS set to true, or if the user
788 // is in a group requiring HTTPS, or if they have the HTTPS
789 // preference set, redirect them to HTTPS.
790 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
791 // isLoggedIn() will do all sorts of weird stuff.
793 $request->getProtocol() == 'http' &&
794 // switch to HTTPS only when supported by the server
795 preg_match( '#^https://#', wfExpandUrl( $request->getRequestURL(), PROTO_HTTPS
) ) &&
797 $request->getSession()->shouldForceHTTPS() ||
798 // Check the cookie manually, for paranoia
799 $request->getCookie( 'forceHTTPS', '' ) ||
800 // check for prefixed version that was used for a time in older MW versions
801 $request->getCookie( 'forceHTTPS' ) ||
802 // Avoid checking the user and groups unless it's enabled.
804 $this->context
->getUser()->isLoggedIn()
805 && $this->context
->getUser()->requiresHTTPS()
809 $oldUrl = $request->getFullRequestURL();
810 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
812 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
813 if ( Hooks
::run( 'BeforeHttpsRedirect', [ $this->context
, &$redirUrl ] ) ) {
815 if ( $request->wasPosted() ) {
816 // This is weird and we'd hope it almost never happens. This
817 // means that a POST came in via HTTP and policy requires us
818 // redirecting to HTTPS. It's likely such a request is going
819 // to fail due to post data being lost, but let's try anyway
820 // and just log the instance.
822 // @todo FIXME: See if we could issue a 307 or 308 here, need
823 // to see how clients (automated & browser) behave when we do
824 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
826 // Setup dummy Title, otherwise OutputPage::redirect will fail
827 $title = Title
::newFromText( 'REDIR', NS_MAIN
);
828 $this->context
->setTitle( $title );
829 // Since we only do this redir to change proto, always send a vary header
830 $output->addVaryHeader( 'X-Forwarded-Proto' );
831 $output->redirect( $redirUrl );
838 if ( $title->canExist() && HTMLFileCache
::useFileCache( $this->context
) ) {
839 // Try low-level file cache hit
840 $cache = new HTMLFileCache( $title, $action );
841 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
842 // Check incoming headers to see if client has this cached
843 $timestamp = $cache->cacheTimestamp();
844 if ( !$output->checkLastModified( $timestamp ) ) {
845 $cache->loadFromFileCache( $this->context
);
847 // Do any stats increment/watchlist stuff, assuming user is viewing the
848 // latest revision (which should always be the case for file cache)
849 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
850 // Tell OutputPage that output is taken care of
857 // Actually do the work of the request and build up any output
858 $this->performRequest();
860 // GUI-ify and stash the page output in MediaWiki::doPreOutputCommit() while
861 // ChronologyProtector synchronizes DB positions or slaves accross all datacenters.
863 $outputWork = function () use ( $output, &$buffer ) {
864 if ( $buffer === null ) {
865 $buffer = $output->output( true );
871 // Now commit any transactions, so that unreported errors after
872 // output() don't roll back the whole DB transaction and so that
873 // we avoid having both success and error text in the response
874 $this->doPreOutputCommit( $outputWork );
876 // Now send the actual output
881 * Ends this task peacefully
882 * @param string $mode Use 'fast' to always skip job running
884 public function restInPeace( $mode = 'fast' ) {
885 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
886 // Assure deferred updates are not in the main transaction
887 $lbFactory->commitMasterChanges( __METHOD__
);
889 // Loosen DB query expectations since the HTTP client is unblocked
890 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
891 $trxProfiler->resetExpectations();
892 $trxProfiler->setExpectations(
893 $this->config
->get( 'TrxProfilerLimits' )['PostSend'],
897 // Do any deferred jobs
898 DeferredUpdates
::doUpdates( 'enqueue' );
899 DeferredUpdates
::setImmediateMode( true );
901 // Make sure any lazy jobs are pushed
902 JobQueueGroup
::pushLazyJobs();
904 // Now that everything specific to this request is done,
905 // try to occasionally run jobs (if enabled) from the queues
906 if ( $mode === 'normal' ) {
907 $this->triggerJobs();
910 // Log profiling data, e.g. in the database or UDP
911 wfLogProfilingData();
913 // Commit and close up!
914 $lbFactory->commitMasterChanges( __METHOD__
);
915 $lbFactory->shutdown( LBFactory
::SHUTDOWN_NO_CHRONPROT
);
917 wfDebug( "Request ended normally\n" );
921 * Potentially open a socket and sent an HTTP request back to the server
922 * to run a specified number of jobs. This registers a callback to cleanup
923 * the socket once it's done.
925 public function triggerJobs() {
926 $jobRunRate = $this->config
->get( 'JobRunRate' );
927 if ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
928 return; // recursion guard
929 } elseif ( $jobRunRate <= 0 ||
wfReadOnly() ) {
933 if ( $jobRunRate < 1 ) {
934 $max = mt_getrandmax();
935 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
936 return; // the higher the job run rate, the less likely we return here
940 $n = intval( $jobRunRate );
943 $runJobsLogger = LoggerFactory
::getInstance( 'runJobs' );
945 // Fall back to running the job(s) while the user waits if needed
946 if ( !$this->config
->get( 'RunJobsAsync' ) ) {
947 $runner = new JobRunner( $runJobsLogger );
948 $runner->run( [ 'maxJobs' => $n ] );
952 // Do not send request if there are probably no jobs
954 $group = JobQueueGroup
::singleton();
955 if ( !$group->queuesHaveJobs( JobQueueGroup
::TYPE_DEFAULT
) ) {
958 } catch ( JobQueueError
$e ) {
959 MWExceptionHandler
::logException( $e );
960 return; // do not make the site unavailable
963 $query = [ 'title' => 'Special:RunJobs',
964 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() +
5 ];
965 $query['signature'] = SpecialRunJobs
::getQuerySignature(
966 $query, $this->config
->get( 'SecretKey' ) );
968 $errno = $errstr = null;
969 $info = wfParseUrl( $this->config
->get( 'CanonicalServer' ) );
970 $host = $info ?
$info['host'] : null;
972 if ( isset( $info['scheme'] ) && $info['scheme'] == 'https' ) {
973 $host = "tls://" . $host;
976 if ( isset( $info['port'] ) ) {
977 $port = $info['port'];
980 MediaWiki\
suppressWarnings();
981 $sock = $host ?
fsockopen(
986 // If it takes more than 100ms to connect to ourselves there is a problem...
989 MediaWiki\restoreWarnings
();
991 $invokedWithSuccess = true;
993 $special = SpecialPageFactory
::getPage( 'RunJobs' );
994 $url = $special->getPageTitle()->getCanonicalURL( $query );
996 "POST $url HTTP/1.1\r\n" .
997 "Host: {$info['host']}\r\n" .
998 "Connection: Close\r\n" .
999 "Content-Length: 0\r\n\r\n"
1002 $runJobsLogger->info( "Running $n job(s) via '$url'" );
1003 // Send a cron API request to be performed in the background.
1004 // Give up if this takes too long to send (which should be rare).
1005 stream_set_timeout( $sock, 2 );
1006 $bytes = fwrite( $sock, $req );
1007 if ( $bytes !== strlen( $req ) ) {
1008 $invokedWithSuccess = false;
1009 $runJobsLogger->error( "Failed to start cron API (socket write error)" );
1011 // Do not wait for the response (the script should handle client aborts).
1012 // Make sure that we don't close before that script reaches ignore_user_abort().
1013 $start = microtime( true );
1014 $status = fgets( $sock );
1015 $sec = microtime( true ) - $start;
1016 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
1017 $invokedWithSuccess = false;
1018 $runJobsLogger->error( "Failed to start cron API: received '$status' ($sec)" );
1023 $invokedWithSuccess = false;
1024 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
1027 // Fall back to running the job(s) while the user waits if needed
1028 if ( !$invokedWithSuccess ) {
1029 $runJobsLogger->warning( "Jobs switched to blocking; Special:RunJobs disabled" );
1031 $runner = new JobRunner( $runJobsLogger );
1032 $runner->run( [ 'maxJobs' => $n ] );