Merge "objectcache: Document the primary entry points people should use"
[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
210 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
211 $this->context->setTitle( $badTitle );
212 $wgTitle = $badTitle;
213
214 throw new PermissionsError( 'read', $permErrors );
215 }
216
217 // Interwiki redirects
218 if ( $title->isExternal() ) {
219 $rdfrom = $request->getVal( 'rdfrom' );
220 if ( $rdfrom ) {
221 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
222 } else {
223 $query = $request->getValues();
224 unset( $query['title'] );
225 $url = $title->getFullURL( $query );
226 }
227 // Check for a redirect loop
228 if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
229 && $title->isLocal()
230 ) {
231 // 301 so google et al report the target as the actual url.
232 $output->redirect( $url, 301 );
233 } else {
234 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
235 try {
236 $this->parseTitle();
237 } catch ( MalformedTitleException $ex ) {
238 throw new BadTitleError( $ex );
239 }
240 throw new BadTitleError();
241 }
242 // Handle any other redirects.
243 // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
244 } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
245
246 // Special pages
247 if ( NS_SPECIAL == $title->getNamespace() ) {
248 // Actions that need to be made when we have a special pages
249 SpecialPageFactory::executePath( $title, $this->context );
250 } else {
251 // ...otherwise treat it as an article view. The article
252 // may still be a wikipage redirect to another article or URL.
253 $article = $this->initializeArticle();
254 if ( is_object( $article ) ) {
255 $this->performAction( $article, $requestTitle );
256 } elseif ( is_string( $article ) ) {
257 $output->redirect( $article );
258 } else {
259 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
260 . " returned neither an object nor a URL" );
261 }
262 }
263 }
264 }
265
266 /**
267 * Handle redirects for uncanonical title requests.
268 *
269 * Handles:
270 * - Redirect loops.
271 * - No title in URL.
272 * - $wgUsePathInfo URLs.
273 * - URLs with a variant.
274 * - Other non-standard URLs (as long as they have no extra query parameters).
275 *
276 * Behaviour:
277 * - Normalise title values:
278 * /wiki/Foo%20Bar -> /wiki/Foo_Bar
279 * - Normalise empty title:
280 * /wiki/ -> /wiki/Main
281 * /w/index.php?title= -> /wiki/Main
282 * - Normalise non-standard title urls:
283 * /w/index.php?title=Foo_Bar -> /wiki/Foo_Bar
284 * - Don't redirect anything with query parameters other than 'title' or 'action=view'.
285 *
286 * @return bool True if a redirect was set.
287 */
288 private function tryNormaliseRedirect( $title ) {
289 $request = $this->context->getRequest();
290 $output = $this->context->getOutput();
291
292 if ( $request->getVal( 'action', 'view' ) != 'view'
293 || $request->wasPosted()
294 || count( $request->getValueNames( array( 'action', 'title' ) ) )
295 || !Hooks::run( 'TestCanonicalRedirect', array( $request, $title, $output ) )
296 ) {
297 return false;
298 }
299
300 if ( $title->isSpecialPage() ) {
301 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
302 if ( $name ) {
303 $title = SpecialPage::getTitleFor( $name, $subpage );
304 }
305 }
306 // Redirect to canonical url, make it a 301 to allow caching
307 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
308
309 if ( $targetUrl != $request->getFullRequestURL() ) {
310 $output->setSquidMaxage( 1200 );
311 $output->redirect( $targetUrl, '301' );
312 return true;
313 }
314
315 // If there is no title, or the title is in a non-standard encoding, we demand
316 // a redirect. If cgi somehow changed the 'title' query to be non-standard while
317 // the url is standard, the server is misconfigured.
318 if ( $request->getVal( 'title' ) === null
319 || $title->getPrefixedDBkey() != $request->getVal( 'title' )
320 ) {
321 $message = "Redirect loop detected!\n\n" .
322 "This means the wiki got confused about what page was " .
323 "requested; this sometimes happens when moving a wiki " .
324 "to a new server or changing the server configuration.\n\n";
325
326 if ( $this->config->get( 'UsePathInfo' ) ) {
327 $message .= "The wiki is trying to interpret the page " .
328 "title from the URL path portion (PATH_INFO), which " .
329 "sometimes fails depending on the web server. Try " .
330 "setting \"\$wgUsePathInfo = false;\" in your " .
331 "LocalSettings.php, or check that \$wgArticlePath " .
332 "is correct.";
333 } else {
334 $message .= "Your web server was detected as possibly not " .
335 "supporting URL path components (PATH_INFO) correctly; " .
336 "check your LocalSettings.php for a customized " .
337 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
338 "to true.";
339 }
340 throw new HttpError( 500, $message );
341 }
342 return false;
343 }
344
345 /**
346 * Initialize the main Article object for "standard" actions (view, etc)
347 * Create an Article object for the page, following redirects if needed.
348 *
349 * @return mixed An Article, or a string to redirect to another URL
350 */
351 private function initializeArticle() {
352
353 $title = $this->context->getTitle();
354 if ( $this->context->canUseWikiPage() ) {
355 // Try to use request context wiki page, as there
356 // is already data from db saved in per process
357 // cache there from this->getAction() call.
358 $page = $this->context->getWikiPage();
359 $article = Article::newFromWikiPage( $page, $this->context );
360 } else {
361 // This case should not happen, but just in case.
362 $article = Article::newFromTitle( $title, $this->context );
363 $this->context->setWikiPage( $article->getPage() );
364 }
365
366 // Skip some unnecessary code if the content model doesn't support redirects
367 if ( !ContentHandler::getForTitle( $title )->supportsRedirects() ) {
368 return $article;
369 }
370
371 $request = $this->context->getRequest();
372
373 // Namespace might change when using redirects
374 // Check for redirects ...
375 $action = $request->getVal( 'action', 'view' );
376 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
377 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
378 && !$request->getVal( 'oldid' ) // ... and are not old revisions
379 && !$request->getVal( 'diff' ) // ... and not when showing diff
380 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
381 // ... and the article is not a non-redirect image page with associated file
382 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
383 ) {
384 // Give extensions a change to ignore/handle redirects as needed
385 $ignoreRedirect = $target = false;
386
387 Hooks::run( 'InitializeArticleMaybeRedirect',
388 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
389
390 // Follow redirects only for... redirects.
391 // If $target is set, then a hook wanted to redirect.
392 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
393 // Is the target already set by an extension?
394 $target = $target ? $target : $article->followRedirect();
395 if ( is_string( $target ) ) {
396 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
397 // we'll need to redirect
398 return $target;
399 }
400 }
401 if ( is_object( $target ) ) {
402 // Rewrite environment to redirected article
403 $rarticle = Article::newFromTitle( $target, $this->context );
404 $rarticle->loadPageData();
405 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
406 $rarticle->setRedirectedFrom( $title );
407 $article = $rarticle;
408 $this->context->setTitle( $target );
409 $this->context->setWikiPage( $article->getPage() );
410 }
411 }
412 } else {
413 $this->context->setTitle( $article->getTitle() );
414 $this->context->setWikiPage( $article->getPage() );
415 }
416 }
417
418 return $article;
419 }
420
421 /**
422 * Perform one of the "standard" actions
423 *
424 * @param Page $page
425 * @param Title $requestTitle The original title, before any redirects were applied
426 */
427 private function performAction( Page $page, Title $requestTitle ) {
428
429 $request = $this->context->getRequest();
430 $output = $this->context->getOutput();
431 $title = $this->context->getTitle();
432 $user = $this->context->getUser();
433
434 if ( !Hooks::run( 'MediaWikiPerformAction',
435 array( $output, $page, $title, $user, $request, $this ) )
436 ) {
437 return;
438 }
439
440 $act = $this->getAction();
441
442 $action = Action::factory( $act, $page, $this->context );
443
444 if ( $action instanceof Action ) {
445 # Let Squid cache things if we can purge them.
446 if ( $this->config->get( 'UseSquid' ) &&
447 in_array(
448 // Use PROTO_INTERNAL because that's what getSquidURLs() uses
449 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
450 $requestTitle->getSquidURLs()
451 )
452 ) {
453 $output->setSquidMaxage( $this->config->get( 'SquidMaxage' ) );
454 }
455
456 $action->show();
457 return;
458 }
459
460 if ( Hooks::run( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
461 $output->setStatusCode( 404 );
462 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
463 }
464
465 }
466
467 /**
468 * Run the current MediaWiki instance; index.php just calls this
469 */
470 public function run() {
471 try {
472 $this->checkMaxLag();
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 * This function commits all DB changes as needed before
491 * the user can receive a response (in case commit fails)
492 *
493 * @since 1.26
494 */
495 public function doPreOutputCommit() {
496 // Either all DBs should commit or none
497 ignore_user_abort( true );
498
499 // Commit all changes and record ChronologyProtector positions
500 $factory = wfGetLBFactory();
501 $factory->commitMasterChanges();
502 $factory->shutdown();
503
504 wfDebug( __METHOD__ . ' completed; all transactions committed' );
505 }
506
507 /**
508 * This function does work that can be done *after* the
509 * user gets the HTTP response so they don't block on it
510 *
511 * @param string $mode Use 'fast' to always skip job running
512 * @since 1.26
513 */
514 public function doPostOutputShutdown( $mode = 'normal' ) {
515 // Show profiling data if enabled
516 Profiler::instance()->logDataPageOutputOnly();
517
518 $that = $this;
519 $callback = function () use ( $that, $mode ) {
520 try {
521 // Assure deferred updates are not in the main transaction
522 wfGetLBFactory()->commitMasterChanges();
523 // Run jobs occasionally, if enabled
524 if ( $mode === 'normal' ) {
525 $that->triggerJobs();
526 }
527 // Do deferred updates and job insertion and final commit
528 $that->restInPeace();
529 } catch ( Exception $e ) {
530 MWExceptionHandler::handleException( $e );
531 }
532 };
533
534 if ( function_exists( 'register_postsend_function' ) ) {
535 // https://github.com/facebook/hhvm/issues/1230
536 register_postsend_function( $callback );
537 } else {
538 if ( function_exists( 'fastcgi_finish_request' ) ) {
539 fastcgi_finish_request();
540 } else {
541 // Either all DB and deferred updates should happen or none.
542 // The later should not be cancelled due to client disconnect.
543 ignore_user_abort( true );
544 }
545
546 $callback();
547 }
548 }
549
550 /**
551 * Checks if the request should abort due to a lagged server,
552 * for given maxlag parameter.
553 * @return bool
554 */
555 private function checkMaxLag() {
556 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
557 if ( !is_null( $maxLag ) ) {
558 list( $host, $lag ) = wfGetLB()->getMaxLag();
559 if ( $lag > $maxLag ) {
560 $resp = $this->context->getRequest()->response();
561 $resp->statusHeader( 503 );
562 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
563 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
564 $resp->header( 'Content-Type: text/plain' );
565 if ( $this->config->get( 'ShowHostnames' ) ) {
566 echo "Waiting for $host: $lag seconds lagged\n";
567 } else {
568 echo "Waiting for a database server: $lag seconds lagged\n";
569 }
570
571 exit;
572 }
573 }
574 return true;
575 }
576
577 private function main() {
578 global $wgTitle, $wgTrxProfilerLimits;
579
580 $request = $this->context->getRequest();
581
582 // Send Ajax requests to the Ajax dispatcher.
583 if ( $this->config->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
584 // Set a dummy title, because $wgTitle == null might break things
585 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
586 . __METHOD__
587 );
588 $this->context->setTitle( $title );
589 $wgTitle = $title;
590
591 $dispatcher = new AjaxDispatcher( $this->config );
592 $dispatcher->performAction( $this->context->getUser() );
593 return;
594 }
595
596 // Get title from request parameters,
597 // is set on the fly by parseTitle the first time.
598 $title = $this->getTitle();
599 $action = $this->getAction();
600 $wgTitle = $title;
601
602 $trxProfiler = Profiler::instance()->getTransactionProfiler();
603 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
604
605 // Aside from rollback, master queries should not happen on GET requests.
606 // Periodic or "in passing" updates on GET should use the job queue.
607 if ( !$request->wasPosted()
608 && in_array( $action, array( 'view', 'edit', 'history' ) )
609 ) {
610 $trxProfiler->setExpectations( $wgTrxProfilerLimits['GET'], __METHOD__ );
611 } else {
612 $trxProfiler->setExpectations( $wgTrxProfilerLimits['POST'], __METHOD__ );
613 }
614
615 // If the user has forceHTTPS set to true, or if the user
616 // is in a group requiring HTTPS, or if they have the HTTPS
617 // preference set, redirect them to HTTPS.
618 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
619 // isLoggedIn() will do all sorts of weird stuff.
620 if (
621 $request->getProtocol() == 'http' &&
622 (
623 $request->getCookie( 'forceHTTPS', '' ) ||
624 // check for prefixed version for currently logged in users
625 $request->getCookie( 'forceHTTPS' ) ||
626 // Avoid checking the user and groups unless it's enabled.
627 (
628 $this->context->getUser()->isLoggedIn()
629 && $this->context->getUser()->requiresHTTPS()
630 )
631 )
632 ) {
633 $oldUrl = $request->getFullRequestURL();
634 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
635
636 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
637 if ( Hooks::run( 'BeforeHttpsRedirect', array( $this->context, &$redirUrl ) ) ) {
638
639 if ( $request->wasPosted() ) {
640 // This is weird and we'd hope it almost never happens. This
641 // means that a POST came in via HTTP and policy requires us
642 // redirecting to HTTPS. It's likely such a request is going
643 // to fail due to post data being lost, but let's try anyway
644 // and just log the instance.
645 //
646 // @todo FIXME: See if we could issue a 307 or 308 here, need
647 // to see how clients (automated & browser) behave when we do
648 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
649 }
650 // Setup dummy Title, otherwise OutputPage::redirect will fail
651 $title = Title::newFromText( 'REDIR', NS_MAIN );
652 $this->context->setTitle( $title );
653 $output = $this->context->getOutput();
654 // Since we only do this redir to change proto, always send a vary header
655 $output->addVaryHeader( 'X-Forwarded-Proto' );
656 $output->redirect( $redirUrl );
657 $output->output();
658 return;
659 }
660 }
661
662 if ( $this->config->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
663 if ( HTMLFileCache::useFileCache( $this->context ) ) {
664 // Try low-level file cache hit
665 $cache = new HTMLFileCache( $title, $action );
666 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
667 // Check incoming headers to see if client has this cached
668 $timestamp = $cache->cacheTimestamp();
669 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
670 $cache->loadFromFileCache( $this->context );
671 }
672 // Do any stats increment/watchlist stuff
673 // Assume we're viewing the latest revision (this should always be the case with file cache)
674 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
675 // Tell OutputPage that output is taken care of
676 $this->context->getOutput()->disable();
677 return;
678 }
679 }
680 }
681
682 // Actually do the work of the request and build up any output
683 $this->performRequest();
684
685 // Now commit any transactions, so that unreported errors after
686 // output() don't roll back the whole DB transaction and so that
687 // we avoid having both success and error text in the response
688 $this->doPreOutputCommit();
689
690 // Output everything!
691 $this->context->getOutput()->output();
692 }
693
694 /**
695 * Ends this task peacefully
696 */
697 public function restInPeace() {
698 // Ignore things like master queries/connections on GET requests
699 // as long as they are in deferred updates (which catch errors).
700 Profiler::instance()->getTransactionProfiler()->resetExpectations();
701
702 // Do any deferred jobs
703 DeferredUpdates::doUpdates( 'commit' );
704
705 // Make sure any lazy jobs are pushed
706 JobQueueGroup::pushLazyJobs();
707
708 // Log profiling data, e.g. in the database or UDP
709 wfLogProfilingData();
710
711 // Commit and close up!
712 $factory = wfGetLBFactory();
713 $factory->commitMasterChanges();
714 $factory->shutdown();
715
716 wfDebug( "Request ended normally\n" );
717 }
718
719 /**
720 * Potentially open a socket and sent an HTTP request back to the server
721 * to run a specified number of jobs. This registers a callback to cleanup
722 * the socket once it's done.
723 */
724 public function triggerJobs() {
725 $jobRunRate = $this->config->get( 'JobRunRate' );
726 if ( $jobRunRate <= 0 || wfReadOnly() ) {
727 return;
728 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
729 return; // recursion guard
730 }
731
732 if ( $jobRunRate < 1 ) {
733 $max = mt_getrandmax();
734 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
735 return; // the higher the job run rate, the less likely we return here
736 }
737 $n = 1;
738 } else {
739 $n = intval( $jobRunRate );
740 }
741
742 $runJobsLogger = LoggerFactory::getInstance( 'runJobs' );
743
744 if ( !$this->config->get( 'RunJobsAsync' ) ) {
745 // Fall back to running the job here while the user waits
746 $runner = new JobRunner( $runJobsLogger );
747 $runner->run( array( 'maxJobs' => $n ) );
748 return;
749 }
750
751 try {
752 if ( !JobQueueGroup::singleton()->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
753 return; // do not send request if there are probably no jobs
754 }
755 } catch ( JobQueueError $e ) {
756 MWExceptionHandler::logException( $e );
757 return; // do not make the site unavailable
758 }
759
760 $query = array( 'title' => 'Special:RunJobs',
761 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 );
762 $query['signature'] = SpecialRunJobs::getQuerySignature(
763 $query, $this->config->get( 'SecretKey' ) );
764
765 $errno = $errstr = null;
766 $info = wfParseUrl( $this->config->get( 'Server' ) );
767 MediaWiki\suppressWarnings();
768 $sock = fsockopen(
769 $info['host'],
770 isset( $info['port'] ) ? $info['port'] : 80,
771 $errno,
772 $errstr,
773 // If it takes more than 100ms to connect to ourselves there
774 // is a problem elsewhere.
775 0.1
776 );
777 MediaWiki\restoreWarnings();
778 if ( !$sock ) {
779 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
780 // Fall back to running the job here while the user waits
781 $runner = new JobRunner( $runJobsLogger );
782 $runner->run( array( 'maxJobs' => $n ) );
783 return;
784 }
785
786 $url = wfAppendQuery( wfScript( 'index' ), $query );
787 $req = (
788 "POST $url HTTP/1.1\r\n" .
789 "Host: {$info['host']}\r\n" .
790 "Connection: Close\r\n" .
791 "Content-Length: 0\r\n\r\n"
792 );
793
794 $runJobsLogger->info( "Running $n job(s) via '$url'" );
795 // Send a cron API request to be performed in the background.
796 // Give up if this takes too long to send (which should be rare).
797 stream_set_timeout( $sock, 1 );
798 $bytes = fwrite( $sock, $req );
799 if ( $bytes !== strlen( $req ) ) {
800 $runJobsLogger->error( "Failed to start cron API (socket write error)" );
801 } else {
802 // Do not wait for the response (the script should handle client aborts).
803 // Make sure that we don't close before that script reaches ignore_user_abort().
804 $status = fgets( $sock );
805 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
806 $runJobsLogger->error( "Failed to start cron API: received '$status'" );
807 }
808 }
809 fclose( $sock );
810 }
811 }