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