Merge "API: Remove action=paraminfo 'props' and 'errors' result properties"
[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 * @var Config
37 */
38 private $config;
39
40 /**
41 * @param null|WebRequest $x
42 * @return WebRequest
43 */
44 public function request( WebRequest $x = null ) {
45 $old = $this->context->getRequest();
46 if ( $x ) {
47 $this->context->setRequest( $x );
48 }
49 return $old;
50 }
51
52 /**
53 * @param null|OutputPage $x
54 * @return OutputPage
55 */
56 public function output( OutputPage $x = null ) {
57 $old = $this->context->getOutput();
58 if ( $x ) {
59 $this->context->setOutput( $x );
60 }
61 return $old;
62 }
63
64 /**
65 * @param IContextSource|null $context
66 */
67 public function __construct( IContextSource $context = null ) {
68 if ( !$context ) {
69 $context = RequestContext::getMain();
70 }
71
72 $this->context = $context;
73 $this->config = $context->getConfig();
74 }
75
76 /**
77 * Parse the request to get the Title object
78 *
79 * @return Title Title object to be $wgTitle
80 */
81 private function parseTitle() {
82 global $wgContLang;
83
84 $request = $this->context->getRequest();
85 $curid = $request->getInt( 'curid' );
86 $title = $request->getVal( 'title' );
87 $action = $request->getVal( 'action', 'view' );
88
89 if ( $request->getCheck( 'search' ) ) {
90 // Compatibility with old search URLs which didn't use Special:Search
91 // Just check for presence here, so blank requests still
92 // show the search page when using ugly URLs (bug 8054).
93 $ret = SpecialPage::getTitleFor( 'Search' );
94 } elseif ( $curid ) {
95 // URLs like this are generated by RC, because rc_title isn't always accurate
96 $ret = Title::newFromID( $curid );
97 } else {
98 $ret = Title::newFromURL( $title );
99 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
100 // in wikitext links to tell Parser to make a direct file link
101 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) {
102 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
103 }
104 // Check variant links so that interwiki links don't have to worry
105 // about the possible different language variants
106 if ( count( $wgContLang->getVariants() ) > 1
107 && !is_null( $ret ) && $ret->getArticleID() == 0
108 ) {
109 $wgContLang->findVariantLink( $title, $ret );
110 }
111 }
112
113 // If title is not provided, always allow oldid and diff to set the title.
114 // If title is provided, allow oldid and diff to override the title, unless
115 // we are talking about a special page which might use these parameters for
116 // other purposes.
117 if ( $ret === null || !$ret->isSpecialPage() ) {
118 // We can have urls with just ?diff=,?oldid= or even just ?diff=
119 $oldid = $request->getInt( 'oldid' );
120 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
121 // Allow oldid to override a changed or missing title
122 if ( $oldid ) {
123 $rev = Revision::newFromId( $oldid );
124 $ret = $rev ? $rev->getTitle() : $ret;
125 }
126 }
127
128 // Use the main page as default title if nothing else has been provided
129 if ( $ret === null
130 && strval( $title ) === ''
131 && !$request->getCheck( 'curid' )
132 && $action !== 'delete'
133 ) {
134 $ret = Title::newMainPage();
135 }
136
137 if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
138 $ret = SpecialPage::getTitleFor( 'Badtitle' );
139 }
140
141 return $ret;
142 }
143
144 /**
145 * Get the Title object that we'll be acting on, as specified in the WebRequest
146 * @return Title
147 */
148 public function getTitle() {
149 if ( $this->context->getTitle() === null ) {
150 $this->context->setTitle( $this->parseTitle() );
151 }
152 return $this->context->getTitle();
153 }
154
155 /**
156 * Returns the name of the action that will be executed.
157 *
158 * @return string Action
159 */
160 public function getAction() {
161 static $action = null;
162
163 if ( $action === null ) {
164 $action = Action::getActionName( $this->context );
165 }
166
167 return $action;
168 }
169
170 /**
171 * Performs the request.
172 * - bad titles
173 * - read restriction
174 * - local interwiki redirects
175 * - redirect loop
176 * - special pages
177 * - normal pages
178 *
179 * @throws MWException|PermissionsError|BadTitleError|HttpError
180 * @return void
181 */
182 private function performRequest() {
183 global $wgTitle;
184
185 wfProfileIn( __METHOD__ );
186
187 $request = $this->context->getRequest();
188 $requestTitle = $title = $this->context->getTitle();
189 $output = $this->context->getOutput();
190 $user = $this->context->getUser();
191
192 if ( $request->getVal( 'printable' ) === 'yes' ) {
193 $output->setPrintable();
194 }
195
196 $unused = null; // To pass it by reference
197 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
198
199 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
200 if ( is_null( $title ) || ( $title->getDBkey() == '' && !$title->isExternal() )
201 || $title->isSpecial( 'Badtitle' )
202 ) {
203 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
204 wfProfileOut( __METHOD__ );
205 throw new BadTitleError();
206 }
207
208 // Check user's permissions to read this page.
209 // We have to check here to catch special pages etc.
210 // We will check again in Article::view().
211 $permErrors = $title->isSpecial( 'RunJobs' )
212 ? array() // relies on HMAC key signature alone
213 : $title->getUserPermissionsErrors( 'read', $user );
214 if ( count( $permErrors ) ) {
215 // Bug 32276: allowing the skin to generate output with $wgTitle or
216 // $this->context->title set to the input title would allow anonymous users to
217 // determine whether a page exists, potentially leaking private data. In fact, the
218 // curid and oldid request parameters would allow page titles to be enumerated even
219 // when they are not guessable. So we reset the title to Special:Badtitle before the
220 // permissions error is displayed.
221 //
222 // The skin mostly uses $this->context->getTitle() these days, but some extensions
223 // still use $wgTitle.
224
225 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
226 $this->context->setTitle( $badTitle );
227 $wgTitle = $badTitle;
228
229 wfProfileOut( __METHOD__ );
230 throw new PermissionsError( 'read', $permErrors );
231 }
232
233 $pageView = false; // was an article or special page viewed?
234
235 // Interwiki redirects
236 if ( $title->isExternal() ) {
237 $rdfrom = $request->getVal( 'rdfrom' );
238 if ( $rdfrom ) {
239 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
240 } else {
241 $query = $request->getValues();
242 unset( $query['title'] );
243 $url = $title->getFullURL( $query );
244 }
245 // Check for a redirect loop
246 if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
247 && $title->isLocal()
248 ) {
249 // 301 so google et al report the target as the actual url.
250 $output->redirect( $url, 301 );
251 } else {
252 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
253 wfProfileOut( __METHOD__ );
254 throw new BadTitleError();
255 }
256 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
257 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
258 && ( $request->getVal( 'title' ) === null
259 || $title->getPrefixedDBkey() != $request->getVal( 'title' ) )
260 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
261 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) )
262 ) {
263 if ( $title->isSpecialPage() ) {
264 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
265 if ( $name ) {
266 $title = SpecialPage::getTitleFor( $name, $subpage );
267 }
268 }
269 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
270 // Redirect to canonical url, make it a 301 to allow caching
271 if ( $targetUrl == $request->getFullRequestURL() ) {
272 $message = "Redirect loop detected!\n\n" .
273 "This means the wiki got confused about what page was " .
274 "requested; this sometimes happens when moving a wiki " .
275 "to a new server or changing the server configuration.\n\n";
276
277 if ( $this->config->get( 'UsePathInfo' ) ) {
278 $message .= "The wiki is trying to interpret the page " .
279 "title from the URL path portion (PATH_INFO), which " .
280 "sometimes fails depending on the web server. Try " .
281 "setting \"\$wgUsePathInfo = false;\" in your " .
282 "LocalSettings.php, or check that \$wgArticlePath " .
283 "is correct.";
284 } else {
285 $message .= "Your web server was detected as possibly not " .
286 "supporting URL path components (PATH_INFO) correctly; " .
287 "check your LocalSettings.php for a customized " .
288 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
289 "to true.";
290 }
291 throw new HttpError( 500, $message );
292 } else {
293 $output->setSquidMaxage( 1200 );
294 $output->redirect( $targetUrl, '301' );
295 }
296 // Special pages
297 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
298 $pageView = true;
299 // Actions that need to be made when we have a special pages
300 SpecialPageFactory::executePath( $title, $this->context );
301 } else {
302 // ...otherwise treat it as an article view. The article
303 // may be a redirect to another article or URL.
304 $article = $this->initializeArticle();
305 if ( is_object( $article ) ) {
306 $pageView = true;
307 $this->performAction( $article, $requestTitle );
308 } elseif ( is_string( $article ) ) {
309 $output->redirect( $article );
310 } else {
311 wfProfileOut( __METHOD__ );
312 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
313 . " returned neither an object nor a URL" );
314 }
315 }
316
317 if ( $pageView ) {
318 // Promote user to any groups they meet the criteria for
319 $user->addAutopromoteOnceGroups( 'onView' );
320 }
321
322 wfProfileOut( __METHOD__ );
323 }
324
325 /**
326 * Initialize the main Article object for "standard" actions (view, etc)
327 * Create an Article object for the page, following redirects if needed.
328 *
329 * @return mixed An Article, or a string to redirect to another URL
330 */
331 private function initializeArticle() {
332 wfProfileIn( __METHOD__ );
333
334 $title = $this->context->getTitle();
335 if ( $this->context->canUseWikiPage() ) {
336 // Try to use request context wiki page, as there
337 // is already data from db saved in per process
338 // cache there from this->getAction() call.
339 $page = $this->context->getWikiPage();
340 $article = Article::newFromWikiPage( $page, $this->context );
341 } else {
342 // This case should not happen, but just in case.
343 $article = Article::newFromTitle( $title, $this->context );
344 $this->context->setWikiPage( $article->getPage() );
345 }
346
347 // NS_MEDIAWIKI has no redirects.
348 // It is also used for CSS/JS, so performance matters here...
349 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
350 wfProfileOut( __METHOD__ );
351 return $article;
352 }
353
354 $request = $this->context->getRequest();
355
356 // Namespace might change when using redirects
357 // Check for redirects ...
358 $action = $request->getVal( 'action', 'view' );
359 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
360 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
361 && !$request->getVal( 'oldid' ) // ... and are not old revisions
362 && !$request->getVal( 'diff' ) // ... and not when showing diff
363 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
364 // ... and the article is not a non-redirect image page with associated file
365 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
366 ) {
367 // Give extensions a change to ignore/handle redirects as needed
368 $ignoreRedirect = $target = false;
369
370 wfRunHooks( 'InitializeArticleMaybeRedirect',
371 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
372
373 // Follow redirects only for... redirects.
374 // If $target is set, then a hook wanted to redirect.
375 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
376 // Is the target already set by an extension?
377 $target = $target ? $target : $article->followRedirect();
378 if ( is_string( $target ) ) {
379 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
380 // we'll need to redirect
381 wfProfileOut( __METHOD__ );
382 return $target;
383 }
384 }
385 if ( is_object( $target ) ) {
386 // Rewrite environment to redirected article
387 $rarticle = Article::newFromTitle( $target, $this->context );
388 $rarticle->loadPageData();
389 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
390 $rarticle->setRedirectedFrom( $title );
391 $article = $rarticle;
392 $this->context->setTitle( $target );
393 $this->context->setWikiPage( $article->getPage() );
394 }
395 }
396 } else {
397 $this->context->setTitle( $article->getTitle() );
398 $this->context->setWikiPage( $article->getPage() );
399 }
400 }
401
402 wfProfileOut( __METHOD__ );
403 return $article;
404 }
405
406 /**
407 * Perform one of the "standard" actions
408 *
409 * @param Page $page
410 * @param Title $requestTitle The original title, before any redirects were applied
411 */
412 private function performAction( Page $page, Title $requestTitle ) {
413 wfProfileIn( __METHOD__ );
414
415 $request = $this->context->getRequest();
416 $output = $this->context->getOutput();
417 $title = $this->context->getTitle();
418 $user = $this->context->getUser();
419
420 if ( !wfRunHooks( 'MediaWikiPerformAction',
421 array( $output, $page, $title, $user, $request, $this ) )
422 ) {
423 wfProfileOut( __METHOD__ );
424 return;
425 }
426
427 $act = $this->getAction();
428
429 $action = Action::factory( $act, $page, $this->context );
430
431 if ( $action instanceof Action ) {
432 # Let Squid cache things if we can purge them.
433 if ( $this->config->get( 'UseSquid' ) &&
434 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
435 ) {
436 $output->setSquidMaxage( $this->config->get( 'SquidMaxage' ) );
437 }
438
439 $action->show();
440 wfProfileOut( __METHOD__ );
441 return;
442 }
443
444 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
445 $output->setStatusCode( 404 );
446 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
447 }
448
449 wfProfileOut( __METHOD__ );
450 }
451
452 /**
453 * Run the current MediaWiki instance
454 * index.php just calls this
455 */
456 public function run() {
457 try {
458 $this->checkMaxLag();
459 try {
460 $this->main();
461 } catch ( ErrorPageError $e ) {
462 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
463 // they are not internal application faults. As with normal requests, this
464 // should commit, print the output, do deferred updates, jobs, and profiling.
465 wfGetLBFactory()->commitMasterChanges();
466 $e->report(); // display the GUI error
467 }
468 if ( function_exists( 'fastcgi_finish_request' ) ) {
469 fastcgi_finish_request();
470 }
471 $this->triggerJobs();
472 $this->restInPeace();
473 } catch ( Exception $e ) {
474 MWExceptionHandler::handle( $e );
475 }
476 }
477
478 /**
479 * Checks if the request should abort due to a lagged server,
480 * for given maxlag parameter.
481 * @return bool
482 */
483 private function checkMaxLag() {
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 ( $this->config->get( 'ShowHostnames' ) ) {
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 $wgTitle;
511
512 wfProfileIn( __METHOD__ );
513
514 $request = $this->context->getRequest();
515
516 // Send Ajax requests to the Ajax dispatcher.
517 if ( $this->config->get( 'UseAjax' ) && $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 ( $this->config->get( 'UseFileCache' ) && $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 $jobRunRate = $this->config->get( 'JobRunRate' );
649 if ( $jobRunRate <= 0 || wfReadOnly() ) {
650 return;
651 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
652 return; // recursion guard
653 }
654
655 $section = new ProfileSection( __METHOD__ );
656
657 if ( $jobRunRate < 1 ) {
658 $max = mt_getrandmax();
659 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
660 return; // the higher the job run rate, the less likely we return here
661 }
662 $n = 1;
663 } else {
664 $n = intval( $jobRunRate );
665 }
666
667 if ( !$this->config->get( 'RunJobsAsync' ) ) {
668 // Fall back to running the job here while the user waits
669 $runner = new JobRunner();
670 $runner->run( array( 'maxJobs' => $n ) );
671 return;
672 }
673
674 try {
675 if ( !JobQueueGroup::singleton()->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
676 return; // do not send request if there are probably no jobs
677 }
678 } catch ( JobQueueError $e ) {
679 MWExceptionHandler::logException( $e );
680 return; // do not make the site unavailable
681 }
682
683 $query = array( 'title' => 'Special:RunJobs',
684 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 );
685 $query['signature'] = SpecialRunJobs::getQuerySignature( $query );
686
687 $errno = $errstr = null;
688 $info = wfParseUrl( $this->config->get( 'Server' ) );
689 wfSuppressWarnings();
690 $sock = fsockopen(
691 $info['host'],
692 isset( $info['port'] ) ? $info['port'] : 80,
693 $errno,
694 $errstr,
695 // If it takes more than 100ms to connect to ourselves there
696 // is a problem elsewhere.
697 0.1
698 );
699 wfRestoreWarnings();
700 if ( !$sock ) {
701 wfDebugLog( 'runJobs', "Failed to start cron API (socket error $errno): $errstr\n" );
702 // Fall back to running the job here while the user waits
703 $runner = new JobRunner();
704 $runner->run( array( 'maxJobs' => $n ) );
705 return;
706 }
707
708 $url = wfAppendQuery( wfScript( 'index' ), $query );
709 $req = "POST $url HTTP/1.1\r\nHost: {$info['host']}\r\nConnection: Close\r\n\r\n";
710
711 wfDebugLog( 'runJobs', "Running $n job(s) via '$url'\n" );
712 // Send a cron API request to be performed in the background.
713 // Give up if this takes too long to send (which should be rare).
714 stream_set_timeout( $sock, 1 );
715 $bytes = fwrite( $sock, $req );
716 if ( $bytes !== strlen( $req ) ) {
717 wfDebugLog( 'runJobs', "Failed to start cron API (socket write error)\n" );
718 } else {
719 // Do not wait for the response (the script should handle client aborts).
720 // Make sure that we don't close before that script reaches ignore_user_abort().
721 $status = fgets( $sock );
722 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
723 wfDebugLog( 'runJobs', "Failed to start cron API: received '$status'\n" );
724 }
725 }
726 fclose( $sock );
727 }
728 }