Improve ApiLogin test coverage
[lhc/web/wiklou.git] / includes / MediaWiki.php
1 <?php
2 /**
3 * Helper class for the index.php entry point.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 use MediaWiki\Logger\LoggerFactory;
24 use Psr\Log\LoggerInterface;
25 use MediaWiki\MediaWikiServices;
26 use Wikimedia\Rdbms\ChronologyProtector;
27 use Wikimedia\Rdbms\LBFactory;
28 use Wikimedia\Rdbms\DBConnectionError;
29 use Liuggio\StatsdClient\Sender\SocketSender;
30
31 /**
32 * The MediaWiki class is the helper class for the index.php entry point.
33 */
34 class MediaWiki {
35 /**
36 * @var IContextSource
37 */
38 private $context;
39
40 /**
41 * @var Config
42 */
43 private $config;
44
45 /**
46 * @var String Cache what action this request is
47 */
48 private $action;
49
50 /**
51 * @param IContextSource|null $context
52 */
53 public function __construct( IContextSource $context = null ) {
54 if ( !$context ) {
55 $context = RequestContext::getMain();
56 }
57
58 $this->context = $context;
59 $this->config = $context->getConfig();
60 }
61
62 /**
63 * Parse the request to get the Title object
64 *
65 * @throws MalformedTitleException If a title has been provided by the user, but is invalid.
66 * @return Title Title object to be $wgTitle
67 */
68 private function parseTitle() {
69 $request = $this->context->getRequest();
70 $curid = $request->getInt( 'curid' );
71 $title = $request->getVal( 'title' );
72 $action = $request->getVal( 'action' );
73
74 if ( $request->getCheck( 'search' ) ) {
75 // Compatibility with old search URLs which didn't use Special:Search
76 // Just check for presence here, so blank requests still
77 // show the search page when using ugly URLs (T10054).
78 $ret = SpecialPage::getTitleFor( 'Search' );
79 } elseif ( $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 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
85 // in wikitext links to tell Parser to make a direct file link
86 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) {
87 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
88 }
89 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
90 // Check variant links so that interwiki links don't have to worry
91 // about the possible different language variants
92 if (
93 $contLang->hasVariants() && !is_null( $ret ) && $ret->getArticleID() == 0
94 ) {
95 $contLang->findVariantLink( $title, $ret );
96 }
97 }
98
99 // If title is not provided, always allow oldid and diff to set the title.
100 // If title is provided, allow oldid and diff to override the title, unless
101 // we are talking about a special page which might use these parameters for
102 // other purposes.
103 if ( $ret === null || !$ret->isSpecialPage() ) {
104 // We can have urls with just ?diff=,?oldid= or even just ?diff=
105 $oldid = $request->getInt( 'oldid' );
106 $oldid = $oldid ?: $request->getInt( 'diff' );
107 // Allow oldid to override a changed or missing title
108 if ( $oldid ) {
109 $rev = Revision::newFromId( $oldid );
110 $ret = $rev ? $rev->getTitle() : $ret;
111 }
112 }
113
114 // Use the main page as default title if nothing else has been provided
115 if ( $ret === null
116 && strval( $title ) === ''
117 && !$request->getCheck( 'curid' )
118 && $action !== 'delete'
119 ) {
120 $ret = Title::newMainPage();
121 }
122
123 if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
124 // If we get here, we definitely don't have a valid title; throw an exception.
125 // Try to get detailed invalid title exception first, fall back to MalformedTitleException.
126 Title::newFromTextThrow( $title );
127 throw new MalformedTitleException( 'badtitletext', $title );
128 }
129
130 return $ret;
131 }
132
133 /**
134 * Get the Title object that we'll be acting on, as specified in the WebRequest
135 * @return Title
136 */
137 public function getTitle() {
138 if ( !$this->context->hasTitle() ) {
139 try {
140 $this->context->setTitle( $this->parseTitle() );
141 } catch ( MalformedTitleException $ex ) {
142 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
143 }
144 }
145 return $this->context->getTitle();
146 }
147
148 /**
149 * Returns the name of the action that will be executed.
150 *
151 * @return string Action
152 */
153 public function getAction() {
154 if ( $this->action === null ) {
155 $this->action = Action::getActionName( $this->context );
156 }
157
158 return $this->action;
159 }
160
161 /**
162 * Performs the request.
163 * - bad titles
164 * - read restriction
165 * - local interwiki redirects
166 * - redirect loop
167 * - special pages
168 * - normal pages
169 *
170 * @throws MWException|PermissionsError|BadTitleError|HttpError
171 * @return void
172 */
173 private function performRequest() {
174 global $wgTitle;
175
176 $request = $this->context->getRequest();
177 $requestTitle = $title = $this->context->getTitle();
178 $output = $this->context->getOutput();
179 $user = $this->context->getUser();
180
181 if ( $request->getVal( 'printable' ) === 'yes' ) {
182 $output->setPrintable();
183 }
184
185 $unused = null; // To pass it by reference
186 Hooks::run( 'BeforeInitialize', [ &$title, &$unused, &$output, &$user, $request, $this ] );
187
188 // Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
189 if ( is_null( $title ) || ( $title->getDBkey() == '' && !$title->isExternal() )
190 || $title->isSpecial( 'Badtitle' )
191 ) {
192 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
193 try {
194 $this->parseTitle();
195 } catch ( MalformedTitleException $ex ) {
196 throw new BadTitleError( $ex );
197 }
198 throw new BadTitleError();
199 }
200
201 // Check user's permissions to read this page.
202 // We have to check here to catch special pages etc.
203 // We will check again in Article::view().
204 $permErrors = $title->isSpecial( 'RunJobs' )
205 ? [] // relies on HMAC key signature alone
206 : $title->getUserPermissionsErrors( 'read', $user );
207 if ( count( $permErrors ) ) {
208 // T34276: allowing the skin to generate output with $wgTitle or
209 // $this->context->title set to the input title would allow anonymous users to
210 // determine whether a page exists, potentially leaking private data. In fact, the
211 // curid and oldid request parameters would allow page titles to be enumerated even
212 // when they are not guessable. So we reset the title to Special:Badtitle before the
213 // permissions error is displayed.
214
215 // The skin mostly uses $this->context->getTitle() these days, but some extensions
216 // still use $wgTitle.
217 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
218 $this->context->setTitle( $badTitle );
219 $wgTitle = $badTitle;
220
221 throw new PermissionsError( 'read', $permErrors );
222 }
223
224 // Interwiki redirects
225 if ( $title->isExternal() ) {
226 $rdfrom = $request->getVal( 'rdfrom' );
227 if ( $rdfrom ) {
228 $url = $title->getFullURL( [ 'rdfrom' => $rdfrom ] );
229 } else {
230 $query = $request->getValues();
231 unset( $query['title'] );
232 $url = $title->getFullURL( $query );
233 }
234 // Check for a redirect loop
235 if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
236 && $title->isLocal()
237 ) {
238 // 301 so google et al report the target as the actual url.
239 $output->redirect( $url, 301 );
240 } else {
241 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
242 try {
243 $this->parseTitle();
244 } catch ( MalformedTitleException $ex ) {
245 throw new BadTitleError( $ex );
246 }
247 throw new BadTitleError();
248 }
249 // Handle any other redirects.
250 // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
251 } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
252 // Prevent information leak via Special:MyPage et al (T109724)
253 $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
254 if ( $title->isSpecialPage() ) {
255 $specialPage = $spFactory->getPage( $title->getDBkey() );
256 if ( $specialPage instanceof RedirectSpecialPage ) {
257 $specialPage->setContext( $this->context );
258 if ( $this->config->get( 'HideIdentifiableRedirects' )
259 && $specialPage->personallyIdentifiableTarget()
260 ) {
261 list( , $subpage ) = $spFactory->resolveAlias( $title->getDBkey() );
262 $target = $specialPage->getRedirect( $subpage );
263 // target can also be true. We let that case fall through to normal processing.
264 if ( $target instanceof Title ) {
265 $query = $specialPage->getRedirectQuery() ?: [];
266 $request = new DerivativeRequest( $this->context->getRequest(), $query );
267 $request->setRequestURL( $this->context->getRequest()->getRequestURL() );
268 $this->context->setRequest( $request );
269 // Do not varnish cache these. May vary even for anons
270 $this->context->getOutput()->lowerCdnMaxage( 0 );
271 $this->context->setTitle( $target );
272 $wgTitle = $target;
273 // Reset action type cache. (Special pages have only view)
274 $this->action = null;
275 $title = $target;
276 $output->addJsConfigVars( [
277 'wgInternalRedirectTargetUrl' => $target->getFullURL( $query ),
278 ] );
279 $output->addModules( 'mediawiki.action.view.redirect' );
280 }
281 }
282 }
283 }
284
285 // Special pages ($title may have changed since if statement above)
286 if ( $title->isSpecialPage() ) {
287 // Actions that need to be made when we have a special pages
288 $spFactory->executePath( $title, $this->context );
289 } else {
290 // ...otherwise treat it as an article view. The article
291 // may still be a wikipage redirect to another article or URL.
292 $article = $this->initializeArticle();
293 if ( is_object( $article ) ) {
294 $this->performAction( $article, $requestTitle );
295 } elseif ( is_string( $article ) ) {
296 $output->redirect( $article );
297 } else {
298 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
299 . " returned neither an object nor a URL" );
300 }
301 }
302 }
303 }
304
305 /**
306 * Handle redirects for uncanonical title requests.
307 *
308 * Handles:
309 * - Redirect loops.
310 * - No title in URL.
311 * - $wgUsePathInfo URLs.
312 * - URLs with a variant.
313 * - Other non-standard URLs (as long as they have no extra query parameters).
314 *
315 * Behaviour:
316 * - Normalise title values:
317 * /wiki/Foo%20Bar -> /wiki/Foo_Bar
318 * - Normalise empty title:
319 * /wiki/ -> /wiki/Main
320 * /w/index.php?title= -> /wiki/Main
321 * - Don't redirect anything with query parameters other than 'title' or 'action=view'.
322 *
323 * @param Title $title
324 * @return bool True if a redirect was set.
325 * @throws HttpError
326 */
327 private function tryNormaliseRedirect( Title $title ) {
328 $request = $this->context->getRequest();
329 $output = $this->context->getOutput();
330
331 if ( $request->getVal( 'action', 'view' ) != 'view'
332 || $request->wasPosted()
333 || ( $request->getVal( 'title' ) !== null
334 && $title->getPrefixedDBkey() == $request->getVal( 'title' ) )
335 || count( $request->getValueNames( [ 'action', 'title' ] ) )
336 || !Hooks::run( 'TestCanonicalRedirect', [ $request, $title, $output ] )
337 ) {
338 return false;
339 }
340
341 if ( $title->isSpecialPage() ) {
342 list( $name, $subpage ) = MediaWikiServices::getInstance()->getSpecialPageFactory()->
343 resolveAlias( $title->getDBkey() );
344 if ( $name ) {
345 $title = SpecialPage::getTitleFor( $name, $subpage );
346 }
347 }
348 // Redirect to canonical url, make it a 301 to allow caching
349 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
350 if ( $targetUrl == $request->getFullRequestURL() ) {
351 $message = "Redirect loop detected!\n\n" .
352 "This means the wiki got confused about what page was " .
353 "requested; this sometimes happens when moving a wiki " .
354 "to a new server or changing the server configuration.\n\n";
355
356 if ( $this->config->get( 'UsePathInfo' ) ) {
357 $message .= "The wiki is trying to interpret the page " .
358 "title from the URL path portion (PATH_INFO), which " .
359 "sometimes fails depending on the web server. Try " .
360 "setting \"\$wgUsePathInfo = false;\" in your " .
361 "LocalSettings.php, or check that \$wgArticlePath " .
362 "is correct.";
363 } else {
364 $message .= "Your web server was detected as possibly not " .
365 "supporting URL path components (PATH_INFO) correctly; " .
366 "check your LocalSettings.php for a customized " .
367 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
368 "to true.";
369 }
370 throw new HttpError( 500, $message );
371 }
372 // Protect against redirects to NS_MEDIA namespace
373 // when the user probably wants NS_FILE
374 if ( $title->inNamespace( NS_MEDIA ) ) {
375 $title->mNamespace = NS_FILE;
376 }
377 $output->setCdnMaxage( 1200 );
378 $output->redirect( $targetUrl, '301' );
379 return true;
380 }
381
382 /**
383 * Initialize the main Article object for "standard" actions (view, etc)
384 * Create an Article object for the page, following redirects if needed.
385 *
386 * @return Article|string An Article, or a string to redirect to another URL
387 */
388 private function initializeArticle() {
389 $title = $this->context->getTitle();
390 if ( $this->context->canUseWikiPage() ) {
391 // Try to use request context wiki page, as there
392 // is already data from db saved in per process
393 // cache there from this->getAction() call.
394 $page = $this->context->getWikiPage();
395 } else {
396 // This case should not happen, but just in case.
397 // @TODO: remove this or use an exception
398 $page = WikiPage::factory( $title );
399 $this->context->setWikiPage( $page );
400 wfWarn( "RequestContext::canUseWikiPage() returned false" );
401 }
402
403 // Make GUI wrapper for the WikiPage
404 $article = Article::newFromWikiPage( $page, $this->context );
405
406 // Skip some unnecessary code if the content model doesn't support redirects
407 if ( !ContentHandler::getForTitle( $title )->supportsRedirects() ) {
408 return $article;
409 }
410
411 $request = $this->context->getRequest();
412
413 // Namespace might change when using redirects
414 // Check for redirects ...
415 $action = $request->getVal( 'action', 'view' );
416 $file = ( $page instanceof WikiFilePage ) ? $page->getFile() : null;
417 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
418 && !$request->getVal( 'oldid' ) // ... and are not old revisions
419 && !$request->getVal( 'diff' ) // ... and not when showing diff
420 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
421 // ... and the article is not a non-redirect image page with associated file
422 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
423 ) {
424 // Give extensions a change to ignore/handle redirects as needed
425 $ignoreRedirect = $target = false;
426
427 Hooks::run( 'InitializeArticleMaybeRedirect',
428 [ &$title, &$request, &$ignoreRedirect, &$target, &$article ] );
429 $page = $article->getPage(); // reflect any hook changes
430
431 // Follow redirects only for... redirects.
432 // If $target is set, then a hook wanted to redirect.
433 if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) {
434 // Is the target already set by an extension?
435 $target = $target ?: $page->followRedirect();
436 if ( is_string( $target ) ) {
437 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
438 // we'll need to redirect
439 return $target;
440 }
441 }
442 if ( is_object( $target ) ) {
443 // Rewrite environment to redirected article
444 $rpage = WikiPage::factory( $target );
445 $rpage->loadPageData();
446 if ( $rpage->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
447 $rarticle = Article::newFromWikiPage( $rpage, $this->context );
448 $rarticle->setRedirectedFrom( $title );
449
450 $article = $rarticle;
451 $this->context->setTitle( $target );
452 $this->context->setWikiPage( $article->getPage() );
453 }
454 }
455 } else {
456 // Article may have been changed by hook
457 $this->context->setTitle( $article->getTitle() );
458 $this->context->setWikiPage( $article->getPage() );
459 }
460 }
461
462 return $article;
463 }
464
465 /**
466 * Perform one of the "standard" actions
467 *
468 * @param Page $page
469 * @param Title $requestTitle The original title, before any redirects were applied
470 */
471 private function performAction( Page $page, Title $requestTitle ) {
472 $request = $this->context->getRequest();
473 $output = $this->context->getOutput();
474 $title = $this->context->getTitle();
475 $user = $this->context->getUser();
476
477 if ( !Hooks::run( 'MediaWikiPerformAction',
478 [ $output, $page, $title, $user, $request, $this ] )
479 ) {
480 return;
481 }
482
483 $act = $this->getAction();
484 $action = Action::factory( $act, $page, $this->context );
485
486 if ( $action instanceof Action ) {
487 // Narrow DB query expectations for this HTTP request
488 $trxLimits = $this->config->get( 'TrxProfilerLimits' );
489 $trxProfiler = Profiler::instance()->getTransactionProfiler();
490 if ( $request->wasPosted() && !$action->doesWrites() ) {
491 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
492 $request->markAsSafeRequest();
493 }
494
495 # Let CDN cache things if we can purge them.
496 if ( $this->config->get( 'UseSquid' ) &&
497 in_array(
498 // Use PROTO_INTERNAL because that's what getCdnUrls() uses
499 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
500 $requestTitle->getCdnUrls()
501 )
502 ) {
503 $output->setCdnMaxage( $this->config->get( 'SquidMaxage' ) );
504 }
505
506 $action->show();
507 return;
508 }
509 // NOTE: deprecated hook. Add to $wgActions instead
510 if ( Hooks::run(
511 'UnknownAction',
512 [
513 $request->getVal( 'action', 'view' ),
514 $page
515 ],
516 '1.19'
517 ) ) {
518 $output->setStatusCode( 404 );
519 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
520 }
521 }
522
523 /**
524 * Run the current MediaWiki instance; index.php just calls this
525 */
526 public function run() {
527 try {
528 $this->setDBProfilingAgent();
529 try {
530 $this->main();
531 } catch ( ErrorPageError $e ) {
532 // T64091: while exceptions are convenient to bubble up GUI errors,
533 // they are not internal application faults. As with normal requests, this
534 // should commit, print the output, do deferred updates, jobs, and profiling.
535 $this->doPreOutputCommit();
536 $e->report(); // display the GUI error
537 }
538 } catch ( Exception $e ) {
539 $context = $this->context;
540 $action = $context->getRequest()->getVal( 'action', 'view' );
541 if (
542 $e instanceof DBConnectionError &&
543 $context->hasTitle() &&
544 $context->getTitle()->canExist() &&
545 in_array( $action, [ 'view', 'history' ], true ) &&
546 HTMLFileCache::useFileCache( $this->context, HTMLFileCache::MODE_OUTAGE )
547 ) {
548 // Try to use any (even stale) file during outages...
549 $cache = new HTMLFileCache( $context->getTitle(), $action );
550 if ( $cache->isCached() ) {
551 $cache->loadFromFileCache( $context, HTMLFileCache::MODE_OUTAGE );
552 print MWExceptionRenderer::getHTML( $e );
553 exit;
554 }
555 }
556
557 MWExceptionHandler::handleException( $e );
558 } catch ( Error $e ) {
559 // Type errors and such: at least handle it now and clean up the LBFactory state
560 MWExceptionHandler::handleException( $e );
561 }
562
563 $this->doPostOutputShutdown( 'normal' );
564 }
565
566 private function setDBProfilingAgent() {
567 $services = MediaWikiServices::getInstance();
568 // Add a comment for easy SHOW PROCESSLIST interpretation
569 $name = $this->context->getUser()->getName();
570 $services->getDBLoadBalancerFactory()->setAgentName(
571 mb_strlen( $name ) > 15 ? mb_substr( $name, 0, 15 ) . '...' : $name
572 );
573 }
574
575 /**
576 * @see MediaWiki::preOutputCommit()
577 * @param callable|null $postCommitWork [default: null]
578 * @since 1.26
579 */
580 public function doPreOutputCommit( callable $postCommitWork = null ) {
581 self::preOutputCommit( $this->context, $postCommitWork );
582 }
583
584 /**
585 * This function commits all DB changes as needed before
586 * the user can receive a response (in case commit fails)
587 *
588 * @param IContextSource $context
589 * @param callable|null $postCommitWork [default: null]
590 * @since 1.27
591 */
592 public static function preOutputCommit(
593 IContextSource $context, callable $postCommitWork = null
594 ) {
595 // Either all DBs should commit or none
596 ignore_user_abort( true );
597
598 $config = $context->getConfig();
599 $request = $context->getRequest();
600 $output = $context->getOutput();
601 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
602
603 // Commit all changes
604 $lbFactory->commitMasterChanges(
605 __METHOD__,
606 // Abort if any transaction was too big
607 [ 'maxWriteDuration' => $config->get( 'MaxUserDBWriteDuration' ) ]
608 );
609 wfDebug( __METHOD__ . ': primary transaction round committed' );
610
611 // Run updates that need to block the user or affect output (this is the last chance)
612 DeferredUpdates::doUpdates( 'enqueue', DeferredUpdates::PRESEND );
613 wfDebug( __METHOD__ . ': pre-send deferred updates completed' );
614
615 // Should the client return, their request should observe the new ChronologyProtector
616 // DB positions. This request might be on a foreign wiki domain, so synchronously update
617 // the DB positions in all datacenters to be safe. If this output is not a redirect,
618 // then OutputPage::output() will be relatively slow, meaning that running it in
619 // $postCommitWork should help mask the latency of those updates.
620 $flags = $lbFactory::SHUTDOWN_CHRONPROT_SYNC;
621 $strategy = 'cookie+sync';
622
623 $allowHeaders = !( $output->isDisabled() || headers_sent() );
624 if ( $output->getRedirect() && $lbFactory->hasOrMadeRecentMasterChanges( INF ) ) {
625 // OutputPage::output() will be fast, so $postCommitWork is useless for masking
626 // the latency of synchronously updating the DB positions in all datacenters.
627 // Try to make use of the time the client spends following redirects instead.
628 $domainDistance = self::getUrlDomainDistance( $output->getRedirect() );
629 if ( $domainDistance === 'local' && $allowHeaders ) {
630 $flags = $lbFactory::SHUTDOWN_CHRONPROT_ASYNC;
631 $strategy = 'cookie'; // use same-domain cookie and keep the URL uncluttered
632 } elseif ( $domainDistance === 'remote' ) {
633 $flags = $lbFactory::SHUTDOWN_CHRONPROT_ASYNC;
634 $strategy = 'cookie+url'; // cross-domain cookie might not work
635 }
636 }
637
638 // Record ChronologyProtector positions for DBs affected in this request at this point
639 $cpIndex = null;
640 $cpClientId = null;
641 $lbFactory->shutdown( $flags, $postCommitWork, $cpIndex, $cpClientId );
642 wfDebug( __METHOD__ . ': LBFactory shutdown completed' );
643
644 if ( $cpIndex > 0 ) {
645 if ( $allowHeaders ) {
646 $now = time();
647 $expires = $now + ChronologyProtector::POSITION_COOKIE_TTL;
648 $options = [ 'prefix' => '' ];
649 $value = LBFactory::makeCookieValueFromCPIndex( $cpIndex, $now, $cpClientId );
650 $request->response()->setCookie( 'cpPosIndex', $value, $expires, $options );
651 }
652
653 if ( $strategy === 'cookie+url' ) {
654 if ( $output->getRedirect() ) { // sanity
655 $safeUrl = $lbFactory->appendShutdownCPIndexAsQuery(
656 $output->getRedirect(),
657 $cpIndex
658 );
659 $output->redirect( $safeUrl );
660 } else {
661 $e = new LogicException( "No redirect; cannot append cpPosIndex parameter." );
662 MWExceptionHandler::logException( $e );
663 }
664 }
665 }
666
667 // Set a cookie to tell all CDN edge nodes to "stick" the user to the DC that handles this
668 // POST request (e.g. the "master" data center). Also have the user briefly bypass CDN so
669 // ChronologyProtector works for cacheable URLs.
670 if ( $request->wasPosted() && $lbFactory->hasOrMadeRecentMasterChanges() ) {
671 $expires = time() + $config->get( 'DataCenterUpdateStickTTL' );
672 $options = [ 'prefix' => '' ];
673 $request->response()->setCookie( 'UseDC', 'master', $expires, $options );
674 $request->response()->setCookie( 'UseCDNCache', 'false', $expires, $options );
675 }
676
677 // Avoid letting a few seconds of replica DB lag cause a month of stale data. This logic is
678 // also intimately related to the value of $wgCdnReboundPurgeDelay.
679 if ( $lbFactory->laggedReplicaUsed() ) {
680 $maxAge = $config->get( 'CdnMaxageLagged' );
681 $output->lowerCdnMaxage( $maxAge );
682 $request->response()->header( "X-Database-Lagged: true" );
683 wfDebugLog( 'replication', "Lagged DB used; CDN cache TTL limited to $maxAge seconds" );
684 }
685
686 // Avoid long-term cache pollution due to message cache rebuild timeouts (T133069)
687 if ( MessageCache::singleton()->isDisabled() ) {
688 $maxAge = $config->get( 'CdnMaxageSubstitute' );
689 $output->lowerCdnMaxage( $maxAge );
690 $request->response()->header( "X-Response-Substitute: true" );
691 }
692 }
693
694 /**
695 * @param string $url
696 * @return string Either "local", "remote" if in the farm, "external" otherwise
697 */
698 private static function getUrlDomainDistance( $url ) {
699 $clusterWiki = WikiMap::getWikiFromUrl( $url );
700 if ( $clusterWiki === wfWikiID() ) {
701 return 'local'; // the current wiki
702 } elseif ( $clusterWiki !== false ) {
703 return 'remote'; // another wiki in this cluster/farm
704 }
705
706 return 'external';
707 }
708
709 /**
710 * This function does work that can be done *after* the
711 * user gets the HTTP response so they don't block on it
712 *
713 * This manages deferred updates, job insertion,
714 * final commit, and the logging of profiling data
715 *
716 * @param string $mode Use 'fast' to always skip job running
717 * @since 1.26
718 */
719 public function doPostOutputShutdown( $mode = 'normal' ) {
720 // Perform the last synchronous operations...
721 try {
722 // Record backend request timing
723 $timing = $this->context->getTiming();
724 $timing->mark( 'requestShutdown' );
725 // Show visible profiling data if enabled (which cannot be post-send)
726 Profiler::instance()->logDataPageOutputOnly();
727 } catch ( Exception $e ) {
728 // An error may already have been shown in run(), so just log it to be safe
729 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
730 }
731
732 // Disable WebResponse setters for post-send processing (T191537).
733 WebResponse::disableForPostSend();
734
735 $blocksHttpClient = true;
736 // Defer everything else if possible...
737 $callback = function () use ( $mode, &$blocksHttpClient ) {
738 try {
739 $this->restInPeace( $mode, $blocksHttpClient );
740 } catch ( Exception $e ) {
741 // If this is post-send, then displaying errors can cause broken HTML
742 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
743 }
744 };
745
746 if ( function_exists( 'register_postsend_function' ) ) {
747 // https://github.com/facebook/hhvm/issues/1230
748 register_postsend_function( $callback );
749 /** @noinspection PhpUnusedLocalVariableInspection */
750 $blocksHttpClient = false;
751 } else {
752 if ( function_exists( 'fastcgi_finish_request' ) ) {
753 fastcgi_finish_request();
754 /** @noinspection PhpUnusedLocalVariableInspection */
755 $blocksHttpClient = false;
756 } else {
757 // Either all DB and deferred updates should happen or none.
758 // The latter should not be cancelled due to client disconnect.
759 ignore_user_abort( true );
760 }
761
762 $callback();
763 }
764 }
765
766 private function main() {
767 global $wgTitle;
768
769 $output = $this->context->getOutput();
770 $request = $this->context->getRequest();
771
772 // Send Ajax requests to the Ajax dispatcher.
773 if ( $request->getVal( 'action' ) === 'ajax' ) {
774 // Set a dummy title, because $wgTitle == null might break things
775 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
776 . __METHOD__
777 );
778 $this->context->setTitle( $title );
779 $wgTitle = $title;
780
781 $dispatcher = new AjaxDispatcher( $this->config );
782 $dispatcher->performAction( $this->context->getUser() );
783
784 return;
785 }
786
787 // Get title from request parameters,
788 // is set on the fly by parseTitle the first time.
789 $title = $this->getTitle();
790 $action = $this->getAction();
791 $wgTitle = $title;
792
793 // Set DB query expectations for this HTTP request
794 $trxLimits = $this->config->get( 'TrxProfilerLimits' );
795 $trxProfiler = Profiler::instance()->getTransactionProfiler();
796 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
797 if ( $request->hasSafeMethod() ) {
798 $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__ );
799 } else {
800 $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__ );
801 }
802
803 // If the user has forceHTTPS set to true, or if the user
804 // is in a group requiring HTTPS, or if they have the HTTPS
805 // preference set, redirect them to HTTPS.
806 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
807 // isLoggedIn() will do all sorts of weird stuff.
808 if (
809 $request->getProtocol() == 'http' &&
810 // switch to HTTPS only when supported by the server
811 preg_match( '#^https://#', wfExpandUrl( $request->getRequestURL(), PROTO_HTTPS ) ) &&
812 (
813 $request->getSession()->shouldForceHTTPS() ||
814 // Check the cookie manually, for paranoia
815 $request->getCookie( 'forceHTTPS', '' ) ||
816 // check for prefixed version that was used for a time in older MW versions
817 $request->getCookie( 'forceHTTPS' ) ||
818 // Avoid checking the user and groups unless it's enabled.
819 (
820 $this->context->getUser()->isLoggedIn()
821 && $this->context->getUser()->requiresHTTPS()
822 )
823 )
824 ) {
825 $oldUrl = $request->getFullRequestURL();
826 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
827
828 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
829 if ( Hooks::run( 'BeforeHttpsRedirect', [ $this->context, &$redirUrl ] ) ) {
830 if ( $request->wasPosted() ) {
831 // This is weird and we'd hope it almost never happens. This
832 // means that a POST came in via HTTP and policy requires us
833 // redirecting to HTTPS. It's likely such a request is going
834 // to fail due to post data being lost, but let's try anyway
835 // and just log the instance.
836
837 // @todo FIXME: See if we could issue a 307 or 308 here, need
838 // to see how clients (automated & browser) behave when we do
839 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
840 }
841 // Setup dummy Title, otherwise OutputPage::redirect will fail
842 $title = Title::newFromText( 'REDIR', NS_MAIN );
843 $this->context->setTitle( $title );
844 // Since we only do this redir to change proto, always send a vary header
845 $output->addVaryHeader( 'X-Forwarded-Proto' );
846 $output->redirect( $redirUrl );
847 $output->output();
848
849 return;
850 }
851 }
852
853 if ( $title->canExist() && HTMLFileCache::useFileCache( $this->context ) ) {
854 // Try low-level file cache hit
855 $cache = new HTMLFileCache( $title, $action );
856 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
857 // Check incoming headers to see if client has this cached
858 $timestamp = $cache->cacheTimestamp();
859 if ( !$output->checkLastModified( $timestamp ) ) {
860 $cache->loadFromFileCache( $this->context );
861 }
862 // Do any stats increment/watchlist stuff, assuming user is viewing the
863 // latest revision (which should always be the case for file cache)
864 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
865 // Tell OutputPage that output is taken care of
866 $output->disable();
867
868 return;
869 }
870 }
871
872 // Actually do the work of the request and build up any output
873 $this->performRequest();
874
875 // GUI-ify and stash the page output in MediaWiki::doPreOutputCommit() while
876 // ChronologyProtector synchronizes DB positions or replicas across all datacenters.
877 $buffer = null;
878 $outputWork = function () use ( $output, &$buffer ) {
879 if ( $buffer === null ) {
880 $buffer = $output->output( true );
881 }
882
883 return $buffer;
884 };
885
886 // Now commit any transactions, so that unreported errors after
887 // output() don't roll back the whole DB transaction and so that
888 // we avoid having both success and error text in the response
889 $this->doPreOutputCommit( $outputWork );
890
891 // Now send the actual output
892 print $outputWork();
893 }
894
895 /**
896 * Ends this task peacefully
897 * @param string $mode Use 'fast' to always skip job running
898 * @param bool $blocksHttpClient Whether this blocks an HTTP response to a client
899 */
900 public function restInPeace( $mode = 'fast', $blocksHttpClient = true ) {
901 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
902 // Assure deferred updates are not in the main transaction
903 $lbFactory->commitMasterChanges( __METHOD__ );
904
905 // Loosen DB query expectations since the HTTP client is unblocked
906 $trxProfiler = Profiler::instance()->getTransactionProfiler();
907 $trxProfiler->resetExpectations();
908 $trxProfiler->setExpectations(
909 $this->context->getRequest()->hasSafeMethod()
910 ? $this->config->get( 'TrxProfilerLimits' )['PostSend-GET']
911 : $this->config->get( 'TrxProfilerLimits' )['PostSend-POST'],
912 __METHOD__
913 );
914
915 // Important: this must be the last deferred update added (T100085, T154425)
916 DeferredUpdates::addCallableUpdate( [ JobQueueGroup::class, 'pushLazyJobs' ] );
917
918 // Do any deferred jobs; preferring to run them now if a client will not wait on them
919 DeferredUpdates::doUpdates( $blocksHttpClient ? 'enqueue' : 'run' );
920
921 // Now that everything specific to this request is done,
922 // try to occasionally run jobs (if enabled) from the queues
923 if ( $mode === 'normal' ) {
924 $this->triggerJobs();
925 }
926
927 // Log profiling data, e.g. in the database or UDP
928 wfLogProfilingData();
929
930 // Commit and close up!
931 $lbFactory->commitMasterChanges( __METHOD__ );
932 $lbFactory->shutdown( LBFactory::SHUTDOWN_NO_CHRONPROT );
933
934 wfDebug( "Request ended normally\n" );
935 }
936
937 /**
938 * Send out any buffered statsd data according to sampling rules
939 *
940 * @param IBufferingStatsdDataFactory $stats
941 * @param Config $config
942 * @throws ConfigException
943 * @since 1.31
944 */
945 public static function emitBufferedStatsdData(
946 IBufferingStatsdDataFactory $stats, Config $config
947 ) {
948 if ( $config->get( 'StatsdServer' ) && $stats->hasData() ) {
949 try {
950 $statsdServer = explode( ':', $config->get( 'StatsdServer' ) );
951 $statsdHost = $statsdServer[0];
952 $statsdPort = $statsdServer[1] ?? 8125;
953 $statsdSender = new SocketSender( $statsdHost, $statsdPort );
954 $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
955 $statsdClient->setSamplingRates( $config->get( 'StatsdSamplingRates' ) );
956 $statsdClient->send( $stats->getData() );
957
958 $stats->clearData(); // empty buffer for the next round
959 } catch ( Exception $ex ) {
960 MWExceptionHandler::logException( $ex );
961 }
962 }
963 }
964
965 /**
966 * Potentially open a socket and sent an HTTP request back to the server
967 * to run a specified number of jobs. This registers a callback to cleanup
968 * the socket once it's done.
969 */
970 public function triggerJobs() {
971 $jobRunRate = $this->config->get( 'JobRunRate' );
972 if ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
973 return; // recursion guard
974 } elseif ( $jobRunRate <= 0 || wfReadOnly() ) {
975 return;
976 }
977
978 if ( $jobRunRate < 1 ) {
979 $max = mt_getrandmax();
980 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
981 return; // the higher the job run rate, the less likely we return here
982 }
983 $n = 1;
984 } else {
985 $n = intval( $jobRunRate );
986 }
987
988 $logger = LoggerFactory::getInstance( 'runJobs' );
989
990 try {
991 if ( $this->config->get( 'RunJobsAsync' ) ) {
992 // Send an HTTP request to the job RPC entry point if possible
993 $invokedWithSuccess = $this->triggerAsyncJobs( $n, $logger );
994 if ( !$invokedWithSuccess ) {
995 // Fall back to blocking on running the job(s)
996 $logger->warning( "Jobs switched to blocking; Special:RunJobs disabled" );
997 $this->triggerSyncJobs( $n, $logger );
998 }
999 } else {
1000 $this->triggerSyncJobs( $n, $logger );
1001 }
1002 } catch ( JobQueueError $e ) {
1003 // Do not make the site unavailable (T88312)
1004 MWExceptionHandler::logException( $e );
1005 }
1006 }
1007
1008 /**
1009 * @param int $n Number of jobs to try to run
1010 * @param LoggerInterface $runJobsLogger
1011 */
1012 private function triggerSyncJobs( $n, LoggerInterface $runJobsLogger ) {
1013 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1014 $old = $trxProfiler->setSilenced( true );
1015 try {
1016 $runner = new JobRunner( $runJobsLogger );
1017 $runner->run( [ 'maxJobs' => $n ] );
1018 } finally {
1019 $trxProfiler->setSilenced( $old );
1020 }
1021 }
1022
1023 /**
1024 * @param int $n Number of jobs to try to run
1025 * @param LoggerInterface $runJobsLogger
1026 * @return bool Success
1027 */
1028 private function triggerAsyncJobs( $n, LoggerInterface $runJobsLogger ) {
1029 // Do not send request if there are probably no jobs
1030 $group = JobQueueGroup::singleton();
1031 if ( !$group->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
1032 return true;
1033 }
1034
1035 $query = [ 'title' => 'Special:RunJobs',
1036 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 ];
1037 $query['signature'] = SpecialRunJobs::getQuerySignature(
1038 $query, $this->config->get( 'SecretKey' ) );
1039
1040 $errno = $errstr = null;
1041 $info = wfParseUrl( $this->config->get( 'CanonicalServer' ) );
1042 $host = $info ? $info['host'] : null;
1043 $port = 80;
1044 if ( isset( $info['scheme'] ) && $info['scheme'] == 'https' ) {
1045 $host = "tls://" . $host;
1046 $port = 443;
1047 }
1048 if ( isset( $info['port'] ) ) {
1049 $port = $info['port'];
1050 }
1051
1052 Wikimedia\suppressWarnings();
1053 $sock = $host ? fsockopen(
1054 $host,
1055 $port,
1056 $errno,
1057 $errstr,
1058 // If it takes more than 100ms to connect to ourselves there is a problem...
1059 0.100
1060 ) : false;
1061 Wikimedia\restoreWarnings();
1062
1063 $invokedWithSuccess = true;
1064 if ( $sock ) {
1065 $special = MediaWikiServices::getInstance()->getSpecialPageFactory()->
1066 getPage( 'RunJobs' );
1067 $url = $special->getPageTitle()->getCanonicalURL( $query );
1068 $req = (
1069 "POST $url HTTP/1.1\r\n" .
1070 "Host: {$info['host']}\r\n" .
1071 "Connection: Close\r\n" .
1072 "Content-Length: 0\r\n\r\n"
1073 );
1074
1075 $runJobsLogger->info( "Running $n job(s) via '$url'" );
1076 // Send a cron API request to be performed in the background.
1077 // Give up if this takes too long to send (which should be rare).
1078 stream_set_timeout( $sock, 2 );
1079 $bytes = fwrite( $sock, $req );
1080 if ( $bytes !== strlen( $req ) ) {
1081 $invokedWithSuccess = false;
1082 $runJobsLogger->error( "Failed to start cron API (socket write error)" );
1083 } else {
1084 // Do not wait for the response (the script should handle client aborts).
1085 // Make sure that we don't close before that script reaches ignore_user_abort().
1086 $start = microtime( true );
1087 $status = fgets( $sock );
1088 $sec = microtime( true ) - $start;
1089 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
1090 $invokedWithSuccess = false;
1091 $runJobsLogger->error( "Failed to start cron API: received '$status' ($sec)" );
1092 }
1093 }
1094 fclose( $sock );
1095 } else {
1096 $invokedWithSuccess = false;
1097 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
1098 }
1099
1100 return $invokedWithSuccess;
1101 }
1102 }