Merge "Throw exception in importDump instead of dumping a random backtrace and erroring"
[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 /**
24 * The MediaWiki class is the helper class for the index.php entry point.
25 *
26 * @internal documentation reviewed 15 Mar 2010
27 */
28 class MediaWiki {
29 /**
30 * @todo Fold $output, etc, into this
31 * @var IContextSource
32 */
33 private $context;
34
35 /**
36 * @param null|WebRequest $x
37 * @return WebRequest
38 */
39 public function request( WebRequest $x = null ) {
40 $old = $this->context->getRequest();
41 if ( $x ) {
42 $this->context->setRequest( $x );
43 }
44 return $old;
45 }
46
47 /**
48 * @param null|OutputPage $x
49 * @return OutputPage
50 */
51 public function output( OutputPage $x = null ) {
52 $old = $this->context->getOutput();
53 if ( $x ) {
54 $this->context->setOutput( $x );
55 }
56 return $old;
57 }
58
59 /**
60 * @param IContextSource|null $context
61 */
62 public function __construct( IContextSource $context = null ) {
63 if ( !$context ) {
64 $context = RequestContext::getMain();
65 }
66
67 $this->context = $context;
68 }
69
70 /**
71 * Parse the request to get the Title object
72 *
73 * @return Title Title object to be $wgTitle
74 */
75 private function parseTitle() {
76 global $wgContLang;
77
78 $request = $this->context->getRequest();
79 $curid = $request->getInt( 'curid' );
80 $title = $request->getVal( 'title' );
81 $action = $request->getVal( 'action', 'view' );
82
83 if ( $request->getCheck( 'search' ) ) {
84 // Compatibility with old search URLs which didn't use Special:Search
85 // Just check for presence here, so blank requests still
86 // show the search page when using ugly URLs (bug 8054).
87 $ret = SpecialPage::getTitleFor( 'Search' );
88 } elseif ( $curid ) {
89 // URLs like this are generated by RC, because rc_title isn't always accurate
90 $ret = Title::newFromID( $curid );
91 } else {
92 $ret = Title::newFromURL( $title );
93 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
94 // in wikitext links to tell Parser to make a direct file link
95 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) {
96 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
97 }
98 // Check variant links so that interwiki links don't have to worry
99 // about the possible different language variants
100 if ( count( $wgContLang->getVariants() ) > 1
101 && !is_null( $ret ) && $ret->getArticleID() == 0
102 ) {
103 $wgContLang->findVariantLink( $title, $ret );
104 }
105 }
106
107 // If title is not provided, always allow oldid and diff to set the title.
108 // If title is provided, allow oldid and diff to override the title, unless
109 // we are talking about a special page which might use these parameters for
110 // other purposes.
111 if ( $ret === null || !$ret->isSpecialPage() ) {
112 // We can have urls with just ?diff=,?oldid= or even just ?diff=
113 $oldid = $request->getInt( 'oldid' );
114 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
115 // Allow oldid to override a changed or missing title
116 if ( $oldid ) {
117 $rev = Revision::newFromId( $oldid );
118 $ret = $rev ? $rev->getTitle() : $ret;
119 }
120 }
121
122 // Use the main page as default title if nothing else has been provided
123 if ( $ret === null
124 && strval( $title ) === ''
125 && !$request->getCheck( 'curid' )
126 && $action !== 'delete'
127 ) {
128 $ret = Title::newMainPage();
129 }
130
131 if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
132 $ret = SpecialPage::getTitleFor( 'Badtitle' );
133 }
134
135 return $ret;
136 }
137
138 /**
139 * Get the Title object that we'll be acting on, as specified in the WebRequest
140 * @return Title
141 */
142 public function getTitle() {
143 if ( $this->context->getTitle() === null ) {
144 $this->context->setTitle( $this->parseTitle() );
145 }
146 return $this->context->getTitle();
147 }
148
149 /**
150 * Returns the name of the action that will be executed.
151 *
152 * @return string Action
153 */
154 public function getAction() {
155 static $action = null;
156
157 if ( $action === null ) {
158 $action = Action::getActionName( $this->context );
159 }
160
161 return $action;
162 }
163
164 /**
165 * Performs the request.
166 * - bad titles
167 * - read restriction
168 * - local interwiki redirects
169 * - redirect loop
170 * - special pages
171 * - normal pages
172 *
173 * @throws MWException|PermissionsError|BadTitleError|HttpError
174 * @return void
175 */
176 private function performRequest() {
177 global $wgServer, $wgUsePathInfo, $wgTitle;
178
179 wfProfileIn( __METHOD__ );
180
181 $request = $this->context->getRequest();
182 $requestTitle = $title = $this->context->getTitle();
183 $output = $this->context->getOutput();
184 $user = $this->context->getUser();
185
186 if ( $request->getVal( 'printable' ) === 'yes' ) {
187 $output->setPrintable();
188 }
189
190 $unused = null; // To pass it by reference
191 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
192
193 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
194 if ( is_null( $title ) || ( $title->getDBkey() == '' && !$title->isExternal() )
195 || $title->isSpecial( 'Badtitle' )
196 ) {
197 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
198 wfProfileOut( __METHOD__ );
199 throw new BadTitleError();
200 }
201
202 // Check user's permissions to read this page.
203 // We have to check here to catch special pages etc.
204 // We will check again in Article::view().
205 $permErrors = $title->isSpecial( 'RunJobs' )
206 ? array() // relies on HMAC key signature alone
207 : $title->getUserPermissionsErrors( 'read', $user );
208 if ( count( $permErrors ) ) {
209 // Bug 32276: allowing the skin to generate output with $wgTitle or
210 // $this->context->title set to the input title would allow anonymous users to
211 // determine whether a page exists, potentially leaking private data. In fact, the
212 // curid and oldid request parameters would allow page titles to be enumerated even
213 // when they are not guessable. So we reset the title to Special:Badtitle before the
214 // permissions error is displayed.
215 //
216 // The skin mostly uses $this->context->getTitle() these days, but some extensions
217 // still use $wgTitle.
218
219 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
220 $this->context->setTitle( $badTitle );
221 $wgTitle = $badTitle;
222
223 wfProfileOut( __METHOD__ );
224 throw new PermissionsError( 'read', $permErrors );
225 }
226
227 $pageView = false; // was an article or special page viewed?
228
229 // Interwiki redirects
230 if ( $title->isExternal() ) {
231 $rdfrom = $request->getVal( 'rdfrom' );
232 if ( $rdfrom ) {
233 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
234 } else {
235 $query = $request->getValues();
236 unset( $query['title'] );
237 $url = $title->getFullURL( $query );
238 }
239 // Check for a redirect loop
240 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
241 && $title->isLocal()
242 ) {
243 // 301 so google et al report the target as the actual url.
244 $output->redirect( $url, 301 );
245 } else {
246 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
247 wfProfileOut( __METHOD__ );
248 throw new BadTitleError();
249 }
250 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
251 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
252 && ( $request->getVal( 'title' ) === null
253 || $title->getPrefixedDBkey() != $request->getVal( 'title' ) )
254 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
255 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) )
256 ) {
257 if ( $title->isSpecialPage() ) {
258 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
259 if ( $name ) {
260 $title = SpecialPage::getTitleFor( $name, $subpage );
261 }
262 }
263 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
264 // Redirect to canonical url, make it a 301 to allow caching
265 if ( $targetUrl == $request->getFullRequestURL() ) {
266 $message = "Redirect loop detected!\n\n" .
267 "This means the wiki got confused about what page was " .
268 "requested; this sometimes happens when moving a wiki " .
269 "to a new server or changing the server configuration.\n\n";
270
271 if ( $wgUsePathInfo ) {
272 $message .= "The wiki is trying to interpret the page " .
273 "title from the URL path portion (PATH_INFO), which " .
274 "sometimes fails depending on the web server. Try " .
275 "setting \"\$wgUsePathInfo = false;\" in your " .
276 "LocalSettings.php, or check that \$wgArticlePath " .
277 "is correct.";
278 } else {
279 $message .= "Your web server was detected as possibly not " .
280 "supporting URL path components (PATH_INFO) correctly; " .
281 "check your LocalSettings.php for a customized " .
282 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
283 "to true.";
284 }
285 throw new HttpError( 500, $message );
286 } else {
287 $output->setSquidMaxage( 1200 );
288 $output->redirect( $targetUrl, '301' );
289 }
290 // Special pages
291 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
292 $pageView = true;
293 // Actions that need to be made when we have a special pages
294 SpecialPageFactory::executePath( $title, $this->context );
295 } else {
296 // ...otherwise treat it as an article view. The article
297 // may be a redirect to another article or URL.
298 $article = $this->initializeArticle();
299 if ( is_object( $article ) ) {
300 $pageView = true;
301 $this->performAction( $article, $requestTitle );
302 } elseif ( is_string( $article ) ) {
303 $output->redirect( $article );
304 } else {
305 wfProfileOut( __METHOD__ );
306 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
307 . " returned neither an object nor a URL" );
308 }
309 }
310
311 if ( $pageView ) {
312 // Promote user to any groups they meet the criteria for
313 $user->addAutopromoteOnceGroups( 'onView' );
314 }
315
316 wfProfileOut( __METHOD__ );
317 }
318
319 /**
320 * Initialize the main Article object for "standard" actions (view, etc)
321 * Create an Article object for the page, following redirects if needed.
322 *
323 * @return mixed An Article, or a string to redirect to another URL
324 */
325 private function initializeArticle() {
326 global $wgDisableHardRedirects;
327
328 wfProfileIn( __METHOD__ );
329
330 $title = $this->context->getTitle();
331 if ( $this->context->canUseWikiPage() ) {
332 // Try to use request context wiki page, as there
333 // is already data from db saved in per process
334 // cache there from this->getAction() call.
335 $page = $this->context->getWikiPage();
336 $article = Article::newFromWikiPage( $page, $this->context );
337 } else {
338 // This case should not happen, but just in case.
339 $article = Article::newFromTitle( $title, $this->context );
340 $this->context->setWikiPage( $article->getPage() );
341 }
342
343 // NS_MEDIAWIKI has no redirects.
344 // It is also used for CSS/JS, so performance matters here...
345 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
346 wfProfileOut( __METHOD__ );
347 return $article;
348 }
349
350 $request = $this->context->getRequest();
351
352 // Namespace might change when using redirects
353 // Check for redirects ...
354 $action = $request->getVal( 'action', 'view' );
355 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
356 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
357 && !$request->getVal( 'oldid' ) // ... and are not old revisions
358 && !$request->getVal( 'diff' ) // ... and not when showing diff
359 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
360 // ... and the article is not a non-redirect image page with associated file
361 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
362 ) {
363 // Give extensions a change to ignore/handle redirects as needed
364 $ignoreRedirect = $target = false;
365
366 wfRunHooks( 'InitializeArticleMaybeRedirect',
367 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
368
369 // Follow redirects only for... redirects.
370 // If $target is set, then a hook wanted to redirect.
371 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
372 // Is the target already set by an extension?
373 $target = $target ? $target : $article->followRedirect();
374 if ( is_string( $target ) ) {
375 if ( !$wgDisableHardRedirects ) {
376 // we'll need to redirect
377 wfProfileOut( __METHOD__ );
378 return $target;
379 }
380 }
381 if ( is_object( $target ) ) {
382 // Rewrite environment to redirected article
383 $rarticle = Article::newFromTitle( $target, $this->context );
384 $rarticle->loadPageData();
385 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
386 $rarticle->setRedirectedFrom( $title );
387 $article = $rarticle;
388 $this->context->setTitle( $target );
389 $this->context->setWikiPage( $article->getPage() );
390 }
391 }
392 } else {
393 $this->context->setTitle( $article->getTitle() );
394 $this->context->setWikiPage( $article->getPage() );
395 }
396 }
397
398 wfProfileOut( __METHOD__ );
399 return $article;
400 }
401
402 /**
403 * Perform one of the "standard" actions
404 *
405 * @param Page $page
406 * @param Title $requestTitle The original title, before any redirects were applied
407 */
408 private function performAction( Page $page, Title $requestTitle ) {
409 global $wgUseSquid, $wgSquidMaxage;
410
411 wfProfileIn( __METHOD__ );
412
413 $request = $this->context->getRequest();
414 $output = $this->context->getOutput();
415 $title = $this->context->getTitle();
416 $user = $this->context->getUser();
417
418 if ( !wfRunHooks( 'MediaWikiPerformAction',
419 array( $output, $page, $title, $user, $request, $this ) )
420 ) {
421 wfProfileOut( __METHOD__ );
422 return;
423 }
424
425 $act = $this->getAction();
426
427 $action = Action::factory( $act, $page, $this->context );
428
429 if ( $action instanceof Action ) {
430 # Let Squid cache things if we can purge them.
431 if ( $wgUseSquid &&
432 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
433 ) {
434 $output->setSquidMaxage( $wgSquidMaxage );
435 }
436
437 $action->show();
438 wfProfileOut( __METHOD__ );
439 return;
440 }
441
442 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
443 $output->setStatusCode( 404 );
444 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
445 }
446
447 wfProfileOut( __METHOD__ );
448 }
449
450 /**
451 * Run the current MediaWiki instance
452 * index.php just calls this
453 */
454 public function run() {
455 try {
456 $this->checkMaxLag();
457 try {
458 $this->main();
459 } catch ( ErrorPageError $e ) {
460 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
461 // they are not internal application faults. As with normal requests, this
462 // should commit, print the output, do deferred updates, jobs, and profiling.
463 wfGetLBFactory()->commitMasterChanges();
464 $e->report(); // display the GUI error
465 }
466 if ( function_exists( 'fastcgi_finish_request' ) ) {
467 fastcgi_finish_request();
468 }
469 $this->triggerJobs();
470 $this->restInPeace();
471 } catch ( Exception $e ) {
472 MWExceptionHandler::handle( $e );
473 }
474 }
475
476 /**
477 * Checks if the request should abort due to a lagged server,
478 * for given maxlag parameter.
479 * @return bool
480 */
481 private function checkMaxLag() {
482 global $wgShowHostnames;
483
484 wfProfileIn( __METHOD__ );
485 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
486 if ( !is_null( $maxLag ) ) {
487 list( $host, $lag ) = wfGetLB()->getMaxLag();
488 if ( $lag > $maxLag ) {
489 $resp = $this->context->getRequest()->response();
490 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
491 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
492 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
493 $resp->header( 'Content-Type: text/plain' );
494 if ( $wgShowHostnames ) {
495 echo "Waiting for $host: $lag seconds lagged\n";
496 } else {
497 echo "Waiting for a database server: $lag seconds lagged\n";
498 }
499
500 wfProfileOut( __METHOD__ );
501
502 exit;
503 }
504 }
505 wfProfileOut( __METHOD__ );
506 return true;
507 }
508
509 private function main() {
510 global $wgUseFileCache, $wgTitle, $wgUseAjax;
511
512 wfProfileIn( __METHOD__ );
513
514 $request = $this->context->getRequest();
515
516 // Send Ajax requests to the Ajax dispatcher.
517 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
518
519 // Set a dummy title, because $wgTitle == null might break things
520 $title = Title::makeTitle( NS_MAIN, 'AJAX' );
521 $this->context->setTitle( $title );
522 $wgTitle = $title;
523
524 $dispatcher = new AjaxDispatcher();
525 $dispatcher->performAction();
526 wfProfileOut( __METHOD__ );
527 return;
528 }
529
530 // Get title from request parameters,
531 // is set on the fly by parseTitle the first time.
532 $title = $this->getTitle();
533 $action = $this->getAction();
534 $wgTitle = $title;
535
536 // If the user has forceHTTPS set to true, or if the user
537 // is in a group requiring HTTPS, or if they have the HTTPS
538 // preference set, redirect them to HTTPS.
539 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
540 // isLoggedIn() will do all sorts of weird stuff.
541 if (
542 $request->getProtocol() == 'http' &&
543 (
544 $request->getCookie( 'forceHTTPS', '' ) ||
545 // check for prefixed version for currently logged in users
546 $request->getCookie( 'forceHTTPS' ) ||
547 // Avoid checking the user and groups unless it's enabled.
548 (
549 $this->context->getUser()->isLoggedIn()
550 && $this->context->getUser()->requiresHTTPS()
551 )
552 )
553 ) {
554 $oldUrl = $request->getFullRequestURL();
555 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
556
557 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
558 if ( wfRunHooks( 'BeforeHttpsRedirect', array( $this->context, &$redirUrl ) ) ) {
559
560 if ( $request->wasPosted() ) {
561 // This is weird and we'd hope it almost never happens. This
562 // means that a POST came in via HTTP and policy requires us
563 // redirecting to HTTPS. It's likely such a request is going
564 // to fail due to post data being lost, but let's try anyway
565 // and just log the instance.
566 //
567 // @todo FIXME: See if we could issue a 307 or 308 here, need
568 // to see how clients (automated & browser) behave when we do
569 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
570 }
571 // Setup dummy Title, otherwise OutputPage::redirect will fail
572 $title = Title::newFromText( NS_MAIN, 'REDIR' );
573 $this->context->setTitle( $title );
574 $output = $this->context->getOutput();
575 // Since we only do this redir to change proto, always send a vary header
576 $output->addVaryHeader( 'X-Forwarded-Proto' );
577 $output->redirect( $redirUrl );
578 $output->output();
579 wfProfileOut( __METHOD__ );
580 return;
581 }
582 }
583
584 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
585 wfProfileIn( 'main-try-filecache' );
586 if ( HTMLFileCache::useFileCache( $this->context ) ) {
587 // Try low-level file cache hit
588 $cache = HTMLFileCache::newFromTitle( $title, $action );
589 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
590 // Check incoming headers to see if client has this cached
591 $timestamp = $cache->cacheTimestamp();
592 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
593 $cache->loadFromFileCache( $this->context );
594 }
595 // Do any stats increment/watchlist stuff
596 // Assume we're viewing the latest revision (this should always be the case with file cache)
597 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
598 // Tell OutputPage that output is taken care of
599 $this->context->getOutput()->disable();
600 wfProfileOut( 'main-try-filecache' );
601 wfProfileOut( __METHOD__ );
602 return;
603 }
604 }
605 wfProfileOut( 'main-try-filecache' );
606 }
607
608 // Actually do the work of the request and build up any output
609 $this->performRequest();
610
611 // Either all DB and deferred updates should happen or none.
612 // The later should not be cancelled due to client disconnect.
613 ignore_user_abort( true );
614 // Now commit any transactions, so that unreported errors after
615 // output() don't roll back the whole DB transaction
616 wfGetLBFactory()->commitMasterChanges();
617
618 // Output everything!
619 $this->context->getOutput()->output();
620
621 wfProfileOut( __METHOD__ );
622 }
623
624 /**
625 * Ends this task peacefully
626 */
627 public function restInPeace() {
628 // Do any deferred jobs
629 DeferredUpdates::doUpdates( 'commit' );
630
631 // Log profiling data, e.g. in the database or UDP
632 wfLogProfilingData();
633
634 // Commit and close up!
635 $factory = wfGetLBFactory();
636 $factory->commitMasterChanges();
637 $factory->shutdown();
638
639 wfDebug( "Request ended normally\n" );
640 }
641
642 /**
643 * Potentially open a socket and sent an HTTP request back to the server
644 * to run a specified number of jobs. This registers a callback to cleanup
645 * the socket once it's done.
646 */
647 protected function triggerJobs() {
648 global $wgJobRunRate, $wgServer, $wgRunJobsAsync;
649
650 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
651 return;
652 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
653 return; // recursion guard
654 }
655
656 $section = new ProfileSection( __METHOD__ );
657
658 if ( $wgJobRunRate < 1 ) {
659 $max = mt_getrandmax();
660 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
661 return; // the higher $wgJobRunRate, the less likely we return here
662 }
663 $n = 1;
664 } else {
665 $n = intval( $wgJobRunRate );
666 }
667
668 if ( !$wgRunJobsAsync ) {
669 // Fall back to running the job here while the user waits
670 $runner = new JobRunner();
671 $runner->run( array( 'maxJobs' => $n ) );
672 return;
673 }
674
675 try {
676 if ( !JobQueueGroup::singleton()->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
677 return; // do not send request if there are probably no jobs
678 }
679 } catch ( JobQueueError $e ) {
680 MWExceptionHandler::logException( $e );
681 return; // do not make the site unavailable
682 }
683
684 $query = array( 'title' => 'Special:RunJobs',
685 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 );
686 $query['signature'] = SpecialRunJobs::getQuerySignature( $query );
687
688 $errno = $errstr = null;
689 $info = wfParseUrl( $wgServer );
690 wfSuppressWarnings();
691 $sock = fsockopen(
692 $info['host'],
693 isset( $info['port'] ) ? $info['port'] : 80,
694 $errno,
695 $errstr,
696 // If it takes more than 100ms to connect to ourselves there
697 // is a problem elsewhere.
698 0.1
699 );
700 wfRestoreWarnings();
701 if ( !$sock ) {
702 wfDebugLog( 'runJobs', "Failed to start cron API (socket error $errno): $errstr\n" );
703 // Fall back to running the job here while the user waits
704 $runner = new JobRunner();
705 $runner->run( array( 'maxJobs' => $n ) );
706 return;
707 }
708
709 $url = wfAppendQuery( wfScript( 'index' ), $query );
710 $req = "POST $url HTTP/1.1\r\nHost: {$info['host']}\r\nConnection: Close\r\n\r\n";
711
712 wfDebugLog( 'runJobs', "Running $n job(s) via '$url'\n" );
713 // Send a cron API request to be performed in the background.
714 // Give up if this takes too long to send (which should be rare).
715 stream_set_timeout( $sock, 1 );
716 $bytes = fwrite( $sock, $req );
717 if ( $bytes !== strlen( $req ) ) {
718 wfDebugLog( 'runJobs', "Failed to start cron API (socket write error)\n" );
719 } else {
720 // Do not wait for the response (the script should handle client aborts).
721 // Make sure that we don't close before that script reaches ignore_user_abort().
722 $status = fgets( $sock );
723 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
724 wfDebugLog( 'runJobs', "Failed to start cron API: received '$status'\n" );
725 }
726 }
727 fclose( $sock );
728 }
729 }