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