Merge "Remove zh-tw message "editing""
[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 use MediaWiki\Logger\LoggerFactory;
24
25 /**
26 * The MediaWiki class is the helper class for the index.php entry point.
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 // 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 // Actions that need to be made when we have a special pages
267 SpecialPageFactory::executePath( $title, $this->context );
268 } else {
269 // ...otherwise treat it as an article view. The article
270 // may be a redirect to another article or URL.
271 $article = $this->initializeArticle();
272 if ( is_object( $article ) ) {
273 $this->performAction( $article, $requestTitle );
274 } elseif ( is_string( $article ) ) {
275 $output->redirect( $article );
276 } else {
277 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
278 . " returned neither an object nor a URL" );
279 }
280 }
281 }
282
283 /**
284 * Initialize the main Article object for "standard" actions (view, etc)
285 * Create an Article object for the page, following redirects if needed.
286 *
287 * @return mixed An Article, or a string to redirect to another URL
288 */
289 private function initializeArticle() {
290
291 $title = $this->context->getTitle();
292 if ( $this->context->canUseWikiPage() ) {
293 // Try to use request context wiki page, as there
294 // is already data from db saved in per process
295 // cache there from this->getAction() call.
296 $page = $this->context->getWikiPage();
297 $article = Article::newFromWikiPage( $page, $this->context );
298 } else {
299 // This case should not happen, but just in case.
300 $article = Article::newFromTitle( $title, $this->context );
301 $this->context->setWikiPage( $article->getPage() );
302 }
303
304 // NS_MEDIAWIKI has no redirects.
305 // It is also used for CSS/JS, so performance matters here...
306 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
307 return $article;
308 }
309
310 $request = $this->context->getRequest();
311
312 // Namespace might change when using redirects
313 // Check for redirects ...
314 $action = $request->getVal( 'action', 'view' );
315 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
316 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
317 && !$request->getVal( 'oldid' ) // ... and are not old revisions
318 && !$request->getVal( 'diff' ) // ... and not when showing diff
319 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
320 // ... and the article is not a non-redirect image page with associated file
321 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
322 ) {
323 // Give extensions a change to ignore/handle redirects as needed
324 $ignoreRedirect = $target = false;
325
326 Hooks::run( 'InitializeArticleMaybeRedirect',
327 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
328
329 // Follow redirects only for... redirects.
330 // If $target is set, then a hook wanted to redirect.
331 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
332 // Is the target already set by an extension?
333 $target = $target ? $target : $article->followRedirect();
334 if ( is_string( $target ) ) {
335 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
336 // we'll need to redirect
337 return $target;
338 }
339 }
340 if ( is_object( $target ) ) {
341 // Rewrite environment to redirected article
342 $rarticle = Article::newFromTitle( $target, $this->context );
343 $rarticle->loadPageData();
344 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
345 $rarticle->setRedirectedFrom( $title );
346 $article = $rarticle;
347 $this->context->setTitle( $target );
348 $this->context->setWikiPage( $article->getPage() );
349 }
350 }
351 } else {
352 $this->context->setTitle( $article->getTitle() );
353 $this->context->setWikiPage( $article->getPage() );
354 }
355 }
356
357 return $article;
358 }
359
360 /**
361 * Perform one of the "standard" actions
362 *
363 * @param Page $page
364 * @param Title $requestTitle The original title, before any redirects were applied
365 */
366 private function performAction( Page $page, Title $requestTitle ) {
367
368 $request = $this->context->getRequest();
369 $output = $this->context->getOutput();
370 $title = $this->context->getTitle();
371 $user = $this->context->getUser();
372
373 if ( !Hooks::run( 'MediaWikiPerformAction',
374 array( $output, $page, $title, $user, $request, $this ) )
375 ) {
376 return;
377 }
378
379 $act = $this->getAction();
380
381 $action = Action::factory( $act, $page, $this->context );
382
383 if ( $action instanceof Action ) {
384 # Let Squid cache things if we can purge them.
385 if ( $this->config->get( 'UseSquid' ) &&
386 in_array(
387 // Use PROTO_INTERNAL because that's what getSquidURLs() uses
388 wfExpandUrl( $request->getRequestURL(), PROTO_INTERNAL ),
389 $requestTitle->getSquidURLs()
390 )
391 ) {
392 $output->setSquidMaxage( $this->config->get( 'SquidMaxage' ) );
393 }
394
395 $action->show();
396 return;
397 }
398
399 if ( Hooks::run( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
400 $output->setStatusCode( 404 );
401 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
402 }
403
404 }
405
406 /**
407 * Run the current MediaWiki instance
408 * index.php just calls this
409 */
410 public function run() {
411 try {
412 $this->checkMaxLag();
413 try {
414 $this->main();
415 } catch ( ErrorPageError $e ) {
416 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
417 // they are not internal application faults. As with normal requests, this
418 // should commit, print the output, do deferred updates, jobs, and profiling.
419 wfGetLBFactory()->commitMasterChanges();
420 $e->report(); // display the GUI error
421 }
422 if ( function_exists( 'fastcgi_finish_request' ) ) {
423 fastcgi_finish_request();
424 }
425 $this->triggerJobs();
426 $this->restInPeace();
427 } catch ( Exception $e ) {
428 MWExceptionHandler::handleException( $e );
429 }
430 }
431
432 /**
433 * Checks if the request should abort due to a lagged server,
434 * for given maxlag parameter.
435 * @return bool
436 */
437 private function checkMaxLag() {
438 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
439 if ( !is_null( $maxLag ) ) {
440 list( $host, $lag ) = wfGetLB()->getMaxLag();
441 if ( $lag > $maxLag ) {
442 $resp = $this->context->getRequest()->response();
443 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
444 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
445 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
446 $resp->header( 'Content-Type: text/plain' );
447 if ( $this->config->get( 'ShowHostnames' ) ) {
448 echo "Waiting for $host: $lag seconds lagged\n";
449 } else {
450 echo "Waiting for a database server: $lag seconds lagged\n";
451 }
452
453 exit;
454 }
455 }
456 return true;
457 }
458
459 private function main() {
460 global $wgTitle;
461
462 $request = $this->context->getRequest();
463
464 // Send Ajax requests to the Ajax dispatcher.
465 if ( $this->config->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
466 // Set a dummy title, because $wgTitle == null might break things
467 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/performing an AJAX call in '
468 . __METHOD__
469 );
470 $this->context->setTitle( $title );
471 $wgTitle = $title;
472
473 $dispatcher = new AjaxDispatcher( $this->config );
474 $dispatcher->performAction( $this->context->getUser() );
475 return;
476 }
477
478 // Get title from request parameters,
479 // is set on the fly by parseTitle the first time.
480 $title = $this->getTitle();
481 $action = $this->getAction();
482 $wgTitle = $title;
483
484 $trxProfiler = Profiler::instance()->getTransactionProfiler();
485 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
486
487 // Aside from rollback, master queries should not happen on GET requests.
488 // Periodic or "in passing" updates on GET should use the job queue.
489 if ( !$request->wasPosted()
490 && in_array( $action, array( 'view', 'edit', 'history' ) )
491 ) {
492 $trxProfiler->setExpectation( 'masterConns', 0, __METHOD__ );
493 $trxProfiler->setExpectation( 'writes', 0, __METHOD__ );
494 } else {
495 $trxProfiler->setExpectation( 'maxAffected', 500, __METHOD__ );
496 }
497
498 // If the user has forceHTTPS set to true, or if the user
499 // is in a group requiring HTTPS, or if they have the HTTPS
500 // preference set, redirect them to HTTPS.
501 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
502 // isLoggedIn() will do all sorts of weird stuff.
503 if (
504 $request->getProtocol() == 'http' &&
505 (
506 $request->getCookie( 'forceHTTPS', '' ) ||
507 // check for prefixed version for currently logged in users
508 $request->getCookie( 'forceHTTPS' ) ||
509 // Avoid checking the user and groups unless it's enabled.
510 (
511 $this->context->getUser()->isLoggedIn()
512 && $this->context->getUser()->requiresHTTPS()
513 )
514 )
515 ) {
516 $oldUrl = $request->getFullRequestURL();
517 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
518
519 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
520 if ( Hooks::run( 'BeforeHttpsRedirect', array( $this->context, &$redirUrl ) ) ) {
521
522 if ( $request->wasPosted() ) {
523 // This is weird and we'd hope it almost never happens. This
524 // means that a POST came in via HTTP and policy requires us
525 // redirecting to HTTPS. It's likely such a request is going
526 // to fail due to post data being lost, but let's try anyway
527 // and just log the instance.
528 //
529 // @todo FIXME: See if we could issue a 307 or 308 here, need
530 // to see how clients (automated & browser) behave when we do
531 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
532 }
533 // Setup dummy Title, otherwise OutputPage::redirect will fail
534 $title = Title::newFromText( 'REDIR', NS_MAIN );
535 $this->context->setTitle( $title );
536 $output = $this->context->getOutput();
537 // Since we only do this redir to change proto, always send a vary header
538 $output->addVaryHeader( 'X-Forwarded-Proto' );
539 $output->redirect( $redirUrl );
540 $output->output();
541 return;
542 }
543 }
544
545 if ( $this->config->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
546 if ( HTMLFileCache::useFileCache( $this->context ) ) {
547 // Try low-level file cache hit
548 $cache = new HTMLFileCache( $title, $action );
549 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
550 // Check incoming headers to see if client has this cached
551 $timestamp = $cache->cacheTimestamp();
552 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
553 $cache->loadFromFileCache( $this->context );
554 }
555 // Do any stats increment/watchlist stuff
556 // Assume we're viewing the latest revision (this should always be the case with file cache)
557 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
558 // Tell OutputPage that output is taken care of
559 $this->context->getOutput()->disable();
560 return;
561 }
562 }
563 }
564
565 // Actually do the work of the request and build up any output
566 $this->performRequest();
567
568 // Either all DB and deferred updates should happen or none.
569 // The later should not be cancelled due to client disconnect.
570 ignore_user_abort( true );
571 // Now commit any transactions, so that unreported errors after
572 // output() don't roll back the whole DB transaction
573 wfGetLBFactory()->commitMasterChanges();
574
575 // Output everything!
576 $this->context->getOutput()->output();
577
578 }
579
580 /**
581 * Ends this task peacefully
582 */
583 public function restInPeace() {
584 // Ignore things like master queries/connections on GET requests
585 // as long as they are in deferred updates (which catch errors).
586 Profiler::instance()->getTransactionProfiler()->resetExpectations();
587
588 // Do any deferred jobs
589 DeferredUpdates::doUpdates( 'commit' );
590
591 // Log profiling data, e.g. in the database or UDP
592 wfLogProfilingData();
593
594 // Commit and close up!
595 $factory = wfGetLBFactory();
596 $factory->commitMasterChanges();
597 $factory->shutdown();
598
599 wfDebug( "Request ended normally\n" );
600 }
601
602 /**
603 * Potentially open a socket and sent an HTTP request back to the server
604 * to run a specified number of jobs. This registers a callback to cleanup
605 * the socket once it's done.
606 */
607 protected function triggerJobs() {
608 $jobRunRate = $this->config->get( 'JobRunRate' );
609 if ( $jobRunRate <= 0 || wfReadOnly() ) {
610 return;
611 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
612 return; // recursion guard
613 }
614
615 if ( $jobRunRate < 1 ) {
616 $max = mt_getrandmax();
617 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
618 return; // the higher the job run rate, the less likely we return here
619 }
620 $n = 1;
621 } else {
622 $n = intval( $jobRunRate );
623 }
624
625 $runJobsLogger = LoggerFactory::getInstance( 'runJobs' );
626
627 if ( !$this->config->get( 'RunJobsAsync' ) ) {
628 // Fall back to running the job here while the user waits
629 $runner = new JobRunner( $runJobsLogger );
630 $runner->run( array( 'maxJobs' => $n ) );
631 return;
632 }
633
634 try {
635 if ( !JobQueueGroup::singleton()->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
636 return; // do not send request if there are probably no jobs
637 }
638 } catch ( JobQueueError $e ) {
639 MWExceptionHandler::logException( $e );
640 return; // do not make the site unavailable
641 }
642
643 $query = array( 'title' => 'Special:RunJobs',
644 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 );
645 $query['signature'] = SpecialRunJobs::getQuerySignature(
646 $query, $this->config->get( 'SecretKey' ) );
647
648 $errno = $errstr = null;
649 $info = wfParseUrl( $this->config->get( 'Server' ) );
650 wfSuppressWarnings();
651 $sock = fsockopen(
652 $info['host'],
653 isset( $info['port'] ) ? $info['port'] : 80,
654 $errno,
655 $errstr,
656 // If it takes more than 100ms to connect to ourselves there
657 // is a problem elsewhere.
658 0.1
659 );
660 wfRestoreWarnings();
661 if ( !$sock ) {
662 $runJobsLogger->error( "Failed to start cron API (socket error $errno): $errstr" );
663 // Fall back to running the job here while the user waits
664 $runner = new JobRunner( $runJobsLogger );
665 $runner->run( array( 'maxJobs' => $n ) );
666 return;
667 }
668
669 $url = wfAppendQuery( wfScript( 'index' ), $query );
670 $req = (
671 "POST $url HTTP/1.1\r\n" .
672 "Host: {$info['host']}\r\n" .
673 "Connection: Close\r\n" .
674 "Content-Length: 0\r\n\r\n"
675 );
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 }