Merge "Cleanup test jobs better"
[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
25 /**
26 * The MediaWiki class is the helper class for the index.php entry point.
27 */
28 class MediaWiki {
29 /**
30 * @var IContextSource
31 */
32 private $context;
33
34 /**
35 * @var Config
36 */
37 private $config;
38
39 /**
40 * @param IContextSource|null $context
41 */
42 public function __construct( IContextSource $context = null ) {
43 if ( !$context ) {
44 $context = RequestContext::getMain();
45 }
46
47 $this->context = $context;
48 $this->config = $context->getConfig();
49 }
50
51 /**
52 * Parse the request to get the Title object
53 *
54 * @throws MalformedTitleException If a title has been provided by the user, but is invalid.
55 * @return Title Title object to be $wgTitle
56 */
57 private function parseTitle() {
58 global $wgContLang;
59
60 $request = $this->context->getRequest();
61 $curid = $request->getInt( 'curid' );
62 $title = $request->getVal( 'title' );
63 $action = $request->getVal( 'action' );
64
65 if ( $request->getCheck( 'search' ) ) {
66 // Compatibility with old search URLs which didn't use Special:Search
67 // Just check for presence here, so blank requests still
68 // show the search page when using ugly URLs (bug 8054).
69 $ret = SpecialPage::getTitleFor( 'Search' );
70 } elseif ( $curid ) {
71 // URLs like this are generated by RC, because rc_title isn't always accurate
72 $ret = Title::newFromID( $curid );
73 } else {
74 $ret = Title::newFromURL( $title );
75 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
76 // in wikitext links to tell Parser to make a direct file link
77 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) {
78 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
79 }
80 // Check variant links so that interwiki links don't have to worry
81 // about the possible different language variants
82 if ( count( $wgContLang->getVariants() ) > 1
83 && !is_null( $ret ) && $ret->getArticleID() == 0
84 ) {
85 $wgContLang->findVariantLink( $title, $ret );
86 }
87 }
88
89 // If title is not provided, always allow oldid and diff to set the title.
90 // If title is provided, allow oldid and diff to override the title, unless
91 // we are talking about a special page which might use these parameters for
92 // other purposes.
93 if ( $ret === null || !$ret->isSpecialPage() ) {
94 // We can have urls with just ?diff=,?oldid= or even just ?diff=
95 $oldid = $request->getInt( 'oldid' );
96 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
97 // Allow oldid to override a changed or missing title
98 if ( $oldid ) {
99 $rev = Revision::newFromId( $oldid );
100 $ret = $rev ? $rev->getTitle() : $ret;
101 }
102 }
103
104 // Use the main page as default title if nothing else has been provided
105 if ( $ret === null
106 && strval( $title ) === ''
107 && !$request->getCheck( 'curid' )
108 && $action !== 'delete'
109 ) {
110 $ret = Title::newMainPage();
111 }
112
113 if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
114 // If we get here, we definitely don't have a valid title; throw an exception.
115 // Try to get detailed invalid title exception first, fall back to MalformedTitleException.
116 Title::newFromTextThrow( $title );
117 throw new MalformedTitleException( 'badtitletext', $title );
118 }
119
120 return $ret;
121 }
122
123 /**
124 * Get the Title object that we'll be acting on, as specified in the WebRequest
125 * @return Title
126 */
127 public function getTitle() {
128 if ( !$this->context->hasTitle() ) {
129 try {
130 $this->context->setTitle( $this->parseTitle() );
131 } catch ( MalformedTitleException $ex ) {
132 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
133 }
134 }
135 return $this->context->getTitle();
136 }
137
138 /**
139 * Returns the name of the action that will be executed.
140 *
141 * @return string Action
142 */
143 public function getAction() {
144 static $action = null;
145
146 if ( $action === null ) {
147 $action = Action::getActionName( $this->context );
148 }
149
150 return $action;
151 }
152
153 /**
154 * Performs the request.
155 * - bad titles
156 * - read restriction
157 * - local interwiki redirects
158 * - redirect loop
159 * - special pages
160 * - normal pages
161 *
162 * @throws MWException|PermissionsError|BadTitleError|HttpError
163 * @return void
164 */
165 private function performRequest() {
166 global $wgTitle;
167
168 $request = $this->context->getRequest();
169 $requestTitle = $title = $this->context->getTitle();
170 $output = $this->context->getOutput();
171 $user = $this->context->getUser();
172
173 if ( $request->getVal( 'printable' ) === 'yes' ) {
174 $output->setPrintable();
175 }
176
177 $unused = null; // To pass it by reference
178 Hooks::run( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
179
180 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
181 if ( is_null( $title ) || ( $title->getDBkey() == '' && !$title->isExternal() )
182 || $title->isSpecial( 'Badtitle' )
183 ) {
184 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
185 try {
186 $this->parseTitle();
187 } catch ( MalformedTitleException $ex ) {
188 throw new BadTitleError( $ex );
189 }
190 throw new BadTitleError();
191 }
192
193 // Check user's permissions to read this page.
194 // We have to check here to catch special pages etc.
195 // We will check again in Article::view().
196 $permErrors = $title->isSpecial( 'RunJobs' )
197 ? array() // relies on HMAC key signature alone
198 : $title->getUserPermissionsErrors( 'read', $user );
199 if ( count( $permErrors ) ) {
200 // Bug 32276: allowing the skin to generate output with $wgTitle or
201 // $this->context->title set to the input title would allow anonymous users to
202 // determine whether a page exists, potentially leaking private data. In fact, the
203 // curid and oldid request parameters would allow page titles to be enumerated even
204 // when they are not guessable. So we reset the title to Special:Badtitle before the
205 // permissions error is displayed.
206
207 // The skin mostly uses $this->context->getTitle() these days, but some extensions
208 // still use $wgTitle.
209 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
210 $this->context->setTitle( $badTitle );
211 $wgTitle = $badTitle;
212
213 throw new PermissionsError( 'read', $permErrors );
214 }
215
216 // Interwiki redirects
217 if ( $title->isExternal() ) {
218 $rdfrom = $request->getVal( 'rdfrom' );
219 if ( $rdfrom ) {
220 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
221 } else {
222 $query = $request->getValues();
223 unset( $query['title'] );
224 $url = $title->getFullURL( $query );
225 }
226 // Check for a redirect loop
227 if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
228 && $title->isLocal()
229 ) {
230 // 301 so google et al report the target as the actual url.
231 $output->redirect( $url, 301 );
232 } else {
233 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
234 try {
235 $this->parseTitle();
236 } catch ( MalformedTitleException $ex ) {
237 throw new BadTitleError( $ex );
238 }
239 throw new BadTitleError();
240 }
241 // Handle any other redirects.
242 // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
243 } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
244
245 // Special pages
246 if ( NS_SPECIAL == $title->getNamespace() ) {
247 // Actions that need to be made when we have a special pages
248 SpecialPageFactory::executePath( $title, $this->context );
249 } else {
250 // ...otherwise treat it as an article view. The article
251 // may still be a wikipage redirect to another article or URL.
252 $article = $this->initializeArticle();
253 if ( is_object( $article ) ) {
254 $this->performAction( $article, $requestTitle );
255 } elseif ( is_string( $article ) ) {
256 $output->redirect( $article );
257 } else {
258 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
259 . " returned neither an object nor a URL" );
260 }
261 }
262 }
263 }
264
265 /**
266 * Handle redirects for uncanonical title requests.
267 *
268 * Handles:
269 * - Redirect loops.
270 * - No title in URL.
271 * - $wgUsePathInfo URLs.
272 * - URLs with a variant.
273 * - Other non-standard URLs (as long as they have no extra query parameters).
274 *
275 * Behaviour:
276 * - Normalise title values:
277 * /wiki/Foo%20Bar -> /wiki/Foo_Bar
278 * - Normalise empty title:
279 * /wiki/ -> /wiki/Main
280 * /w/index.php?title= -> /wiki/Main
281 * - Normalise non-standard title urls:
282 * /w/index.php?title=Foo_Bar -> /wiki/Foo_Bar
283 * - Don't redirect anything with query parameters other than 'title' or 'action=view'.
284 *
285 * @param Title $title
286 * @return bool True if a redirect was set.
287 * @throws HttpError
288 */
289 private function tryNormaliseRedirect( Title $title ) {
290 $request = $this->context->getRequest();
291 $output = $this->context->getOutput();
292
293 if ( $request->getVal( 'action', 'view' ) != 'view'
294 || $request->wasPosted()
295 || count( $request->getValueNames( array( 'action', 'title' ) ) )
296 || !Hooks::run( 'TestCanonicalRedirect', array( $request, $title, $output ) )
297 ) {
298 return false;
299 }
300
301 if ( $title->isSpecialPage() ) {
302 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
303 if ( $name ) {
304 $title = SpecialPage::getTitleFor( $name, $subpage );
305 }
306 }
307 // Redirect to canonical url, make it a 301 to allow caching
308 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
309
310 if ( $targetUrl != $request->getFullRequestURL() ) {
311 $output->setCdnMaxage( 1200 );
312 $output->redirect( $targetUrl, '301' );
313 return true;
314 }
315
316 // If there is no title, or the title is in a non-standard encoding, we demand
317 // a redirect. If cgi somehow changed the 'title' query to be non-standard while
318 // the url is standard, the server is misconfigured.
319 if ( $request->getVal( 'title' ) === null
320 || $title->getPrefixedDBkey() != $request->getVal( 'title' )
321 ) {
322 $message = "Redirect loop detected!\n\n" .
323 "This means the wiki got confused about what page was " .
324 "requested; this sometimes happens when moving a wiki " .
325 "to a new server or changing the server configuration.\n\n";
326
327 if ( $this->config->get( 'UsePathInfo' ) ) {
328 $message .= "The wiki is trying to interpret the page " .
329 "title from the URL path portion (PATH_INFO), which " .
330 "sometimes fails depending on the web server. Try " .
331 "setting \"\$wgUsePathInfo = false;\" in your " .
332 "LocalSettings.php, or check that \$wgArticlePath " .
333 "is correct.";
334 } else {
335 $message .= "Your web server was detected as possibly not " .
336 "supporting URL path components (PATH_INFO) correctly; " .
337 "check your LocalSettings.php for a customized " .
338 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
339 "to true.";
340 }
341 throw new HttpError( 500, $message );
342 }
343 return false;
344 }
345
346 /**
347 * Initialize the main Article object for "standard" actions (view, etc)
348 * Create an Article object for the page, following redirects if needed.
349 *
350 * @return mixed An Article, or a string to redirect to another URL
351 */
352 private function initializeArticle() {
353
354 $title = $this->context->getTitle();
355 if ( $this->context->canUseWikiPage() ) {
356 // Try to use request context wiki page, as there
357 // is already data from db saved in per process
358 // cache there from this->getAction() call.
359 $page = $this->context->getWikiPage();
360 $article = Article::newFromWikiPage( $page, $this->context );
361 } else {
362 // This case should not happen, but just in case.
363 $article = Article::newFromTitle( $title, $this->context );
364 $this->context->setWikiPage( $article->getPage() );
365 }
366
367 // Skip some unnecessary code if the content model doesn't support redirects
368 if ( !ContentHandler::getForTitle( $title )->supportsRedirects() ) {
369 return $article;
370 }
371
372 $request = $this->context->getRequest();
373
374 // Namespace might change when using redirects
375 // Check for redirects ...
376 $action = $request->getVal( 'action', 'view' );
377 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
378 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
379 && !$request->getVal( 'oldid' ) // ... and are not old revisions
380 && !$request->getVal( 'diff' ) // ... and not when showing diff
381 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
382 // ... and the article is not a non-redirect image page with associated file
383 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
384 ) {
385 // Give extensions a change to ignore/handle redirects as needed
386 $ignoreRedirect = $target = false;
387
388 Hooks::run( 'InitializeArticleMaybeRedirect',
389 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
390
391 // Follow redirects only for... redirects.
392 // If $target is set, then a hook wanted to redirect.
393 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
394 // Is the target already set by an extension?
395 $target = $target ? $target : $article->followRedirect();
396 if ( is_string( $target ) ) {
397 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
398 // we'll need to redirect
399 return $target;
400 }
401 }
402 if ( is_object( $target ) ) {
403 // Rewrite environment to redirected article
404 $rarticle = Article::newFromTitle( $target, $this->context );
405 $rarticle->loadPageData();
406 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
407 $rarticle->setRedirectedFrom( $title );
408 $article = $rarticle;
409 $this->context->setTitle( $target );
410 $this->context->setWikiPage( $article->getPage() );
411 }
412 }
413 } else {
414 $this->context->setTitle( $article->getTitle() );
415 $this->context->setWikiPage( $article->getPage() );
416 }
417 }
418
419 return $article;
420 }
421
422 /**
423 * Perform one of the "standard" actions
424 *
425 * @param Page $page
426 * @param Title $requestTitle The original title, before any redirects were applied
427 */
428 private function performAction( Page $page, Title $requestTitle ) {
429
430 $request = $this->context->getRequest();
431 $output = $this->context->getOutput();
432 $title = $this->context->getTitle();
433 $user = $this->context->getUser();
434
435 if ( !Hooks::run( 'MediaWikiPerformAction',
436 array( $output, $page, $title, $user, $request, $this ) )
437 ) {
438 return;
439 }
440
441 $act = $this->getAction();
442
443 $action = Action::factory( $act, $page, $this->context );
444
445 if ( $action instanceof Action ) {
446 # Let CDN cache things if we can purge them.
447 if ( $this->config->get( 'UseSquid' ) &&
448 in_array(
449 // Use PROTO_INTERNAL because that's what getCdnUrls() uses
450 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
451 $requestTitle->getCdnUrls()
452 )
453 ) {
454 $output->setCdnMaxage( $this->config->get( 'SquidMaxage' ) );
455 }
456
457 $action->show();
458 return;
459 }
460
461 if ( Hooks::run( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
462 $output->setStatusCode( 404 );
463 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
464 }
465
466 }
467
468 /**
469 * Run the current MediaWiki instance; index.php just calls this
470 */
471 public function run() {
472 try {
473 try {
474 $this->main();
475 } catch ( ErrorPageError $e ) {
476 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
477 // they are not internal application faults. As with normal requests, this
478 // should commit, print the output, do deferred updates, jobs, and profiling.
479 $this->doPreOutputCommit();
480 $e->report(); // display the GUI error
481 }
482 } catch ( Exception $e ) {
483 MWExceptionHandler::handleException( $e );
484 }
485
486 $this->doPostOutputShutdown( 'normal' );
487 }
488
489 /**
490 * @see MediaWiki::preOutputCommit()
491 * @since 1.26
492 */
493 public function doPreOutputCommit() {
494 self::preOutputCommit( $this->context );
495 }
496
497 /**
498 * This function commits all DB changes as needed before
499 * the user can receive a response (in case commit fails)
500 *
501 * @param IContextSource $context
502 * @since 1.27
503 */
504 public static function preOutputCommit( IContextSource $context ) {
505 // Either all DBs should commit or none
506 ignore_user_abort( true );
507
508 $config = $context->getConfig();
509
510 $factory = wfGetLBFactory();
511 // Check if any transaction was too big
512 $limit = $config->get( 'MaxUserDBWriteDuration' );
513 $factory->forEachLB( function ( LoadBalancer $lb ) use ( $limit ) {
514 $lb->forEachOpenConnection( function ( IDatabase $db ) use ( $limit ) {
515 $time = $db->pendingWriteQueryDuration();
516 if ( $limit > 0 && $time > $limit ) {
517 throw new DBTransactionError(
518 $db,
519 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->plain()
520 );
521 }
522 } );
523 } );
524 // Commit all changes
525 $factory->commitMasterChanges();
526 // Record ChronologyProtector positions
527 $factory->shutdown();
528 wfDebug( __METHOD__ . ': all transactions committed' );
529
530 DeferredUpdates::doUpdates( 'enqueue', DeferredUpdates::PRESEND );
531 wfDebug( __METHOD__ . ': pre-send deferred updates completed' );
532
533 // Set a cookie to tell all CDN edge nodes to "stick" the user to the
534 // DC that handles this POST request (e.g. the "master" data center)
535 $request = $context->getRequest();
536 if ( $request->wasPosted() && $factory->hasOrMadeRecentMasterChanges() ) {
537 $expires = time() + $config->get( 'DataCenterUpdateStickTTL' );
538 $request->response()->setCookie( 'UseDC', 'master', $expires, array( 'prefix' => '' ) );
539 }
540
541 // Avoid letting a few seconds of slave lag cause a month of stale data
542 if ( $factory->laggedSlaveUsed() ) {
543 $maxAge = $config->get( 'CdnMaxageLagged' );
544 $context->getOutput()->lowerCdnMaxage( $maxAge );
545 $request->response()->header( "X-Database-Lagged: true" );
546 wfDebugLog( 'replication', "Lagged DB used; CDN cache TTL limited to $maxAge seconds" );
547 }
548 }
549
550 /**
551 * This function does work that can be done *after* the
552 * user gets the HTTP response so they don't block on it
553 *
554 * This manages deferred updates, job insertion,
555 * final commit, and the logging of profiling data
556 *
557 * @param string $mode Use 'fast' to always skip job running
558 * @since 1.26
559 */
560 public function doPostOutputShutdown( $mode = 'normal' ) {
561 $timing = $this->context->getTiming();
562 $timing->mark( 'requestShutdown' );
563
564 // Show visible profiling data if enabled (which cannot be post-send)
565 Profiler::instance()->logDataPageOutputOnly();
566
567 $that = $this;
568 $callback = function () use ( $that, $mode ) {
569 try {
570 $that->restInPeace( $mode );
571 } catch ( Exception $e ) {
572 MWExceptionHandler::handleException( $e );
573 }
574 };
575
576 // Defer everything else...
577 if ( function_exists( 'register_postsend_function' ) ) {
578 // https://github.com/facebook/hhvm/issues/1230
579 register_postsend_function( $callback );
580 } else {
581 if ( function_exists( 'fastcgi_finish_request' ) ) {
582 fastcgi_finish_request();
583 } else {
584 // Either all DB and deferred updates should happen or none.
585 // The later should not be cancelled due to client disconnect.
586 ignore_user_abort( true );
587 }
588
589 $callback();
590 }
591 }
592
593 private function main() {
594 global $wgTitle, $wgTrxProfilerLimits;
595
596 $request = $this->context->getRequest();
597
598 // Send Ajax requests to the Ajax dispatcher.
599 if ( $this->config->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
600 // Set a dummy title, because $wgTitle == null might break things
601 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
602 . __METHOD__
603 );
604 $this->context->setTitle( $title );
605 $wgTitle = $title;
606
607 $dispatcher = new AjaxDispatcher( $this->config );
608 $dispatcher->performAction( $this->context->getUser() );
609 return;
610 }
611
612 // Get title from request parameters,
613 // is set on the fly by parseTitle the first time.
614 $title = $this->getTitle();
615 $action = $this->getAction();
616 $wgTitle = $title;
617
618 $trxProfiler = Profiler::instance()->getTransactionProfiler();
619 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
620
621 // Aside from rollback, master queries should not happen on GET requests.
622 // Periodic or "in passing" updates on GET should use the job queue.
623 if ( !$request->wasPosted()
624 && in_array( $action, array( 'view', 'edit', 'history' ) )
625 ) {
626 $trxProfiler->setExpectations( $wgTrxProfilerLimits['GET'], __METHOD__ );
627 } else {
628 $trxProfiler->setExpectations( $wgTrxProfilerLimits['POST'], __METHOD__ );
629 }
630
631 // If the user has forceHTTPS set to true, or if the user
632 // is in a group requiring HTTPS, or if they have the HTTPS
633 // preference set, redirect them to HTTPS.
634 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
635 // isLoggedIn() will do all sorts of weird stuff.
636 if (
637 $request->getProtocol() == 'http' &&
638 (
639 $request->getCookie( 'forceHTTPS', '' ) ||
640 // check for prefixed version for currently logged in users
641 $request->getCookie( 'forceHTTPS' ) ||
642 // Avoid checking the user and groups unless it's enabled.
643 (
644 $this->context->getUser()->isLoggedIn()
645 && $this->context->getUser()->requiresHTTPS()
646 )
647 )
648 ) {
649 $oldUrl = $request->getFullRequestURL();
650 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
651
652 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
653 if ( Hooks::run( 'BeforeHttpsRedirect', array( $this->context, &$redirUrl ) ) ) {
654
655 if ( $request->wasPosted() ) {
656 // This is weird and we'd hope it almost never happens. This
657 // means that a POST came in via HTTP and policy requires us
658 // redirecting to HTTPS. It's likely such a request is going
659 // to fail due to post data being lost, but let's try anyway
660 // and just log the instance.
661
662 // @todo FIXME: See if we could issue a 307 or 308 here, need
663 // to see how clients (automated & browser) behave when we do
664 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
665 }
666 // Setup dummy Title, otherwise OutputPage::redirect will fail
667 $title = Title::newFromText( 'REDIR', NS_MAIN );
668 $this->context->setTitle( $title );
669 $output = $this->context->getOutput();
670 // Since we only do this redir to change proto, always send a vary header
671 $output->addVaryHeader( 'X-Forwarded-Proto' );
672 $output->redirect( $redirUrl );
673 $output->output();
674 return;
675 }
676 }
677
678 if ( $this->config->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
679 if ( HTMLFileCache::useFileCache( $this->context ) ) {
680 // Try low-level file cache hit
681 $cache = new HTMLFileCache( $title, $action );
682 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
683 // Check incoming headers to see if client has this cached
684 $timestamp = $cache->cacheTimestamp();
685 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
686 $cache->loadFromFileCache( $this->context );
687 }
688 // Do any stats increment/watchlist stuff
689 // Assume we're viewing the latest revision (this should always be the case with file cache)
690 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
691 // Tell OutputPage that output is taken care of
692 $this->context->getOutput()->disable();
693 return;
694 }
695 }
696 }
697
698 // Actually do the work of the request and build up any output
699 $this->performRequest();
700
701 // Now commit any transactions, so that unreported errors after
702 // output() don't roll back the whole DB transaction and so that
703 // we avoid having both success and error text in the response
704 $this->doPreOutputCommit();
705
706 // Output everything!
707 $this->context->getOutput()->output();
708 }
709
710 /**
711 * Ends this task peacefully
712 * @param string $mode Use 'fast' to always skip job running
713 */
714 public function restInPeace( $mode = 'fast' ) {
715 // Assure deferred updates are not in the main transaction
716 wfGetLBFactory()->commitMasterChanges();
717
718 // Ignore things like master queries/connections on GET requests
719 // as long as they are in deferred updates (which catch errors).
720 Profiler::instance()->getTransactionProfiler()->resetExpectations();
721
722 // Do any deferred jobs
723 DeferredUpdates::doUpdates( 'enqueue' );
724
725 // Make sure any lazy jobs are pushed
726 JobQueueGroup::pushLazyJobs();
727
728 // Now that everything specific to this request is done,
729 // try to occasionally run jobs (if enabled) from the queues
730 if ( $mode === 'normal' ) {
731 $this->triggerJobs();
732 }
733
734 // Log profiling data, e.g. in the database or UDP
735 wfLogProfilingData();
736
737 // Commit and close up!
738 $factory = wfGetLBFactory();
739 $factory->commitMasterChanges();
740 $factory->shutdown( LBFactory::SHUTDOWN_NO_CHRONPROT );
741
742 wfDebug( "Request ended normally\n" );
743 }
744
745 /**
746 * Potentially open a socket and sent an HTTP request back to the server
747 * to run a specified number of jobs. This registers a callback to cleanup
748 * the socket once it's done.
749 */
750 public function triggerJobs() {
751 $jobRunRate = $this->config->get( 'JobRunRate' );
752 if ( $jobRunRate <= 0 || wfReadOnly() ) {
753 return;
754 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
755 return; // recursion guard
756 }
757
758 if ( $jobRunRate < 1 ) {
759 $max = mt_getrandmax();
760 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
761 return; // the higher the job run rate, the less likely we return here
762 }
763 $n = 1;
764 } else {
765 $n = intval( $jobRunRate );
766 }
767
768 $runJobsLogger = LoggerFactory::getInstance( 'runJobs' );
769
770 if ( !$this->config->get( 'RunJobsAsync' ) ) {
771 // Fall back to running the job here while the user waits
772 $runner = new JobRunner( $runJobsLogger );
773 $runner->run( array( 'maxJobs' => $n ) );
774 return;
775 }
776
777 try {
778 if ( !JobQueueGroup::singleton()->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
779 return; // do not send request if there are probably no jobs
780 }
781 } catch ( JobQueueError $e ) {
782 MWExceptionHandler::logException( $e );
783 return; // do not make the site unavailable
784 }
785
786 $query = array( 'title' => 'Special:RunJobs',
787 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 );
788 $query['signature'] = SpecialRunJobs::getQuerySignature(
789 $query, $this->config->get( 'SecretKey' ) );
790
791 $errno = $errstr = null;
792 $info = wfParseUrl( $this->config->get( 'Server' ) );
793 MediaWiki\suppressWarnings();
794 $sock = fsockopen(
795 $info['host'],
796 isset( $info['port'] ) ? $info['port'] : 80,
797 $errno,
798 $errstr,
799 // If it takes more than 100ms to connect to ourselves there
800 // is a problem elsewhere.
801 0.1
802 );
803 MediaWiki\restoreWarnings();
804 if ( !$sock ) {
805 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
806 // Fall back to running the job here while the user waits
807 $runner = new JobRunner( $runJobsLogger );
808 $runner->run( array( 'maxJobs' => $n ) );
809 return;
810 }
811
812 $url = wfAppendQuery( wfScript( 'index' ), $query );
813 $req = (
814 "POST $url HTTP/1.1\r\n" .
815 "Host: {$info['host']}\r\n" .
816 "Connection: Close\r\n" .
817 "Content-Length: 0\r\n\r\n"
818 );
819
820 $runJobsLogger->info( "Running $n job(s) via '$url'" );
821 // Send a cron API request to be performed in the background.
822 // Give up if this takes too long to send (which should be rare).
823 stream_set_timeout( $sock, 1 );
824 $bytes = fwrite( $sock, $req );
825 if ( $bytes !== strlen( $req ) ) {
826 $runJobsLogger->error( "Failed to start cron API (socket write error)" );
827 } else {
828 // Do not wait for the response (the script should handle client aborts).
829 // Make sure that we don't close before that script reaches ignore_user_abort().
830 $status = fgets( $sock );
831 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
832 $runJobsLogger->error( "Failed to start cron API: received '$status'" );
833 }
834 }
835 fclose( $sock );
836 }
837 }