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