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