3 * Helper class for the index.php entry point.
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.
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.
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
23 use MediaWiki\Logger\LoggerFactory
;
26 * The MediaWiki class is the helper class for the index.php entry point.
40 * @param IContextSource|null $context
42 public function __construct( IContextSource
$context = null ) {
44 $context = RequestContext
::getMain();
47 $this->context
= $context;
48 $this->config
= $context->getConfig();
52 * Parse the request to get the Title object
54 * @throws MalformedTitleException If a title has been provided by the user, but is invalid.
55 * @return Title Title object to be $wgTitle
57 private function parseTitle() {
60 $request = $this->context
->getRequest();
61 $curid = $request->getInt( 'curid' );
62 $title = $request->getVal( 'title' );
63 $action = $request->getVal( 'action' );
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' );
71 // URLs like this are generated by RC, because rc_title isn't always accurate
72 $ret = Title
::newFromID( $curid );
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() );
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
85 $wgContLang->findVariantLink( $title, $ret );
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
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
99 $rev = Revision
::newFromId( $oldid );
100 $ret = $rev ?
$rev->getTitle() : $ret;
104 // Use the main page as default title if nothing else has been provided
106 && strval( $title ) === ''
107 && !$request->getCheck( 'curid' )
108 && $action !== 'delete'
110 $ret = Title
::newMainPage();
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 );
124 * Get the Title object that we'll be acting on, as specified in the WebRequest
127 public function getTitle() {
128 if ( !$this->context
->hasTitle() ) {
130 $this->context
->setTitle( $this->parseTitle() );
131 } catch ( MalformedTitleException
$ex ) {
132 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
135 return $this->context
->getTitle();
139 * Returns the name of the action that will be executed.
141 * @return string Action
143 public function getAction() {
144 static $action = null;
146 if ( $action === null ) {
147 $action = Action
::getActionName( $this->context
);
154 * Performs the request.
157 * - local interwiki redirects
162 * @throws MWException|PermissionsError|BadTitleError|HttpError
165 private function performRequest() {
168 $request = $this->context
->getRequest();
169 $requestTitle = $title = $this->context
->getTitle();
170 $output = $this->context
->getOutput();
171 $user = $this->context
->getUser();
173 if ( $request->getVal( 'printable' ) === 'yes' ) {
174 $output->setPrintable();
177 $unused = null; // To pass it by reference
178 Hooks
::run( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
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' )
184 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
187 } catch ( MalformedTitleException
$ex ) {
188 throw new BadTitleError( $ex );
190 throw new BadTitleError();
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.
207 // The skin mostly uses $this->context->getTitle() these days, but some extensions
208 // still use $wgTitle.
210 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
211 $this->context
->setTitle( $badTitle );
212 $wgTitle = $badTitle;
214 throw new PermissionsError( 'read', $permErrors );
217 // Interwiki redirects
218 if ( $title->isExternal() ) {
219 $rdfrom = $request->getVal( 'rdfrom' );
221 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
223 $query = $request->getValues();
224 unset( $query['title'] );
225 $url = $title->getFullURL( $query );
227 // Check for a redirect loop
228 if ( !preg_match( '/^' . preg_quote( $this->config
->get( 'Server' ), '/' ) . '/', $url )
231 // 301 so google et al report the target as the actual url.
232 $output->redirect( $url, 301 );
234 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
237 } catch ( MalformedTitleException
$ex ) {
238 throw new BadTitleError( $ex );
240 throw new BadTitleError();
242 // Handle any other redirects.
243 // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
244 } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
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
);
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 );
259 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
260 . " returned neither an object nor a URL" );
267 * Handle redirects for uncanonical title requests.
272 * - $wgUsePathInfo URLs.
273 * - URLs with a variant.
274 * - Other non-standard URLs (as long as they have no extra query parameters).
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'.
286 * @param Title $title
287 * @return bool True if a redirect was set.
290 private function tryNormaliseRedirect( Title
$title ) {
291 $request = $this->context
->getRequest();
292 $output = $this->context
->getOutput();
294 if ( $request->getVal( 'action', 'view' ) != 'view'
295 ||
$request->wasPosted()
296 ||
count( $request->getValueNames( array( 'action', 'title' ) ) )
297 ||
!Hooks
::run( 'TestCanonicalRedirect', array( $request, $title, $output ) )
302 if ( $title->isSpecialPage() ) {
303 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
305 $title = SpecialPage
::getTitleFor( $name, $subpage );
308 // Redirect to canonical url, make it a 301 to allow caching
309 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
311 if ( $targetUrl != $request->getFullRequestURL() ) {
312 $output->setSquidMaxage( 1200 );
313 $output->redirect( $targetUrl, '301' );
317 // If there is no title, or the title is in a non-standard encoding, we demand
318 // a redirect. If cgi somehow changed the 'title' query to be non-standard while
319 // the url is standard, the server is misconfigured.
320 if ( $request->getVal( 'title' ) === null
321 ||
$title->getPrefixedDBkey() != $request->getVal( 'title' )
323 $message = "Redirect loop detected!\n\n" .
324 "This means the wiki got confused about what page was " .
325 "requested; this sometimes happens when moving a wiki " .
326 "to a new server or changing the server configuration.\n\n";
328 if ( $this->config
->get( 'UsePathInfo' ) ) {
329 $message .= "The wiki is trying to interpret the page " .
330 "title from the URL path portion (PATH_INFO), which " .
331 "sometimes fails depending on the web server. Try " .
332 "setting \"\$wgUsePathInfo = false;\" in your " .
333 "LocalSettings.php, or check that \$wgArticlePath " .
336 $message .= "Your web server was detected as possibly not " .
337 "supporting URL path components (PATH_INFO) correctly; " .
338 "check your LocalSettings.php for a customized " .
339 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
342 throw new HttpError( 500, $message );
348 * Initialize the main Article object for "standard" actions (view, etc)
349 * Create an Article object for the page, following redirects if needed.
351 * @return mixed An Article, or a string to redirect to another URL
353 private function initializeArticle() {
355 $title = $this->context
->getTitle();
356 if ( $this->context
->canUseWikiPage() ) {
357 // Try to use request context wiki page, as there
358 // is already data from db saved in per process
359 // cache there from this->getAction() call.
360 $page = $this->context
->getWikiPage();
361 $article = Article
::newFromWikiPage( $page, $this->context
);
363 // This case should not happen, but just in case.
364 $article = Article
::newFromTitle( $title, $this->context
);
365 $this->context
->setWikiPage( $article->getPage() );
368 // Skip some unnecessary code if the content model doesn't support redirects
369 if ( !ContentHandler
::getForTitle( $title )->supportsRedirects() ) {
373 $request = $this->context
->getRequest();
375 // Namespace might change when using redirects
376 // Check for redirects ...
377 $action = $request->getVal( 'action', 'view' );
378 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
379 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
380 && !$request->getVal( 'oldid' ) // ... and are not old revisions
381 && !$request->getVal( 'diff' ) // ... and not when showing diff
382 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
383 // ... and the article is not a non-redirect image page with associated file
384 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
386 // Give extensions a change to ignore/handle redirects as needed
387 $ignoreRedirect = $target = false;
389 Hooks
::run( 'InitializeArticleMaybeRedirect',
390 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
392 // Follow redirects only for... redirects.
393 // If $target is set, then a hook wanted to redirect.
394 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
395 // Is the target already set by an extension?
396 $target = $target ?
$target : $article->followRedirect();
397 if ( is_string( $target ) ) {
398 if ( !$this->config
->get( 'DisableHardRedirects' ) ) {
399 // we'll need to redirect
403 if ( is_object( $target ) ) {
404 // Rewrite environment to redirected article
405 $rarticle = Article
::newFromTitle( $target, $this->context
);
406 $rarticle->loadPageData();
407 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
408 $rarticle->setRedirectedFrom( $title );
409 $article = $rarticle;
410 $this->context
->setTitle( $target );
411 $this->context
->setWikiPage( $article->getPage() );
415 $this->context
->setTitle( $article->getTitle() );
416 $this->context
->setWikiPage( $article->getPage() );
424 * Perform one of the "standard" actions
427 * @param Title $requestTitle The original title, before any redirects were applied
429 private function performAction( Page
$page, Title
$requestTitle ) {
431 $request = $this->context
->getRequest();
432 $output = $this->context
->getOutput();
433 $title = $this->context
->getTitle();
434 $user = $this->context
->getUser();
436 if ( !Hooks
::run( 'MediaWikiPerformAction',
437 array( $output, $page, $title, $user, $request, $this ) )
442 $act = $this->getAction();
444 $action = Action
::factory( $act, $page, $this->context
);
446 if ( $action instanceof Action
) {
447 # Let Squid cache things if we can purge them.
448 if ( $this->config
->get( 'UseSquid' ) &&
450 // Use PROTO_INTERNAL because that's what getSquidURLs() uses
451 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL
),
452 $requestTitle->getSquidURLs()
455 $output->setSquidMaxage( $this->config
->get( 'SquidMaxage' ) );
462 if ( Hooks
::run( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
463 $output->setStatusCode( 404 );
464 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
470 * Run the current MediaWiki instance; index.php just calls this
472 public function run() {
474 $this->checkMaxLag();
477 } catch ( ErrorPageError
$e ) {
478 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
479 // they are not internal application faults. As with normal requests, this
480 // should commit, print the output, do deferred updates, jobs, and profiling.
481 $this->doPreOutputCommit();
482 $e->report(); // display the GUI error
484 } catch ( Exception
$e ) {
485 MWExceptionHandler
::handleException( $e );
488 $this->doPostOutputShutdown( 'normal' );
492 * This function commits all DB changes as needed before
493 * the user can receive a response (in case commit fails)
497 public function doPreOutputCommit() {
498 // Either all DBs should commit or none
499 ignore_user_abort( true );
501 // Commit all changes and record ChronologyProtector positions
502 $factory = wfGetLBFactory();
503 $factory->commitMasterChanges();
504 $factory->shutdown();
506 wfDebug( __METHOD__
. ' completed; all transactions committed' );
508 // Set a cookie to tell all CDN edge nodes to "stick" the user to the
509 // DC that handles this POST request (e.g. the "master" data center)
510 $request = $this->context
->getRequest();
511 if ( $request->wasPosted() && $factory->hasOrMadeRecentMasterChanges() ) {
512 $expires = time() +
$this->config
->get( 'DataCenterUpdateStickTTL' );
513 $request->response()->setCookie( 'UseDC', 'master', $expires );
518 * This function does work that can be done *after* the
519 * user gets the HTTP response so they don't block on it
521 * This manages deferred updates, job insertion,
522 * final commit, and the logging of profiling data
524 * @param string $mode Use 'fast' to always skip job running
527 public function doPostOutputShutdown( $mode = 'normal' ) {
528 // Show visible profiling data if enabled (which cannot be post-send)
529 Profiler
::instance()->logDataPageOutputOnly();
532 $callback = function () use ( $that, $mode ) {
534 $that->restInPeace( $mode );
535 } catch ( Exception
$e ) {
536 MWExceptionHandler
::handleException( $e );
540 // Defer everything else...
541 if ( function_exists( 'register_postsend_function' ) ) {
542 // https://github.com/facebook/hhvm/issues/1230
543 register_postsend_function( $callback );
545 if ( function_exists( 'fastcgi_finish_request' ) ) {
546 fastcgi_finish_request();
548 // Either all DB and deferred updates should happen or none.
549 // The later should not be cancelled due to client disconnect.
550 ignore_user_abort( true );
558 * Checks if the request should abort due to a lagged server,
559 * for given maxlag parameter.
562 private function checkMaxLag() {
563 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
564 if ( !is_null( $maxLag ) ) {
565 list( $host, $lag ) = wfGetLB()->getMaxLag();
566 if ( $lag > $maxLag ) {
567 $resp = $this->context
->getRequest()->response();
568 $resp->statusHeader( 503 );
569 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
570 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
571 $resp->header( 'Content-Type: text/plain' );
572 if ( $this->config
->get( 'ShowHostnames' ) ) {
573 echo "Waiting for $host: $lag seconds lagged\n";
575 echo "Waiting for a database server: $lag seconds lagged\n";
584 private function main() {
585 global $wgTitle, $wgTrxProfilerLimits;
587 $request = $this->context
->getRequest();
589 // Send Ajax requests to the Ajax dispatcher.
590 if ( $this->config
->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
591 // Set a dummy title, because $wgTitle == null might break things
592 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/performing an AJAX call in '
595 $this->context
->setTitle( $title );
598 $dispatcher = new AjaxDispatcher( $this->config
);
599 $dispatcher->performAction( $this->context
->getUser() );
603 // Get title from request parameters,
604 // is set on the fly by parseTitle the first time.
605 $title = $this->getTitle();
606 $action = $this->getAction();
609 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
610 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
612 // Aside from rollback, master queries should not happen on GET requests.
613 // Periodic or "in passing" updates on GET should use the job queue.
614 if ( !$request->wasPosted()
615 && in_array( $action, array( 'view', 'edit', 'history' ) )
617 $trxProfiler->setExpectations( $wgTrxProfilerLimits['GET'], __METHOD__
);
619 $trxProfiler->setExpectations( $wgTrxProfilerLimits['POST'], __METHOD__
);
622 // If the user has forceHTTPS set to true, or if the user
623 // is in a group requiring HTTPS, or if they have the HTTPS
624 // preference set, redirect them to HTTPS.
625 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
626 // isLoggedIn() will do all sorts of weird stuff.
628 $request->getProtocol() == 'http' &&
630 $request->getCookie( 'forceHTTPS', '' ) ||
631 // check for prefixed version for currently logged in users
632 $request->getCookie( 'forceHTTPS' ) ||
633 // Avoid checking the user and groups unless it's enabled.
635 $this->context
->getUser()->isLoggedIn()
636 && $this->context
->getUser()->requiresHTTPS()
640 $oldUrl = $request->getFullRequestURL();
641 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
643 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
644 if ( Hooks
::run( 'BeforeHttpsRedirect', array( $this->context
, &$redirUrl ) ) ) {
646 if ( $request->wasPosted() ) {
647 // This is weird and we'd hope it almost never happens. This
648 // means that a POST came in via HTTP and policy requires us
649 // redirecting to HTTPS. It's likely such a request is going
650 // to fail due to post data being lost, but let's try anyway
651 // and just log the instance.
653 // @todo FIXME: See if we could issue a 307 or 308 here, need
654 // to see how clients (automated & browser) behave when we do
655 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
657 // Setup dummy Title, otherwise OutputPage::redirect will fail
658 $title = Title
::newFromText( 'REDIR', NS_MAIN
);
659 $this->context
->setTitle( $title );
660 $output = $this->context
->getOutput();
661 // Since we only do this redir to change proto, always send a vary header
662 $output->addVaryHeader( 'X-Forwarded-Proto' );
663 $output->redirect( $redirUrl );
669 if ( $this->config
->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
670 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
671 // Try low-level file cache hit
672 $cache = new HTMLFileCache( $title, $action );
673 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
674 // Check incoming headers to see if client has this cached
675 $timestamp = $cache->cacheTimestamp();
676 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
677 $cache->loadFromFileCache( $this->context
);
679 // Do any stats increment/watchlist stuff
680 // Assume we're viewing the latest revision (this should always be the case with file cache)
681 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
682 // Tell OutputPage that output is taken care of
683 $this->context
->getOutput()->disable();
689 // Actually do the work of the request and build up any output
690 $this->performRequest();
692 // Now commit any transactions, so that unreported errors after
693 // output() don't roll back the whole DB transaction and so that
694 // we avoid having both success and error text in the response
695 $this->doPreOutputCommit();
697 // Output everything!
698 $this->context
->getOutput()->output();
702 * Ends this task peacefully
703 * @param string $mode Use 'fast' to always skip job running
705 public function restInPeace( $mode = 'fast' ) {
706 // Assure deferred updates are not in the main transaction
707 wfGetLBFactory()->commitMasterChanges();
709 // Ignore things like master queries/connections on GET requests
710 // as long as they are in deferred updates (which catch errors).
711 Profiler
::instance()->getTransactionProfiler()->resetExpectations();
713 // Do any deferred jobs
714 DeferredUpdates
::doUpdates( 'commit' );
716 // Make sure any lazy jobs are pushed
717 JobQueueGroup
::pushLazyJobs();
719 // Now that everything specific to this request is done,
720 // try to occasionally run jobs (if enabled) from the queues
721 if ( $mode === 'normal' ) {
722 $this->triggerJobs();
725 // Log profiling data, e.g. in the database or UDP
726 wfLogProfilingData();
728 // Commit and close up!
729 $factory = wfGetLBFactory();
730 $factory->commitMasterChanges();
731 $factory->shutdown();
733 wfDebug( "Request ended normally\n" );
737 * Potentially open a socket and sent an HTTP request back to the server
738 * to run a specified number of jobs. This registers a callback to cleanup
739 * the socket once it's done.
741 public function triggerJobs() {
742 $jobRunRate = $this->config
->get( 'JobRunRate' );
743 if ( $jobRunRate <= 0 ||
wfReadOnly() ) {
745 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
746 return; // recursion guard
749 if ( $jobRunRate < 1 ) {
750 $max = mt_getrandmax();
751 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
752 return; // the higher the job run rate, the less likely we return here
756 $n = intval( $jobRunRate );
759 $runJobsLogger = LoggerFactory
::getInstance( 'runJobs' );
761 if ( !$this->config
->get( 'RunJobsAsync' ) ) {
762 // Fall back to running the job here while the user waits
763 $runner = new JobRunner( $runJobsLogger );
764 $runner->run( array( 'maxJobs' => $n ) );
769 if ( !JobQueueGroup
::singleton()->queuesHaveJobs( JobQueueGroup
::TYPE_DEFAULT
) ) {
770 return; // do not send request if there are probably no jobs
772 } catch ( JobQueueError
$e ) {
773 MWExceptionHandler
::logException( $e );
774 return; // do not make the site unavailable
777 $query = array( 'title' => 'Special:RunJobs',
778 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() +
5 );
779 $query['signature'] = SpecialRunJobs
::getQuerySignature(
780 $query, $this->config
->get( 'SecretKey' ) );
782 $errno = $errstr = null;
783 $info = wfParseUrl( $this->config
->get( 'Server' ) );
784 MediaWiki\
suppressWarnings();
787 isset( $info['port'] ) ?
$info['port'] : 80,
790 // If it takes more than 100ms to connect to ourselves there
791 // is a problem elsewhere.
794 MediaWiki\restoreWarnings
();
796 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
797 // Fall back to running the job here while the user waits
798 $runner = new JobRunner( $runJobsLogger );
799 $runner->run( array( 'maxJobs' => $n ) );
803 $url = wfAppendQuery( wfScript( 'index' ), $query );
805 "POST $url HTTP/1.1\r\n" .
806 "Host: {$info['host']}\r\n" .
807 "Connection: Close\r\n" .
808 "Content-Length: 0\r\n\r\n"
811 $runJobsLogger->info( "Running $n job(s) via '$url'" );
812 // Send a cron API request to be performed in the background.
813 // Give up if this takes too long to send (which should be rare).
814 stream_set_timeout( $sock, 1 );
815 $bytes = fwrite( $sock, $req );
816 if ( $bytes !== strlen( $req ) ) {
817 $runJobsLogger->error( "Failed to start cron API (socket write error)" );
819 // Do not wait for the response (the script should handle client aborts).
820 // Make sure that we don't close before that script reaches ignore_user_abort().
821 $status = fgets( $sock );
822 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
823 $runJobsLogger->error( "Failed to start cron API: received '$status'" );