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