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