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