2aa4b80c66cd6e97adf22108f97d8e44f53ec3db
[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 MediaWiki\MediaWikiServices;
25
26 /**
27 * The MediaWiki class is the helper class for the index.php entry point.
28 */
29 class MediaWiki {
30 /**
31 * @var IContextSource
32 */
33 private $context;
34
35 /**
36 * @var Config
37 */
38 private $config;
39
40 /**
41 * @var String Cache what action this request is
42 */
43 private $action;
44
45 /**
46 * @param IContextSource|null $context
47 */
48 public function __construct( IContextSource $context = null ) {
49 if ( !$context ) {
50 $context = RequestContext::getMain();
51 }
52
53 $this->context = $context;
54 $this->config = $context->getConfig();
55 }
56
57 /**
58 * Parse the request to get the Title object
59 *
60 * @throws MalformedTitleException If a title has been provided by the user, but is invalid.
61 * @return Title Title object to be $wgTitle
62 */
63 private function parseTitle() {
64 global $wgContLang;
65
66 $request = $this->context->getRequest();
67 $curid = $request->getInt( 'curid' );
68 $title = $request->getVal( 'title' );
69 $action = $request->getVal( 'action' );
70
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' );
76 } elseif ( $curid ) {
77 // URLs like this are generated by RC, because rc_title isn't always accurate
78 $ret = Title::newFromID( $curid );
79 } else {
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() );
85 }
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
90 ) {
91 $wgContLang->findVariantLink( $title, $ret );
92 }
93 }
94
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
98 // other purposes.
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
104 if ( $oldid ) {
105 $rev = Revision::newFromId( $oldid );
106 $ret = $rev ? $rev->getTitle() : $ret;
107 }
108 }
109
110 // Use the main page as default title if nothing else has been provided
111 if ( $ret === null
112 && strval( $title ) === ''
113 && !$request->getCheck( 'curid' )
114 && $action !== 'delete'
115 ) {
116 $ret = Title::newMainPage();
117 }
118
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 );
124 }
125
126 return $ret;
127 }
128
129 /**
130 * Get the Title object that we'll be acting on, as specified in the WebRequest
131 * @return Title
132 */
133 public function getTitle() {
134 if ( !$this->context->hasTitle() ) {
135 try {
136 $this->context->setTitle( $this->parseTitle() );
137 } catch ( MalformedTitleException $ex ) {
138 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
139 }
140 }
141 return $this->context->getTitle();
142 }
143
144 /**
145 * Returns the name of the action that will be executed.
146 *
147 * @return string Action
148 */
149 public function getAction() {
150 if ( $this->action === null ) {
151 $this->action = Action::getActionName( $this->context );
152 }
153
154 return $this->action;
155 }
156
157 /**
158 * Performs the request.
159 * - bad titles
160 * - read restriction
161 * - local interwiki redirects
162 * - redirect loop
163 * - special pages
164 * - normal pages
165 *
166 * @throws MWException|PermissionsError|BadTitleError|HttpError
167 * @return void
168 */
169 private function performRequest() {
170 global $wgTitle;
171
172 $request = $this->context->getRequest();
173 $requestTitle = $title = $this->context->getTitle();
174 $output = $this->context->getOutput();
175 $user = $this->context->getUser();
176
177 if ( $request->getVal( 'printable' ) === 'yes' ) {
178 $output->setPrintable();
179 }
180
181 $unused = null; // To pass it by reference
182 Hooks::run( 'BeforeInitialize', [ &$title, &$unused, &$output, &$user, $request, $this ] );
183
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' )
187 ) {
188 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
189 try {
190 $this->parseTitle();
191 } catch ( MalformedTitleException $ex ) {
192 throw new BadTitleError( $ex );
193 }
194 throw new BadTitleError();
195 }
196
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.
210
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;
216
217 throw new PermissionsError( 'read', $permErrors );
218 }
219
220 // Interwiki redirects
221 if ( $title->isExternal() ) {
222 $rdfrom = $request->getVal( 'rdfrom' );
223 if ( $rdfrom ) {
224 $url = $title->getFullURL( [ 'rdfrom' => $rdfrom ] );
225 } else {
226 $query = $request->getValues();
227 unset( $query['title'] );
228 $url = $title->getFullURL( $query );
229 }
230 // Check for a redirect loop
231 if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
232 && $title->isLocal()
233 ) {
234 // 301 so google et al report the target as the actual url.
235 $output->redirect( $url, 301 );
236 } else {
237 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
238 try {
239 $this->parseTitle();
240 } catch ( MalformedTitleException $ex ) {
241 throw new BadTitleError( $ex );
242 }
243 throw new BadTitleError();
244 }
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()
255 ) {
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 );
267 $wgTitle = $target;
268 // Reset action type cache. (Special pages have only view)
269 $this->action = null;
270 $title = $target;
271 $output->addJsConfigVars( [
272 'wgInternalRedirectTargetUrl' => $target->getFullURL( $query ),
273 ] );
274 $output->addModules( 'mediawiki.action.view.redirect' );
275 }
276 }
277 }
278 }
279
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 );
284 } else {
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 );
292 } else {
293 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
294 . " returned neither an object nor a URL" );
295 }
296 }
297 }
298 }
299
300 /**
301 * Handle redirects for uncanonical title requests.
302 *
303 * Handles:
304 * - Redirect loops.
305 * - No title in URL.
306 * - $wgUsePathInfo URLs.
307 * - URLs with a variant.
308 * - Other non-standard URLs (as long as they have no extra query parameters).
309 *
310 * Behaviour:
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 * - Normalise non-standard title urls:
317 * /w/index.php?title=Foo_Bar -> /wiki/Foo_Bar
318 * - Don't redirect anything with query parameters other than 'title' or 'action=view'.
319 *
320 * @param Title $title
321 * @return bool True if a redirect was set.
322 * @throws HttpError
323 */
324 private function tryNormaliseRedirect( Title $title ) {
325 $request = $this->context->getRequest();
326 $output = $this->context->getOutput();
327
328 if ( $request->getVal( 'action', 'view' ) != 'view'
329 || $request->wasPosted()
330 || count( $request->getValueNames( [ 'action', 'title' ] ) )
331 || !Hooks::run( 'TestCanonicalRedirect', [ $request, $title, $output ] )
332 ) {
333 return false;
334 }
335
336 if ( $title->isSpecialPage() ) {
337 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
338 if ( $name ) {
339 $title = SpecialPage::getTitleFor( $name, $subpage );
340 }
341 }
342 // Redirect to canonical url, make it a 301 to allow caching
343 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
344
345 if ( $targetUrl != $request->getFullRequestURL() ) {
346 $output->setCdnMaxage( 1200 );
347 $output->redirect( $targetUrl, '301' );
348 return true;
349 }
350
351 // If there is no title, or the title is in a non-standard encoding, we demand
352 // a redirect. If cgi somehow changed the 'title' query to be non-standard while
353 // the url is standard, the server is misconfigured.
354 if ( $request->getVal( 'title' ) === null
355 || $title->getPrefixedDBkey() != $request->getVal( 'title' )
356 ) {
357 $message = "Redirect loop detected!\n\n" .
358 "This means the wiki got confused about what page was " .
359 "requested; this sometimes happens when moving a wiki " .
360 "to a new server or changing the server configuration.\n\n";
361
362 if ( $this->config->get( 'UsePathInfo' ) ) {
363 $message .= "The wiki is trying to interpret the page " .
364 "title from the URL path portion (PATH_INFO), which " .
365 "sometimes fails depending on the web server. Try " .
366 "setting \"\$wgUsePathInfo = false;\" in your " .
367 "LocalSettings.php, or check that \$wgArticlePath " .
368 "is correct.";
369 } else {
370 $message .= "Your web server was detected as possibly not " .
371 "supporting URL path components (PATH_INFO) correctly; " .
372 "check your LocalSettings.php for a customized " .
373 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
374 "to true.";
375 }
376 throw new HttpError( 500, $message );
377 }
378 return false;
379 }
380
381 /**
382 * Initialize the main Article object for "standard" actions (view, etc)
383 * Create an Article object for the page, following redirects if needed.
384 *
385 * @return Article|string An Article, or a string to redirect to another URL
386 */
387 private function initializeArticle() {
388 $title = $this->context->getTitle();
389 if ( $this->context->canUseWikiPage() ) {
390 // Try to use request context wiki page, as there
391 // is already data from db saved in per process
392 // cache there from this->getAction() call.
393 $page = $this->context->getWikiPage();
394 } else {
395 // This case should not happen, but just in case.
396 // @TODO: remove this or use an exception
397 $page = WikiPage::factory( $title );
398 $this->context->setWikiPage( $page );
399 wfWarn( "RequestContext::canUseWikiPage() returned false" );
400 }
401
402 // Make GUI wrapper for the WikiPage
403 $article = Article::newFromWikiPage( $page, $this->context );
404
405 // Skip some unnecessary code if the content model doesn't support redirects
406 if ( !ContentHandler::getForTitle( $title )->supportsRedirects() ) {
407 return $article;
408 }
409
410 $request = $this->context->getRequest();
411
412 // Namespace might change when using redirects
413 // Check for redirects ...
414 $action = $request->getVal( 'action', 'view' );
415 $file = ( $page instanceof WikiFilePage ) ? $page->getFile() : null;
416 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
417 && !$request->getVal( 'oldid' ) // ... and are not old revisions
418 && !$request->getVal( 'diff' ) // ... and not when showing diff
419 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
420 // ... and the article is not a non-redirect image page with associated file
421 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
422 ) {
423 // Give extensions a change to ignore/handle redirects as needed
424 $ignoreRedirect = $target = false;
425
426 Hooks::run( 'InitializeArticleMaybeRedirect',
427 [ &$title, &$request, &$ignoreRedirect, &$target, &$article ] );
428 $page = $article->getPage(); // reflect any hook changes
429
430 // Follow redirects only for... redirects.
431 // If $target is set, then a hook wanted to redirect.
432 if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) {
433 // Is the target already set by an extension?
434 $target = $target ? $target : $page->followRedirect();
435 if ( is_string( $target ) ) {
436 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
437 // we'll need to redirect
438 return $target;
439 }
440 }
441 if ( is_object( $target ) ) {
442 // Rewrite environment to redirected article
443 $rpage = WikiPage::factory( $target );
444 $rpage->loadPageData();
445 if ( $rpage->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
446 $rarticle = Article::newFromWikiPage( $rpage, $this->context );
447 $rarticle->setRedirectedFrom( $title );
448
449 $article = $rarticle;
450 $this->context->setTitle( $target );
451 $this->context->setWikiPage( $article->getPage() );
452 }
453 }
454 } else {
455 // Article may have been changed by hook
456 $this->context->setTitle( $article->getTitle() );
457 $this->context->setWikiPage( $article->getPage() );
458 }
459 }
460
461 return $article;
462 }
463
464 /**
465 * Perform one of the "standard" actions
466 *
467 * @param Page $page
468 * @param Title $requestTitle The original title, before any redirects were applied
469 */
470 private function performAction( Page $page, Title $requestTitle ) {
471 $request = $this->context->getRequest();
472 $output = $this->context->getOutput();
473 $title = $this->context->getTitle();
474 $user = $this->context->getUser();
475
476 if ( !Hooks::run( 'MediaWikiPerformAction',
477 [ $output, $page, $title, $user, $request, $this ] )
478 ) {
479 return;
480 }
481
482 $act = $this->getAction();
483 $action = Action::factory( $act, $page, $this->context );
484
485 if ( $action instanceof Action ) {
486 // Narrow DB query expectations for this HTTP request
487 $trxLimits = $this->config->get( 'TrxProfilerLimits' );
488 $trxProfiler = Profiler::instance()->getTransactionProfiler();
489 if ( $request->wasPosted() && !$action->doesWrites() ) {
490 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
491 $request->markAsSafeRequest();
492 }
493
494 # Let CDN cache things if we can purge them.
495 if ( $this->config->get( 'UseSquid' ) &&
496 in_array(
497 // Use PROTO_INTERNAL because that's what getCdnUrls() uses
498 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
499 $requestTitle->getCdnUrls()
500 )
501 ) {
502 $output->setCdnMaxage( $this->config->get( 'SquidMaxage' ) );
503 }
504
505 $action->show();
506 return;
507 }
508
509 if ( Hooks::run( 'UnknownAction', [ $request->getVal( 'action', 'view' ), $page ] ) ) {
510 $output->setStatusCode( 404 );
511 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
512 }
513 }
514
515 /**
516 * Run the current MediaWiki instance; index.php just calls this
517 */
518 public function run() {
519 try {
520 $this->setDBProfilingAgent();
521 try {
522 $this->main();
523 } catch ( ErrorPageError $e ) {
524 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
525 // they are not internal application faults. As with normal requests, this
526 // should commit, print the output, do deferred updates, jobs, and profiling.
527 $this->doPreOutputCommit();
528 $e->report(); // display the GUI error
529 }
530 } catch ( Exception $e ) {
531 MWExceptionHandler::handleException( $e );
532 }
533
534 $this->doPostOutputShutdown( 'normal' );
535 }
536
537 private function setDBProfilingAgent() {
538 $services = MediaWikiServices::getInstance();
539 // Add a comment for easy SHOW PROCESSLIST interpretation
540 $name = $this->context->getUser()->getName();
541 $services->getDBLoadBalancerFactory()->setAgentName(
542 mb_strlen( $name ) > 15 ? mb_substr( $name, 0, 15 ) . '...' : $name
543 );
544 }
545
546 /**
547 * @see MediaWiki::preOutputCommit()
548 * @param callable $postCommitWork [default: null]
549 * @since 1.26
550 */
551 public function doPreOutputCommit( callable $postCommitWork = null ) {
552 self::preOutputCommit( $this->context, $postCommitWork );
553 }
554
555 /**
556 * This function commits all DB changes as needed before
557 * the user can receive a response (in case commit fails)
558 *
559 * @param IContextSource $context
560 * @param callable $postCommitWork [default: null]
561 * @since 1.27
562 */
563 public static function preOutputCommit(
564 IContextSource $context, callable $postCommitWork = null
565 ) {
566 // Either all DBs should commit or none
567 ignore_user_abort( true );
568
569 $config = $context->getConfig();
570 $request = $context->getRequest();
571 $output = $context->getOutput();
572 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
573
574 // Commit all changes
575 $lbFactory->commitMasterChanges(
576 __METHOD__,
577 // Abort if any transaction was too big
578 [ 'maxWriteDuration' => $config->get( 'MaxUserDBWriteDuration' ) ]
579 );
580 wfDebug( __METHOD__ . ': primary transaction round committed' );
581
582 // Run updates that need to block the user or affect output (this is the last chance)
583 DeferredUpdates::doUpdates( 'enqueue', DeferredUpdates::PRESEND );
584 wfDebug( __METHOD__ . ': pre-send deferred updates completed' );
585
586 // Decide when clients block on ChronologyProtector DB position writes
587 $urlDomainDistance = (
588 $request->wasPosted() &&
589 $output->getRedirect() &&
590 $lbFactory->hasOrMadeRecentMasterChanges( INF )
591 ) ? self::getUrlDomainDistance( $output->getRedirect(), $context ) : false;
592
593 if ( $urlDomainDistance === 'local' || $urlDomainDistance === 'remote' ) {
594 // OutputPage::output() will be fast; $postCommitWork will not be useful for
595 // masking the latency of syncing DB positions accross all datacenters synchronously.
596 // Instead, make use of the RTT time of the client follow redirects.
597 $flags = $lbFactory::SHUTDOWN_CHRONPROT_ASYNC;
598 $cpPosTime = microtime( true );
599 // Client's next request should see 1+ positions with this DBMasterPos::asOf() time
600 if ( $urlDomainDistance === 'local' ) {
601 // Client will stay on this domain, so set an unobtrusive cookie
602 $expires = time() + ChronologyProtector::POSITION_TTL;
603 $options = [ 'prefix' => '' ];
604 $request->response()->setCookie( 'cpPosTime', $cpPosTime, $expires, $options );
605 } else {
606 // Cookies may not work across wiki domains, so use a URL parameter
607 $safeUrl = $lbFactory->appendPreShutdownTimeAsQuery(
608 $output->getRedirect(),
609 $cpPosTime
610 );
611 $output->redirect( $safeUrl );
612 }
613 } else {
614 // OutputPage::output() is fairly slow; run it in $postCommitWork to mask
615 // the latency of syncing DB positions accross all datacenters synchronously
616 $flags = $lbFactory::SHUTDOWN_CHRONPROT_SYNC;
617 if ( $lbFactory->hasOrMadeRecentMasterChanges( INF ) ) {
618 $cpPosTime = microtime( true );
619 // Set a cookie in case the DB position store cannot sync accross datacenters.
620 // This will at least cover the common case of the user staying on the domain.
621 $expires = time() + ChronologyProtector::POSITION_TTL;
622 $options = [ 'prefix' => '' ];
623 $request->response()->setCookie( 'cpPosTime', $cpPosTime, $expires, $options );
624 }
625 }
626 // Record ChronologyProtector positions for DBs affected in this request at this point
627 $lbFactory->shutdown( $flags, $postCommitWork );
628 wfDebug( __METHOD__ . ': LBFactory shutdown completed' );
629
630 // Set a cookie to tell all CDN edge nodes to "stick" the user to the DC that handles this
631 // POST request (e.g. the "master" data center). Also have the user briefly bypass CDN so
632 // ChronologyProtector works for cacheable URLs.
633 if ( $request->wasPosted() && $lbFactory->hasOrMadeRecentMasterChanges() ) {
634 $expires = time() + $config->get( 'DataCenterUpdateStickTTL' );
635 $options = [ 'prefix' => '' ];
636 $request->response()->setCookie( 'UseDC', 'master', $expires, $options );
637 $request->response()->setCookie( 'UseCDNCache', 'false', $expires, $options );
638 }
639
640 // Avoid letting a few seconds of replica DB lag cause a month of stale data. This logic is
641 // also intimately related to the value of $wgCdnReboundPurgeDelay.
642 if ( $lbFactory->laggedReplicaUsed() ) {
643 $maxAge = $config->get( 'CdnMaxageLagged' );
644 $output->lowerCdnMaxage( $maxAge );
645 $request->response()->header( "X-Database-Lagged: true" );
646 wfDebugLog( 'replication', "Lagged DB used; CDN cache TTL limited to $maxAge seconds" );
647 }
648
649 // Avoid long-term cache pollution due to message cache rebuild timeouts (T133069)
650 if ( MessageCache::singleton()->isDisabled() ) {
651 $maxAge = $config->get( 'CdnMaxageSubstitute' );
652 $output->lowerCdnMaxage( $maxAge );
653 $request->response()->header( "X-Response-Substitute: true" );
654 }
655 }
656
657 /**
658 * @param string $url
659 * @param IContextSource $context
660 * @return string|bool Either "local" or "remote" if in the farm, false otherwise
661 */
662 private function getUrlDomainDistance( $url, IContextSource $context ) {
663 static $relevantKeys = [ 'host' => true, 'port' => true ];
664
665 $infoCandidate = wfParseUrl( $url );
666 if ( $infoCandidate === false ) {
667 return false;
668 }
669
670 $infoCandidate = array_intersect_key( $infoCandidate, $relevantKeys );
671 $clusterHosts = array_merge(
672 // Local wiki host (the most common case)
673 [ $context->getConfig()->get( 'CanonicalServer' ) ],
674 // Any local/remote wiki virtual hosts for this wiki farm
675 $context->getConfig()->get( 'LocalVirtualHosts' )
676 );
677
678 foreach ( $clusterHosts as $i => $clusterHost ) {
679 $parseUrl = wfParseUrl( $clusterHost );
680 if ( !$parseUrl ) {
681 continue;
682 }
683 $infoHost = array_intersect_key( $parseUrl, $relevantKeys );
684 if ( $infoCandidate === $infoHost ) {
685 return ( $i === 0 ) ? 'local' : 'remote';
686 }
687 }
688
689 return false;
690 }
691
692 /**
693 * This function does work that can be done *after* the
694 * user gets the HTTP response so they don't block on it
695 *
696 * This manages deferred updates, job insertion,
697 * final commit, and the logging of profiling data
698 *
699 * @param string $mode Use 'fast' to always skip job running
700 * @since 1.26
701 */
702 public function doPostOutputShutdown( $mode = 'normal' ) {
703 $timing = $this->context->getTiming();
704 $timing->mark( 'requestShutdown' );
705
706 // Show visible profiling data if enabled (which cannot be post-send)
707 Profiler::instance()->logDataPageOutputOnly();
708
709 $callback = function () use ( $mode ) {
710 try {
711 $this->restInPeace( $mode );
712 } catch ( Exception $e ) {
713 MWExceptionHandler::handleException( $e );
714 }
715 };
716
717 // Defer everything else...
718 if ( function_exists( 'register_postsend_function' ) ) {
719 // https://github.com/facebook/hhvm/issues/1230
720 register_postsend_function( $callback );
721 } else {
722 if ( function_exists( 'fastcgi_finish_request' ) ) {
723 fastcgi_finish_request();
724 } else {
725 // Either all DB and deferred updates should happen or none.
726 // The latter should not be cancelled due to client disconnect.
727 ignore_user_abort( true );
728 }
729
730 $callback();
731 }
732 }
733
734 private function main() {
735 global $wgTitle;
736
737 $output = $this->context->getOutput();
738 $request = $this->context->getRequest();
739
740 // Send Ajax requests to the Ajax dispatcher.
741 if ( $this->config->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
742 // Set a dummy title, because $wgTitle == null might break things
743 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
744 . __METHOD__
745 );
746 $this->context->setTitle( $title );
747 $wgTitle = $title;
748
749 $dispatcher = new AjaxDispatcher( $this->config );
750 $dispatcher->performAction( $this->context->getUser() );
751
752 return;
753 }
754
755 // Get title from request parameters,
756 // is set on the fly by parseTitle the first time.
757 $title = $this->getTitle();
758 $action = $this->getAction();
759 $wgTitle = $title;
760
761 // Set DB query expectations for this HTTP request
762 $trxLimits = $this->config->get( 'TrxProfilerLimits' );
763 $trxProfiler = Profiler::instance()->getTransactionProfiler();
764 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
765 if ( $request->hasSafeMethod() ) {
766 $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__ );
767 } else {
768 $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__ );
769 }
770
771 // If the user has forceHTTPS set to true, or if the user
772 // is in a group requiring HTTPS, or if they have the HTTPS
773 // preference set, redirect them to HTTPS.
774 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
775 // isLoggedIn() will do all sorts of weird stuff.
776 if (
777 $request->getProtocol() == 'http' &&
778 // switch to HTTPS only when supported by the server
779 preg_match( '#^https://#', wfExpandUrl( $request->getRequestURL(), PROTO_HTTPS ) ) &&
780 (
781 $request->getSession()->shouldForceHTTPS() ||
782 // Check the cookie manually, for paranoia
783 $request->getCookie( 'forceHTTPS', '' ) ||
784 // check for prefixed version that was used for a time in older MW versions
785 $request->getCookie( 'forceHTTPS' ) ||
786 // Avoid checking the user and groups unless it's enabled.
787 (
788 $this->context->getUser()->isLoggedIn()
789 && $this->context->getUser()->requiresHTTPS()
790 )
791 )
792 ) {
793 $oldUrl = $request->getFullRequestURL();
794 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
795
796 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
797 if ( Hooks::run( 'BeforeHttpsRedirect', [ $this->context, &$redirUrl ] ) ) {
798
799 if ( $request->wasPosted() ) {
800 // This is weird and we'd hope it almost never happens. This
801 // means that a POST came in via HTTP and policy requires us
802 // redirecting to HTTPS. It's likely such a request is going
803 // to fail due to post data being lost, but let's try anyway
804 // and just log the instance.
805
806 // @todo FIXME: See if we could issue a 307 or 308 here, need
807 // to see how clients (automated & browser) behave when we do
808 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
809 }
810 // Setup dummy Title, otherwise OutputPage::redirect will fail
811 $title = Title::newFromText( 'REDIR', NS_MAIN );
812 $this->context->setTitle( $title );
813 // Since we only do this redir to change proto, always send a vary header
814 $output->addVaryHeader( 'X-Forwarded-Proto' );
815 $output->redirect( $redirUrl );
816 $output->output();
817
818 return;
819 }
820 }
821
822 if ( $this->config->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
823 if ( HTMLFileCache::useFileCache( $this->context ) ) {
824 // Try low-level file cache hit
825 $cache = new HTMLFileCache( $title, $action );
826 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
827 // Check incoming headers to see if client has this cached
828 $timestamp = $cache->cacheTimestamp();
829 if ( !$output->checkLastModified( $timestamp ) ) {
830 $cache->loadFromFileCache( $this->context );
831 }
832 // Do any stats increment/watchlist stuff
833 // Assume we're viewing the latest revision (this should always be the case with file cache)
834 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
835 // Tell OutputPage that output is taken care of
836 $output->disable();
837
838 return;
839 }
840 }
841 }
842
843 // Actually do the work of the request and build up any output
844 $this->performRequest();
845
846 // GUI-ify and stash the page output in MediaWiki::doPreOutputCommit() while
847 // ChronologyProtector synchronizes DB positions or slaves accross all datacenters.
848 $buffer = null;
849 $outputWork = function () use ( $output, &$buffer ) {
850 if ( $buffer === null ) {
851 $buffer = $output->output( true );
852 }
853
854 return $buffer;
855 };
856
857 // Now commit any transactions, so that unreported errors after
858 // output() don't roll back the whole DB transaction and so that
859 // we avoid having both success and error text in the response
860 $this->doPreOutputCommit( $outputWork );
861
862 // Now send the actual output
863 print $outputWork();
864 }
865
866 /**
867 * Ends this task peacefully
868 * @param string $mode Use 'fast' to always skip job running
869 */
870 public function restInPeace( $mode = 'fast' ) {
871 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
872 // Assure deferred updates are not in the main transaction
873 $lbFactory->commitMasterChanges( __METHOD__ );
874
875 // Loosen DB query expectations since the HTTP client is unblocked
876 $trxProfiler = Profiler::instance()->getTransactionProfiler();
877 $trxProfiler->resetExpectations();
878 $trxProfiler->setExpectations(
879 $this->config->get( 'TrxProfilerLimits' )['PostSend'],
880 __METHOD__
881 );
882
883 // Do any deferred jobs
884 DeferredUpdates::doUpdates( 'enqueue' );
885
886 // Make sure any lazy jobs are pushed
887 JobQueueGroup::pushLazyJobs();
888
889 // Now that everything specific to this request is done,
890 // try to occasionally run jobs (if enabled) from the queues
891 if ( $mode === 'normal' ) {
892 $this->triggerJobs();
893 }
894
895 // Log profiling data, e.g. in the database or UDP
896 wfLogProfilingData();
897
898 // Commit and close up!
899 $lbFactory->commitMasterChanges( __METHOD__ );
900 $lbFactory->shutdown( LBFactory::SHUTDOWN_NO_CHRONPROT );
901
902 wfDebug( "Request ended normally\n" );
903 }
904
905 /**
906 * Potentially open a socket and sent an HTTP request back to the server
907 * to run a specified number of jobs. This registers a callback to cleanup
908 * the socket once it's done.
909 */
910 public function triggerJobs() {
911 $jobRunRate = $this->config->get( 'JobRunRate' );
912 if ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
913 return; // recursion guard
914 } elseif ( $jobRunRate <= 0 || wfReadOnly() ) {
915 return;
916 }
917
918 if ( $jobRunRate < 1 ) {
919 $max = mt_getrandmax();
920 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
921 return; // the higher the job run rate, the less likely we return here
922 }
923 $n = 1;
924 } else {
925 $n = intval( $jobRunRate );
926 }
927
928 $runJobsLogger = LoggerFactory::getInstance( 'runJobs' );
929
930 // Fall back to running the job(s) while the user waits if needed
931 if ( !$this->config->get( 'RunJobsAsync' ) ) {
932 $runner = new JobRunner( $runJobsLogger );
933 $runner->run( [ 'maxJobs' => $n ] );
934 return;
935 }
936
937 // Do not send request if there are probably no jobs
938 try {
939 $group = JobQueueGroup::singleton();
940 if ( !$group->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
941 return;
942 }
943 } catch ( JobQueueError $e ) {
944 MWExceptionHandler::logException( $e );
945 return; // do not make the site unavailable
946 }
947
948 $query = [ 'title' => 'Special:RunJobs',
949 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 ];
950 $query['signature'] = SpecialRunJobs::getQuerySignature(
951 $query, $this->config->get( 'SecretKey' ) );
952
953 $errno = $errstr = null;
954 $info = wfParseUrl( $this->config->get( 'CanonicalServer' ) );
955 $host = $info ? $info['host'] : null;
956 $port = 80;
957 if ( isset( $info['scheme'] ) && $info['scheme'] == 'https' ) {
958 $host = "tls://" . $host;
959 $port = 443;
960 }
961 if ( isset( $info['port'] ) ) {
962 $port = $info['port'];
963 }
964
965 MediaWiki\suppressWarnings();
966 $sock = $host ? fsockopen(
967 $host,
968 $port,
969 $errno,
970 $errstr,
971 // If it takes more than 100ms to connect to ourselves there is a problem...
972 0.100
973 ) : false;
974 MediaWiki\restoreWarnings();
975
976 $invokedWithSuccess = true;
977 if ( $sock ) {
978 $special = SpecialPageFactory::getPage( 'RunJobs' );
979 $url = $special->getPageTitle()->getCanonicalURL( $query );
980 $req = (
981 "POST $url HTTP/1.1\r\n" .
982 "Host: {$info['host']}\r\n" .
983 "Connection: Close\r\n" .
984 "Content-Length: 0\r\n\r\n"
985 );
986
987 $runJobsLogger->info( "Running $n job(s) via '$url'" );
988 // Send a cron API request to be performed in the background.
989 // Give up if this takes too long to send (which should be rare).
990 stream_set_timeout( $sock, 2 );
991 $bytes = fwrite( $sock, $req );
992 if ( $bytes !== strlen( $req ) ) {
993 $invokedWithSuccess = false;
994 $runJobsLogger->error( "Failed to start cron API (socket write error)" );
995 } else {
996 // Do not wait for the response (the script should handle client aborts).
997 // Make sure that we don't close before that script reaches ignore_user_abort().
998 $start = microtime( true );
999 $status = fgets( $sock );
1000 $sec = microtime( true ) - $start;
1001 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
1002 $invokedWithSuccess = false;
1003 $runJobsLogger->error( "Failed to start cron API: received '$status' ($sec)" );
1004 }
1005 }
1006 fclose( $sock );
1007 } else {
1008 $invokedWithSuccess = false;
1009 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
1010 }
1011
1012 // Fall back to running the job(s) while the user waits if needed
1013 if ( !$invokedWithSuccess ) {
1014 $runJobsLogger->warning( "Jobs switched to blocking; Special:RunJobs disabled" );
1015
1016 $runner = new JobRunner( $runJobsLogger );
1017 $runner->run( [ 'maxJobs' => $n ] );
1018 }
1019 }
1020 }