Implement extension registration from an extension.json file
[mediawiki.git] / includes / MediaWiki.php
blob7adaca0ab971eb77ee551f3c48a6aa2f00b13a67
1 <?php
2 /**
3 * Helper class for the index.php entry point.
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.
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.
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
20 * @file
23 /**
24 * The MediaWiki class is the helper class for the index.php entry point.
26 * @internal documentation reviewed 15 Mar 2010
28 class MediaWiki {
29 /**
30 * @var IContextSource
32 private $context;
34 /**
35 * @var Config
37 private $config;
39 /**
40 * @param IContextSource|null $context
42 public function __construct( IContextSource $context = null ) {
43 if ( !$context ) {
44 $context = RequestContext::getMain();
47 $this->context = $context;
48 $this->config = $context->getConfig();
51 /**
52 * Parse the request to get the Title object
54 * @return Title Title object to be $wgTitle
56 private function parseTitle() {
57 global $wgContLang;
59 $request = $this->context->getRequest();
60 $curid = $request->getInt( 'curid' );
61 $title = $request->getVal( 'title' );
62 $action = $request->getVal( 'action' );
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() );
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 );
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;
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'
109 $ret = Title::newMainPage();
112 if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
113 $ret = SpecialPage::getTitleFor( 'Badtitle' );
116 return $ret;
120 * Get the Title object that we'll be acting on, as specified in the WebRequest
121 * @return Title
123 public function getTitle() {
124 if ( !$this->context->hasTitle() ) {
125 $this->context->setTitle( $this->parseTitle() );
127 return $this->context->getTitle();
131 * Returns the name of the action that will be executed.
133 * @return string Action
135 public function getAction() {
136 static $action = null;
138 if ( $action === null ) {
139 $action = Action::getActionName( $this->context );
142 return $action;
146 * Performs the request.
147 * - bad titles
148 * - read restriction
149 * - local interwiki redirects
150 * - redirect loop
151 * - special pages
152 * - normal pages
154 * @throws MWException|PermissionsError|BadTitleError|HttpError
155 * @return void
157 private function performRequest() {
158 global $wgTitle;
161 $request = $this->context->getRequest();
162 $requestTitle = $title = $this->context->getTitle();
163 $output = $this->context->getOutput();
164 $user = $this->context->getUser();
166 if ( $request->getVal( 'printable' ) === 'yes' ) {
167 $output->setPrintable();
170 $unused = null; // To pass it by reference
171 Hooks::run( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
173 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
174 if ( is_null( $title ) || ( $title->getDBkey() == '' && !$title->isExternal() )
175 || $title->isSpecial( 'Badtitle' )
177 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
178 throw new BadTitleError();
181 // Check user's permissions to read this page.
182 // We have to check here to catch special pages etc.
183 // We will check again in Article::view().
184 $permErrors = $title->isSpecial( 'RunJobs' )
185 ? array() // relies on HMAC key signature alone
186 : $title->getUserPermissionsErrors( 'read', $user );
187 if ( count( $permErrors ) ) {
188 // Bug 32276: allowing the skin to generate output with $wgTitle or
189 // $this->context->title set to the input title would allow anonymous users to
190 // determine whether a page exists, potentially leaking private data. In fact, the
191 // curid and oldid request parameters would allow page titles to be enumerated even
192 // when they are not guessable. So we reset the title to Special:Badtitle before the
193 // permissions error is displayed.
195 // The skin mostly uses $this->context->getTitle() these days, but some extensions
196 // still use $wgTitle.
198 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
199 $this->context->setTitle( $badTitle );
200 $wgTitle = $badTitle;
202 throw new PermissionsError( 'read', $permErrors );
205 $pageView = false; // was an article or special page viewed?
207 // Interwiki redirects
208 if ( $title->isExternal() ) {
209 $rdfrom = $request->getVal( 'rdfrom' );
210 if ( $rdfrom ) {
211 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
212 } else {
213 $query = $request->getValues();
214 unset( $query['title'] );
215 $url = $title->getFullURL( $query );
217 // Check for a redirect loop
218 if ( !preg_match( '/^' . preg_quote( $this->config->get( 'Server' ), '/' ) . '/', $url )
219 && $title->isLocal()
221 // 301 so google et al report the target as the actual url.
222 $output->redirect( $url, 301 );
223 } else {
224 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
225 throw new BadTitleError();
227 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
228 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
229 && ( $request->getVal( 'title' ) === null
230 || $title->getPrefixedDBkey() != $request->getVal( 'title' ) )
231 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
232 && Hooks::run( 'TestCanonicalRedirect', array( $request, $title, $output ) )
234 if ( $title->isSpecialPage() ) {
235 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
236 if ( $name ) {
237 $title = SpecialPage::getTitleFor( $name, $subpage );
240 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
241 // Redirect to canonical url, make it a 301 to allow caching
242 if ( $targetUrl == $request->getFullRequestURL() ) {
243 $message = "Redirect loop detected!\n\n" .
244 "This means the wiki got confused about what page was " .
245 "requested; this sometimes happens when moving a wiki " .
246 "to a new server or changing the server configuration.\n\n";
248 if ( $this->config->get( 'UsePathInfo' ) ) {
249 $message .= "The wiki is trying to interpret the page " .
250 "title from the URL path portion (PATH_INFO), which " .
251 "sometimes fails depending on the web server. Try " .
252 "setting \"\$wgUsePathInfo = false;\" in your " .
253 "LocalSettings.php, or check that \$wgArticlePath " .
254 "is correct.";
255 } else {
256 $message .= "Your web server was detected as possibly not " .
257 "supporting URL path components (PATH_INFO) correctly; " .
258 "check your LocalSettings.php for a customized " .
259 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
260 "to true.";
262 throw new HttpError( 500, $message );
263 } else {
264 $output->setSquidMaxage( 1200 );
265 $output->redirect( $targetUrl, '301' );
267 // Special pages
268 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
269 $pageView = true;
270 // Actions that need to be made when we have a special pages
271 SpecialPageFactory::executePath( $title, $this->context );
272 } else {
273 // ...otherwise treat it as an article view. The article
274 // may be a redirect to another article or URL.
275 $article = $this->initializeArticle();
276 if ( is_object( $article ) ) {
277 $pageView = true;
278 $this->performAction( $article, $requestTitle );
279 } elseif ( is_string( $article ) ) {
280 $output->redirect( $article );
281 } else {
282 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
283 . " returned neither an object nor a URL" );
287 if ( $pageView ) {
288 // Promote user to any groups they meet the criteria for
289 $user->addAutopromoteOnceGroups( 'onView' );
295 * Initialize the main Article object for "standard" actions (view, etc)
296 * Create an Article object for the page, following redirects if needed.
298 * @return mixed An Article, or a string to redirect to another URL
300 private function initializeArticle() {
302 $title = $this->context->getTitle();
303 if ( $this->context->canUseWikiPage() ) {
304 // Try to use request context wiki page, as there
305 // is already data from db saved in per process
306 // cache there from this->getAction() call.
307 $page = $this->context->getWikiPage();
308 $article = Article::newFromWikiPage( $page, $this->context );
309 } else {
310 // This case should not happen, but just in case.
311 $article = Article::newFromTitle( $title, $this->context );
312 $this->context->setWikiPage( $article->getPage() );
315 // NS_MEDIAWIKI has no redirects.
316 // It is also used for CSS/JS, so performance matters here...
317 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
318 return $article;
321 $request = $this->context->getRequest();
323 // Namespace might change when using redirects
324 // Check for redirects ...
325 $action = $request->getVal( 'action', 'view' );
326 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
327 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
328 && !$request->getVal( 'oldid' ) // ... and are not old revisions
329 && !$request->getVal( 'diff' ) // ... and not when showing diff
330 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
331 // ... and the article is not a non-redirect image page with associated file
332 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
334 // Give extensions a change to ignore/handle redirects as needed
335 $ignoreRedirect = $target = false;
337 Hooks::run( 'InitializeArticleMaybeRedirect',
338 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
340 // Follow redirects only for... redirects.
341 // If $target is set, then a hook wanted to redirect.
342 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
343 // Is the target already set by an extension?
344 $target = $target ? $target : $article->followRedirect();
345 if ( is_string( $target ) ) {
346 if ( !$this->config->get( 'DisableHardRedirects' ) ) {
347 // we'll need to redirect
348 return $target;
351 if ( is_object( $target ) ) {
352 // Rewrite environment to redirected article
353 $rarticle = Article::newFromTitle( $target, $this->context );
354 $rarticle->loadPageData();
355 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
356 $rarticle->setRedirectedFrom( $title );
357 $article = $rarticle;
358 $this->context->setTitle( $target );
359 $this->context->setWikiPage( $article->getPage() );
362 } else {
363 $this->context->setTitle( $article->getTitle() );
364 $this->context->setWikiPage( $article->getPage() );
368 return $article;
372 * Perform one of the "standard" actions
374 * @param Page $page
375 * @param Title $requestTitle The original title, before any redirects were applied
377 private function performAction( Page $page, Title $requestTitle ) {
379 $request = $this->context->getRequest();
380 $output = $this->context->getOutput();
381 $title = $this->context->getTitle();
382 $user = $this->context->getUser();
384 if ( !Hooks::run( 'MediaWikiPerformAction',
385 array( $output, $page, $title, $user, $request, $this ) )
387 return;
390 $act = $this->getAction();
392 $action = Action::factory( $act, $page, $this->context );
394 if ( $action instanceof Action ) {
395 # Let Squid cache things if we can purge them.
396 if ( $this->config->get( 'UseSquid' ) &&
397 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
399 $output->setSquidMaxage( $this->config->get( 'SquidMaxage' ) );
402 $action->show();
403 return;
406 if ( Hooks::run( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
407 $output->setStatusCode( 404 );
408 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
414 * Run the current MediaWiki instance
415 * index.php just calls this
417 public function run() {
418 try {
419 $this->checkMaxLag();
420 try {
421 $this->main();
422 } catch ( ErrorPageError $e ) {
423 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
424 // they are not internal application faults. As with normal requests, this
425 // should commit, print the output, do deferred updates, jobs, and profiling.
426 wfGetLBFactory()->commitMasterChanges();
427 $e->report(); // display the GUI error
429 if ( function_exists( 'fastcgi_finish_request' ) ) {
430 fastcgi_finish_request();
432 $this->triggerJobs();
433 $this->restInPeace();
434 } catch ( Exception $e ) {
435 MWExceptionHandler::handleException( $e );
440 * Checks if the request should abort due to a lagged server,
441 * for given maxlag parameter.
442 * @return bool
444 private function checkMaxLag() {
445 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
446 if ( !is_null( $maxLag ) ) {
447 list( $host, $lag ) = wfGetLB()->getMaxLag();
448 if ( $lag > $maxLag ) {
449 $resp = $this->context->getRequest()->response();
450 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
451 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
452 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
453 $resp->header( 'Content-Type: text/plain' );
454 if ( $this->config->get( 'ShowHostnames' ) ) {
455 echo "Waiting for $host: $lag seconds lagged\n";
456 } else {
457 echo "Waiting for a database server: $lag seconds lagged\n";
461 exit;
464 return true;
467 private function main() {
468 global $wgTitle;
471 $request = $this->context->getRequest();
473 // Send Ajax requests to the Ajax dispatcher.
474 if ( $this->config->get( 'UseAjax' ) && $request->getVal( 'action' ) === 'ajax' ) {
475 // Set a dummy title, because $wgTitle == null might break things
476 $title = Title::makeTitle( NS_MAIN, 'AJAX' );
477 $this->context->setTitle( $title );
478 $wgTitle = $title;
480 $dispatcher = new AjaxDispatcher( $this->config );
481 $dispatcher->performAction( $this->context->getUser() );
482 return;
485 // Get title from request parameters,
486 // is set on the fly by parseTitle the first time.
487 $title = $this->getTitle();
488 $action = $this->getAction();
489 $wgTitle = $title;
491 // If the user has forceHTTPS set to true, or if the user
492 // is in a group requiring HTTPS, or if they have the HTTPS
493 // preference set, redirect them to HTTPS.
494 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
495 // isLoggedIn() will do all sorts of weird stuff.
496 if (
497 $request->getProtocol() == 'http' &&
499 $request->getCookie( 'forceHTTPS', '' ) ||
500 // check for prefixed version for currently logged in users
501 $request->getCookie( 'forceHTTPS' ) ||
502 // Avoid checking the user and groups unless it's enabled.
504 $this->context->getUser()->isLoggedIn()
505 && $this->context->getUser()->requiresHTTPS()
509 $oldUrl = $request->getFullRequestURL();
510 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
512 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
513 if ( Hooks::run( 'BeforeHttpsRedirect', array( $this->context, &$redirUrl ) ) ) {
515 if ( $request->wasPosted() ) {
516 // This is weird and we'd hope it almost never happens. This
517 // means that a POST came in via HTTP and policy requires us
518 // redirecting to HTTPS. It's likely such a request is going
519 // to fail due to post data being lost, but let's try anyway
520 // and just log the instance.
522 // @todo FIXME: See if we could issue a 307 or 308 here, need
523 // to see how clients (automated & browser) behave when we do
524 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
526 // Setup dummy Title, otherwise OutputPage::redirect will fail
527 $title = Title::newFromText( NS_MAIN, 'REDIR' );
528 $this->context->setTitle( $title );
529 $output = $this->context->getOutput();
530 // Since we only do this redir to change proto, always send a vary header
531 $output->addVaryHeader( 'X-Forwarded-Proto' );
532 $output->redirect( $redirUrl );
533 $output->output();
534 return;
538 if ( $this->config->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
539 wfProfileIn( 'main-try-filecache' );
540 if ( HTMLFileCache::useFileCache( $this->context ) ) {
541 // Try low-level file cache hit
542 $cache = new HTMLFileCache( $title, $action );
543 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
544 // Check incoming headers to see if client has this cached
545 $timestamp = $cache->cacheTimestamp();
546 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
547 $cache->loadFromFileCache( $this->context );
549 // Do any stats increment/watchlist stuff
550 // Assume we're viewing the latest revision (this should always be the case with file cache)
551 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
552 // Tell OutputPage that output is taken care of
553 $this->context->getOutput()->disable();
554 wfProfileOut( 'main-try-filecache' );
555 return;
558 wfProfileOut( 'main-try-filecache' );
561 // Actually do the work of the request and build up any output
562 $this->performRequest();
564 // Either all DB and deferred updates should happen or none.
565 // The later should not be cancelled due to client disconnect.
566 ignore_user_abort( true );
567 // Now commit any transactions, so that unreported errors after
568 // output() don't roll back the whole DB transaction
569 wfGetLBFactory()->commitMasterChanges();
571 // Output everything!
572 $this->context->getOutput()->output();
577 * Ends this task peacefully
579 public function restInPeace() {
580 // Do any deferred jobs
581 DeferredUpdates::doUpdates( 'commit' );
583 // Log profiling data, e.g. in the database or UDP
584 wfLogProfilingData();
586 // Commit and close up!
587 $factory = wfGetLBFactory();
588 $factory->commitMasterChanges();
589 $factory->shutdown();
591 wfDebug( "Request ended normally\n" );
595 * Potentially open a socket and sent an HTTP request back to the server
596 * to run a specified number of jobs. This registers a callback to cleanup
597 * the socket once it's done.
599 protected function triggerJobs() {
600 $jobRunRate = $this->config->get( 'JobRunRate' );
601 if ( $jobRunRate <= 0 || wfReadOnly() ) {
602 return;
603 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
604 return; // recursion guard
608 if ( $jobRunRate < 1 ) {
609 $max = mt_getrandmax();
610 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
611 return; // the higher the job run rate, the less likely we return here
613 $n = 1;
614 } else {
615 $n = intval( $jobRunRate );
618 if ( !$this->config->get( 'RunJobsAsync' ) ) {
619 // Fall back to running the job here while the user waits
620 $runner = new JobRunner();
621 $runner->run( array( 'maxJobs' => $n ) );
622 return;
625 try {
626 if ( !JobQueueGroup::singleton()->queuesHaveJobs( JobQueueGroup::TYPE_DEFAULT ) ) {
627 return; // do not send request if there are probably no jobs
629 } catch ( JobQueueError $e ) {
630 MWExceptionHandler::logException( $e );
631 return; // do not make the site unavailable
634 $query = array( 'title' => 'Special:RunJobs',
635 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() + 5 );
636 $query['signature'] = SpecialRunJobs::getQuerySignature(
637 $query, $this->config->get( 'SecretKey' ) );
639 $errno = $errstr = null;
640 $info = wfParseUrl( $this->config->get( 'Server' ) );
641 wfSuppressWarnings();
642 $sock = fsockopen(
643 $info['host'],
644 isset( $info['port'] ) ? $info['port'] : 80,
645 $errno,
646 $errstr,
647 // If it takes more than 100ms to connect to ourselves there
648 // is a problem elsewhere.
651 wfRestoreWarnings();
652 if ( !$sock ) {
653 wfDebugLog( 'runJobs', "Failed to start cron API (socket error $errno): $errstr\n" );
654 // Fall back to running the job here while the user waits
655 $runner = new JobRunner();
656 $runner->run( array( 'maxJobs' => $n ) );
657 return;
660 $url = wfAppendQuery( wfScript( 'index' ), $query );
661 $req = "POST $url HTTP/1.1\r\nHost: {$info['host']}\r\nConnection: Close\r\nContent-Length: 0\r\n\r\n";
663 wfDebugLog( 'runJobs', "Running $n job(s) via '$url'\n" );
664 // Send a cron API request to be performed in the background.
665 // Give up if this takes too long to send (which should be rare).
666 stream_set_timeout( $sock, 1 );
667 $bytes = fwrite( $sock, $req );
668 if ( $bytes !== strlen( $req ) ) {
669 wfDebugLog( 'runJobs', "Failed to start cron API (socket write error)\n" );
670 } else {
671 // Do not wait for the response (the script should handle client aborts).
672 // Make sure that we don't close before that script reaches ignore_user_abort().
673 $status = fgets( $sock );
674 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
675 wfDebugLog( 'runJobs', "Failed to start cron API: received '$status'\n" );
678 fclose( $sock );