Merge "resourceloader: Improve coverage in ResourceLoaderTest.php"
[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 $url = $request->getFullRequestURL(); // requested URL
290 if (
291 $request->getMethod() === 'GET' &&
292 $url === $article->getTitle()->getCanonicalURL() &&
293 $article->checkTouched() &&
294 $output->checkLastModified( $article->getTouched() )
295 ) {
296 wfDebug( __METHOD__ . ": done 304\n" );
297 return;
298 }
299 $this->performAction( $article, $requestTitle );
300 } elseif ( is_string( $article ) ) {
301 $output->redirect( $article );
302 } else {
303 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
304 . " returned neither an object nor a URL" );
305 }
306 }
307 }
308 }
309
310 /**
311 * Handle redirects for uncanonical title requests.
312 *
313 * Handles:
314 * - Redirect loops.
315 * - No title in URL.
316 * - $wgUsePathInfo URLs.
317 * - URLs with a variant.
318 * - Other non-standard URLs (as long as they have no extra query parameters).
319 *
320 * Behaviour:
321 * - Normalise title values:
322 * /wiki/Foo%20Bar -> /wiki/Foo_Bar
323 * - Normalise empty title:
324 * /wiki/ -> /wiki/Main
325 * /w/index.php?title= -> /wiki/Main
326 * - Normalise non-standard title urls:
327 * /w/index.php?title=Foo_Bar -> /wiki/Foo_Bar
328 * - Don't redirect anything with query parameters other than 'title' or 'action=view'.
329 *
330 * @param Title $title
331 * @return bool True if a redirect was set.
332 * @throws HttpError
333 */
334 private function tryNormaliseRedirect( Title $title ) {
335 $request = $this->context->getRequest();
336 $output = $this->context->getOutput();
337
338 if ( $request->getVal( 'action', 'view' ) != 'view'
339 || $request->wasPosted()
340 || count( $request->getValueNames( [ 'action', 'title' ] ) )
341 || !Hooks::run( 'TestCanonicalRedirect', [ $request, $title, $output ] )
342 ) {
343 return false;
344 }
345
346 if ( $title->isSpecialPage() ) {
347 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
348 if ( $name ) {
349 $title = SpecialPage::getTitleFor( $name, $subpage );
350 }
351 }
352 // Redirect to canonical url, make it a 301 to allow caching
353 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
354
355 if ( $targetUrl != $request->getFullRequestURL() ) {
356 $output->setCdnMaxage( 1200 );
357 $output->redirect( $targetUrl, '301' );
358 return true;
359 }
360
361 // If there is no title, or the title is in a non-standard encoding, we demand
362 // a redirect. If cgi somehow changed the 'title' query to be non-standard while
363 // the url is standard, the server is misconfigured.
364 if ( $request->getVal( 'title' ) === null
365 || $title->getPrefixedDBkey() != $request->getVal( 'title' )
366 ) {
367 $message = "Redirect loop detected!\n\n" .
368 "This means the wiki got confused about what page was " .
369 "requested; this sometimes happens when moving a wiki " .
370 "to a new server or changing the server configuration.\n\n";
371
372 if ( $this->config->get( 'UsePathInfo' ) ) {
373 $message .= "The wiki is trying to interpret the page " .
374 "title from the URL path portion (PATH_INFO), which " .
375 "sometimes fails depending on the web server. Try " .
376 "setting \"\$wgUsePathInfo = false;\" in your " .
377 "LocalSettings.php, or check that \$wgArticlePath " .
378 "is correct.";
379 } else {
380 $message .= "Your web server was detected as possibly not " .
381 "supporting URL path components (PATH_INFO) correctly; " .
382 "check your LocalSettings.php for a customized " .
383 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
384 "to true.";
385 }
386 throw new HttpError( 500, $message );
387 }
388 return false;
389 }
390
391 /**
392 * Initialize the main Article object for "standard" actions (view, etc)
393 * Create an Article object for the page, following redirects if needed.
394 *
395 * @return Article|string An Article, or a string to redirect to another URL
396 */
397 private function initializeArticle() {
398 $title = $this->context->getTitle();
399 if ( $this->context->canUseWikiPage() ) {
400 // Try to use request context wiki page, as there
401 // is already data from db saved in per process
402 // cache there from this->getAction() call.
403 $page = $this->context->getWikiPage();
404 } else {
405 // This case should not happen, but just in case.
406 // @TODO: remove this or use an exception
407 $page = WikiPage::factory( $title );
408 $this->context->setWikiPage( $page );
409 wfWarn( "RequestContext::canUseWikiPage() returned false" );
410 }
411
412 // Make GUI wrapper for the WikiPage
413 $article = Article::newFromWikiPage( $page, $this->context );
414
415 // Skip some unnecessary code if the content model doesn't support redirects
416 if ( !ContentHandler::getForTitle( $title )->supportsRedirects() ) {
417 return $article;
418 }
419
420 $request = $this->context->getRequest();
421
422 // Namespace might change when using redirects
423 // Check for redirects ...
424 $action = $request->getVal( 'action', 'view' );
425 $file = ( $page instanceof WikiFilePage ) ? $page->getFile() : null;
426 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
427 && !$request->getVal( 'oldid' ) // ... and are not old revisions
428 && !$request->getVal( 'diff' ) // ... and not when showing diff
429 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
430 // ... and the article is not a non-redirect image page with associated file
431 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
432 ) {
433 // Give extensions a change to ignore/handle redirects as needed
434 $ignoreRedirect = $target = false;
435
436 Hooks::run( 'InitializeArticleMaybeRedirect',
437 [ &$title, &$request, &$ignoreRedirect, &$target, &$article ] );
438 $page = $article->getPage(); // reflect any hook changes
439
440 // Follow redirects only for... redirects.
441 // If $target is set, then a hook wanted to redirect.
442 if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) {
443 // Is the target already set by an extension?
444 $target = $target ? $target : $page->followRedirect();
445 if ( is_string( $target ) ) {
446 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
447 // we'll need to redirect
448 return $target;
449 }
450 }
451 if ( is_object( $target ) ) {
452 // Rewrite environment to redirected article
453 $rpage = WikiPage::factory( $target );
454 $rpage->loadPageData();
455 if ( $rpage->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
456 $rarticle = Article::newFromWikiPage( $rpage, $this->context );
457 $rarticle->setRedirectedFrom( $title );
458
459 $article = $rarticle;
460 $this->context->setTitle( $target );
461 $this->context->setWikiPage( $article->getPage() );
462 }
463 }
464 } else {
465 // Article may have been changed by hook
466 $this->context->setTitle( $article->getTitle() );
467 $this->context->setWikiPage( $article->getPage() );
468 }
469 }
470
471 return $article;
472 }
473
474 /**
475 * Perform one of the "standard" actions
476 *
477 * @param Page $page
478 * @param Title $requestTitle The original title, before any redirects were applied
479 */
480 private function performAction( Page $page, Title $requestTitle ) {
481 $request = $this->context->getRequest();
482 $output = $this->context->getOutput();
483 $title = $this->context->getTitle();
484 $user = $this->context->getUser();
485
486 if ( !Hooks::run( 'MediaWikiPerformAction',
487 [ $output, $page, $title, $user, $request, $this ] )
488 ) {
489 return;
490 }
491
492 $act = $this->getAction();
493 $action = Action::factory( $act, $page, $this->context );
494
495 if ( $action instanceof Action ) {
496 // Narrow DB query expectations for this HTTP request
497 $trxLimits = $this->config->get( 'TrxProfilerLimits' );
498 $trxProfiler = Profiler::instance()->getTransactionProfiler();
499 if ( $request->wasPosted() && !$action->doesWrites() ) {
500 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
501 $request->markAsSafeRequest();
502 }
503
504 # Let CDN cache things if we can purge them.
505 if ( $this->config->get( 'UseSquid' ) &&
506 in_array(
507 // Use PROTO_INTERNAL because that's what getCdnUrls() uses
508 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
509 $requestTitle->getCdnUrls()
510 )
511 ) {
512 $output->setCdnMaxage( $this->config->get( 'SquidMaxage' ) );
513 }
514
515 $action->show();
516 return;
517 }
518
519 if ( Hooks::run( 'UnknownAction', [ $request->getVal( 'action', 'view' ), $page ] ) ) {
520 $output->setStatusCode( 404 );
521 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
522 }
523 }
524
525 /**
526 * Run the current MediaWiki instance; index.php just calls this
527 */
528 public function run() {
529 try {
530 try {
531 $this->main();
532 } catch ( ErrorPageError $e ) {
533 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
534 // they are not internal application faults. As with normal requests, this
535 // should commit, print the output, do deferred updates, jobs, and profiling.
536 $this->doPreOutputCommit();
537 $e->report(); // display the GUI error
538 }
539 } catch ( Exception $e ) {
540 MWExceptionHandler::handleException( $e );
541 }
542
543 $this->doPostOutputShutdown( 'normal' );
544 }
545
546 /**
547 * @see MediaWiki::preOutputCommit()
548 * @since 1.26
549 */
550 public function doPreOutputCommit() {
551 self::preOutputCommit( $this->context );
552 }
553
554 /**
555 * This function commits all DB changes as needed before
556 * the user can receive a response (in case commit fails)
557 *
558 * @param IContextSource $context
559 * @since 1.27
560 */
561 public static function preOutputCommit( IContextSource $context ) {
562 // Either all DBs should commit or none
563 ignore_user_abort( true );
564
565 $config = $context->getConfig();
566
567 $factory = wfGetLBFactory();
568 // Commit all changes
569 $factory->commitMasterChanges(
570 __METHOD__,
571 // Abort if any transaction was too big
572 [ 'maxWriteDuration' => $config->get( 'MaxUserDBWriteDuration' ) ]
573 );
574 // Record ChronologyProtector positions
575 $factory->shutdown();
576 wfDebug( __METHOD__ . ': all transactions committed' );
577
578 DeferredUpdates::doUpdates( 'enqueue', DeferredUpdates::PRESEND );
579 wfDebug( __METHOD__ . ': pre-send deferred updates completed' );
580
581 // Set a cookie to tell all CDN edge nodes to "stick" the user to the DC that handles this
582 // POST request (e.g. the "master" data center). Also have the user briefly bypass CDN so
583 // ChronologyProtector works for cacheable URLs.
584 $request = $context->getRequest();
585 if ( $request->wasPosted() && $factory->hasOrMadeRecentMasterChanges() ) {
586 $expires = time() + $config->get( 'DataCenterUpdateStickTTL' );
587 $options = [ 'prefix' => '' ];
588 $request->response()->setCookie( 'UseDC', 'master', $expires, $options );
589 $request->response()->setCookie( 'UseCDNCache', 'false', $expires, $options );
590 }
591
592 // Avoid letting a few seconds of slave lag cause a month of stale data. This logic is
593 // also intimately related to the value of $wgCdnReboundPurgeDelay.
594 if ( $factory->laggedSlaveUsed() ) {
595 $maxAge = $config->get( 'CdnMaxageLagged' );
596 $context->getOutput()->lowerCdnMaxage( $maxAge );
597 $request->response()->header( "X-Database-Lagged: true" );
598 wfDebugLog( 'replication', "Lagged DB used; CDN cache TTL limited to $maxAge seconds" );
599 }
600
601 // Avoid long-term cache pollution due to message cache rebuild timeouts (T133069)
602 if ( MessageCache::singleton()->isDisabled() ) {
603 $maxAge = $config->get( 'CdnMaxageSubstitute' );
604 $context->getOutput()->lowerCdnMaxage( $maxAge );
605 $request->response()->header( "X-Response-Substitute: true" );
606 }
607 }
608
609 /**
610 * This function does work that can be done *after* the
611 * user gets the HTTP response so they don't block on it
612 *
613 * This manages deferred updates, job insertion,
614 * final commit, and the logging of profiling data
615 *
616 * @param string $mode Use 'fast' to always skip job running
617 * @since 1.26
618 */
619 public function doPostOutputShutdown( $mode = 'normal' ) {
620 $timing = $this->context->getTiming();
621 $timing->mark( 'requestShutdown' );
622
623 // Show visible profiling data if enabled (which cannot be post-send)
624 Profiler::instance()->logDataPageOutputOnly();
625
626 $that = $this;
627 $callback = function () use ( $that, $mode ) {
628 try {
629 $that->restInPeace( $mode );
630 } catch ( Exception $e ) {
631 MWExceptionHandler::handleException( $e );
632 }
633 };
634
635 // Defer everything else...
636 if ( function_exists( 'register_postsend_function' ) ) {
637 // https://github.com/facebook/hhvm/issues/1230
638 register_postsend_function( $callback );
639 } else {
640 if ( function_exists( 'fastcgi_finish_request' ) ) {
641 fastcgi_finish_request();
642 } else {
643 // Either all DB and deferred updates should happen or none.
644 // The later should not be cancelled due to client disconnect.
645 ignore_user_abort( true );
646 }
647
648 $callback();
649 }
650 }
651
652 private function main() {
653 global $wgTitle;
654
655 $request = $this->context->getRequest();
656
657 // Send Ajax requests to the Ajax dispatcher.
658 if ( $this->config->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
659 // Set a dummy title, because $wgTitle == null might break things
660 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
661 . __METHOD__
662 );
663 $this->context->setTitle( $title );
664 $wgTitle = $title;
665
666 $dispatcher = new AjaxDispatcher( $this->config );
667 $dispatcher->performAction( $this->context->getUser() );
668 return;
669 }
670
671 // Get title from request parameters,
672 // is set on the fly by parseTitle the first time.
673 $title = $this->getTitle();
674 $action = $this->getAction();
675 $wgTitle = $title;
676
677 // Set DB query expectations for this HTTP request
678 $trxLimits = $this->config->get( 'TrxProfilerLimits' );
679 $trxProfiler = Profiler::instance()->getTransactionProfiler();
680 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
681 if ( $request->hasSafeMethod() ) {
682 $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__ );
683 } else {
684 $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__ );
685 }
686
687 // If the user has forceHTTPS set to true, or if the user
688 // is in a group requiring HTTPS, or if they have the HTTPS
689 // preference set, redirect them to HTTPS.
690 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
691 // isLoggedIn() will do all sorts of weird stuff.
692 if (
693 $request->getProtocol() == 'http' &&
694 // switch to HTTPS only when supported by the server
695 preg_match( '#^https://#', wfExpandUrl( $request->getRequestURL(), PROTO_HTTPS ) ) &&
696 (
697 $request->getSession()->shouldForceHTTPS() ||
698 // Check the cookie manually, for paranoia
699 $request->getCookie( 'forceHTTPS', '' ) ||
700 // check for prefixed version that was used for a time in older MW versions
701 $request->getCookie( 'forceHTTPS' ) ||
702 // Avoid checking the user and groups unless it's enabled.
703 (
704 $this->context->getUser()->isLoggedIn()
705 && $this->context->getUser()->requiresHTTPS()
706 )
707 )
708 ) {
709 $oldUrl = $request->getFullRequestURL();
710 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
711
712 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
713 if ( Hooks::run( 'BeforeHttpsRedirect', [ $this->context, &$redirUrl ] ) ) {
714
715 if ( $request->wasPosted() ) {
716 // This is weird and we'd hope it almost never happens. This
717 // means that a POST came in via HTTP and policy requires us
718 // redirecting to HTTPS. It's likely such a request is going
719 // to fail due to post data being lost, but let's try anyway
720 // and just log the instance.
721
722 // @todo FIXME: See if we could issue a 307 or 308 here, need
723 // to see how clients (automated & browser) behave when we do
724 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
725 }
726 // Setup dummy Title, otherwise OutputPage::redirect will fail
727 $title = Title::newFromText( 'REDIR', NS_MAIN );
728 $this->context->setTitle( $title );
729 $output = $this->context->getOutput();
730 // Since we only do this redir to change proto, always send a vary header
731 $output->addVaryHeader( 'X-Forwarded-Proto' );
732 $output->redirect( $redirUrl );
733 $output->output();
734 return;
735 }
736 }
737
738 if ( $this->config->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
739 if ( HTMLFileCache::useFileCache( $this->context ) ) {
740 // Try low-level file cache hit
741 $cache = new HTMLFileCache( $title, $action );
742 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
743 // Check incoming headers to see if client has this cached
744 $timestamp = $cache->cacheTimestamp();
745 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
746 $cache->loadFromFileCache( $this->context );
747 }
748 // Do any stats increment/watchlist stuff
749 // Assume we're viewing the latest revision (this should always be the case with file cache)
750 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
751 // Tell OutputPage that output is taken care of
752 $this->context->getOutput()->disable();
753 return;
754 }
755 }
756 }
757
758 // Actually do the work of the request and build up any output
759 $this->performRequest();
760
761 // Now commit any transactions, so that unreported errors after
762 // output() don't roll back the whole DB transaction and so that
763 // we avoid having both success and error text in the response
764 $this->doPreOutputCommit();
765
766 // Output everything!
767 $this->context->getOutput()->output();
768 }
769
770 /**
771 * Ends this task peacefully
772 * @param string $mode Use 'fast' to always skip job running
773 */
774 public function restInPeace( $mode = 'fast' ) {
775 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
776 // Assure deferred updates are not in the main transaction
777 $factory->commitMasterChanges( __METHOD__ );
778
779 // Loosen DB query expectations since the HTTP client is unblocked
780 $trxProfiler = Profiler::instance()->getTransactionProfiler();
781 $trxProfiler->resetExpectations();
782 $trxProfiler->setExpectations(
783 $this->config->get( 'TrxProfilerLimits' )['PostSend'],
784 __METHOD__
785 );
786
787 // Do any deferred jobs
788 DeferredUpdates::doUpdates( 'enqueue' );
789
790 // Make sure any lazy jobs are pushed
791 JobQueueGroup::pushLazyJobs();
792
793 // Now that everything specific to this request is done,
794 // try to occasionally run jobs (if enabled) from the queues
795 if ( $mode === 'normal' ) {
796 $this->triggerJobs();
797 }
798
799 // Log profiling data, e.g. in the database or UDP
800 wfLogProfilingData();
801
802 // Commit and close up!
803 $factory->commitMasterChanges( __METHOD__ );
804 $factory->shutdown( LBFactory::SHUTDOWN_NO_CHRONPROT );
805
806 wfDebug( "Request ended normally\n" );
807 }
808
809 /**
810 * Potentially open a socket and sent an HTTP request back to the server
811 * to run a specified number of jobs. This registers a callback to cleanup
812 * the socket once it's done.
813 */
814 public function triggerJobs() {
815 $jobRunRate = $this->config->get( 'JobRunRate' );
816 if ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
817 return; // recursion guard
818 } elseif ( $jobRunRate <= 0 || wfReadOnly() ) {
819 return;
820 }
821
822 if ( $jobRunRate < 1 ) {
823 $max = mt_getrandmax();
824 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
825 return; // the higher the job run rate, the less likely we return here
826 }
827 $n = 1;
828 } else {
829 $n = intval( $jobRunRate );
830 }
831
832 $runJobsLogger = LoggerFactory::getInstance( 'runJobs' );
833
834 if ( !$this->config->get( 'RunJobsAsync' ) ) {
835 // Fall back to running the job here while the user waits
836 $runner = new JobRunner( $runJobsLogger );
837 $runner->run( [ 'maxJobs' => $n ] );
838 return;
839 }
840
841 try {
842 if ( !JobQueueGroup::singleton()->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
843 return; // do not send request if there are probably no jobs
844 }
845 } catch ( JobQueueError $e ) {
846 MWExceptionHandler::logException( $e );
847 return; // do not make the site unavailable
848 }
849
850 $query = [ 'title' => 'Special:RunJobs',
851 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 ];
852 $query['signature'] = SpecialRunJobs::getQuerySignature(
853 $query, $this->config->get( 'SecretKey' ) );
854
855 $errno = $errstr = null;
856 $info = wfParseUrl( $this->config->get( 'CanonicalServer' ) );
857 MediaWiki\suppressWarnings();
858 $host = $info['host'];
859 $port = 80;
860 if ( isset( $info['scheme'] ) && $info['scheme'] == 'https' ) {
861 $host = "tls://" . $host;
862 $port = 443;
863 }
864 if ( isset( $info['port'] ) ) {
865 $port = $info['port'];
866 }
867 $sock = fsockopen(
868 $host,
869 $port,
870 $errno,
871 $errstr,
872 // If it takes more than 100ms to connect to ourselves there
873 // is a problem elsewhere.
874 0.1
875 );
876 MediaWiki\restoreWarnings();
877 if ( !$sock ) {
878 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
879 // Fall back to running the job here while the user waits
880 $runner = new JobRunner( $runJobsLogger );
881 $runner->run( [ 'maxJobs' => $n ] );
882 return;
883 }
884
885 $special = SpecialPageFactory::getPage( 'RunJobs' );
886 $url = $special->getPageTitle()->getCanonicalURL( $query );
887 $req = (
888 "POST $url HTTP/1.1\r\n" .
889 "Host: {$info['host']}\r\n" .
890 "Connection: Close\r\n" .
891 "Content-Length: 0\r\n\r\n"
892 );
893
894 $runJobsLogger->info( "Running $n job(s) via '$url'" );
895 // Send a cron API request to be performed in the background.
896 // Give up if this takes too long to send (which should be rare).
897 stream_set_timeout( $sock, 2 );
898 $bytes = fwrite( $sock, $req );
899 if ( $bytes !== strlen( $req ) ) {
900 $runJobsLogger->error( "Failed to start cron API (socket write error)" );
901 } else {
902 // Do not wait for the response (the script should handle client aborts).
903 // Make sure that we don't close before that script reaches ignore_user_abort().
904 $status = fgets( $sock );
905 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
906 $runJobsLogger->error( "Failed to start cron API: received '$status'" );
907 }
908 }
909 fclose( $sock );
910 }
911 }