Add a way for packagers to override some installation details
[mediawiki.git] / includes / Wiki.php
blob08e06eae3139b2d6753ce60b019533aa039bda7a
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 {
30 /**
31 * TODO: fold $output, etc, into this
32 * @var IContextSource
34 private $context;
36 /**
37 * @param $x null|WebRequest
38 * @return WebRequest
40 public function request( WebRequest $x = null ) {
41 $old = $this->context->getRequest();
42 $this->context->setRequest( $x );
43 return $old;
46 /**
47 * @param $x null|OutputPage
48 * @return OutputPage
50 public function output( OutputPage $x = null ) {
51 $old = $this->context->getOutput();
52 $this->context->setOutput( $x );
53 return $old;
56 /**
57 * @param IContextSource|null $context
59 public function __construct( IContextSource $context = null ) {
60 if ( !$context ) {
61 $context = RequestContext::getMain();
64 $this->context = $context;
65 $this->context->setTitle( $this->parseTitle() );
68 /**
69 * Parse the request to get the Title object
71 * @return Title object to be $wgTitle
73 private function parseTitle() {
74 global $wgContLang;
76 $request = $this->context->getRequest();
77 $curid = $request->getInt( 'curid' );
78 $title = $request->getVal( 'title' );
79 $action = $request->getVal( 'action', 'view' );
81 if ( $request->getCheck( 'search' ) ) {
82 // Compatibility with old search URLs which didn't use Special:Search
83 // Just check for presence here, so blank requests still
84 // show the search page when using ugly URLs (bug 8054).
85 $ret = SpecialPage::getTitleFor( 'Search' );
86 } elseif ( $curid ) {
87 // URLs like this are generated by RC, because rc_title isn't always accurate
88 $ret = Title::newFromID( $curid );
89 } elseif ( $title == '' && $action != 'delete' ) {
90 $ret = Title::newMainPage();
91 } else {
92 $ret = Title::newFromURL( $title );
93 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
94 // in wikitext links to tell Parser to make a direct file link
95 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) {
96 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
98 // Check variant links so that interwiki links don't have to worry
99 // about the possible different language variants
100 if ( count( $wgContLang->getVariants() ) > 1
101 && !is_null( $ret ) && $ret->getArticleID() == 0 )
103 $wgContLang->findVariantLink( $title, $ret );
106 // For non-special titles, check for implicit titles
107 if ( is_null( $ret ) || !$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;
118 if ( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
119 $ret = SpecialPage::getTitleFor( 'Badtitle' );
122 return $ret;
126 * Get the Title object that we'll be acting on, as specified in the WebRequest
127 * @return Title
129 public function getTitle() {
130 if( $this->context->getTitle() === null ){
131 $this->context->setTitle( $this->parseTitle() );
133 return $this->context->getTitle();
137 * Performs the request.
138 * - bad titles
139 * - read restriction
140 * - local interwiki redirects
141 * - redirect loop
142 * - special pages
143 * - normal pages
145 * @return void
147 private function performRequest() {
148 global $wgServer, $wgUsePathInfo, $wgTitle;
150 wfProfileIn( __METHOD__ );
152 $request = $this->context->getRequest();
153 $title = $this->context->getTitle();
154 $output = $this->context->getOutput();
155 $user = $this->context->getUser();
157 if ( $request->getVal( 'printable' ) === 'yes' ) {
158 $output->setPrintable();
161 $unused = null; // To pass it by reference
162 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
164 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
165 if ( is_null( $title ) || ( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
166 $title->isSpecial( 'Badtitle' ) )
168 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
169 wfProfileOut( __METHOD__ );
170 throw new BadTitleError();
173 // Check user's permissions to read this page.
174 // We have to check here to catch special pages etc.
175 // We will check again in Article::view().
176 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
177 if ( count( $permErrors ) ) {
178 // Bug 32276: allowing the skin to generate output with $wgTitle or
179 // $this->context->title set to the input title would allow anonymous users to
180 // determine whether a page exists, potentially leaking private data. In fact, the
181 // curid and oldid request parameters would allow page titles to be enumerated even
182 // when they are not guessable. So we reset the title to Special:Badtitle before the
183 // permissions error is displayed.
185 // The skin mostly uses $this->context->getTitle() these days, but some extensions
186 // still use $wgTitle.
188 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
189 $this->context->setTitle( $badTitle );
190 $wgTitle = $badTitle;
192 wfProfileOut( __METHOD__ );
193 throw new PermissionsError( 'read', $permErrors );
196 $pageView = false; // was an article or special page viewed?
198 // Interwiki redirects
199 if ( $title->getInterwiki() != '' ) {
200 $rdfrom = $request->getVal( 'rdfrom' );
201 if ( $rdfrom ) {
202 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
203 } else {
204 $query = $request->getValues();
205 unset( $query['title'] );
206 $url = $title->getFullURL( $query );
208 // Check for a redirect loop
209 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
210 && $title->isLocal() )
212 // 301 so google et al report the target as the actual url.
213 $output->redirect( $url, 301 );
214 } else {
215 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
216 wfProfileOut( __METHOD__ );
217 throw new BadTitleError();
219 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
220 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
221 && ( $request->getVal( 'title' ) === null ||
222 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
223 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
224 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
226 if ( $title->isSpecialPage() ) {
227 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
228 if ( $name ) {
229 $title = SpecialPage::getTitleFor( $name, $subpage );
232 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
233 // Redirect to canonical url, make it a 301 to allow caching
234 if ( $targetUrl == $request->getFullRequestURL() ) {
235 $message = "Redirect loop detected!\n\n" .
236 "This means the wiki got confused about what page was " .
237 "requested; this sometimes happens when moving a wiki " .
238 "to a new server or changing the server configuration.\n\n";
240 if ( $wgUsePathInfo ) {
241 $message .= "The wiki is trying to interpret the page " .
242 "title from the URL path portion (PATH_INFO), which " .
243 "sometimes fails depending on the web server. Try " .
244 "setting \"\$wgUsePathInfo = false;\" in your " .
245 "LocalSettings.php, or check that \$wgArticlePath " .
246 "is correct.";
247 } else {
248 $message .= "Your web server was detected as possibly not " .
249 "supporting URL path components (PATH_INFO) correctly; " .
250 "check your LocalSettings.php for a customized " .
251 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
252 "to true.";
254 throw new HttpError( 500, $message );
255 } else {
256 $output->setSquidMaxage( 1200 );
257 $output->redirect( $targetUrl, '301' );
259 // Special pages
260 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
261 $pageView = true;
262 // Actions that need to be made when we have a special pages
263 SpecialPageFactory::executePath( $title, $this->context );
264 } else {
265 // ...otherwise treat it as an article view. The article
266 // may be a redirect to another article or URL.
267 $article = $this->initializeArticle();
268 if ( is_object( $article ) ) {
269 $pageView = true;
271 * $wgArticle is deprecated, do not use it.
272 * @deprecated since 1.18
274 global $wgArticle;
275 $wgArticle = new DeprecatedGlobal( 'wgArticle', $article, '1.18' );
277 $this->performAction( $article );
278 } elseif ( is_string( $article ) ) {
279 $output->redirect( $article );
280 } else {
281 wfProfileOut( __METHOD__ );
282 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
286 if ( $pageView ) {
287 // Promote user to any groups they meet the criteria for
288 $user->addAutopromoteOnceGroups( 'onView' );
291 wfProfileOut( __METHOD__ );
295 * Create an Article object of the appropriate class for the given page.
297 * @deprecated in 1.18; use Article::newFromTitle() instead
298 * @param $title Title
299 * @param $context IContextSource
300 * @return Article object
302 public static function articleFromTitle( $title, IContextSource $context ) {
303 wfDeprecated( __METHOD__, '1.18' );
304 return Article::newFromTitle( $title, $context );
308 * Returns the name of the action that will be executed.
310 * @return string: action
312 public function getAction() {
313 static $action = null;
315 if ( $action === null ) {
316 $action = Action::getActionName( $this->context );
319 return $action;
323 * Initialize the main Article object for "standard" actions (view, etc)
324 * Create an Article object for the page, following redirects if needed.
326 * @return mixed an Article, or a string to redirect to another URL
328 private function initializeArticle() {
329 global $wgDisableHardRedirects;
331 wfProfileIn( __METHOD__ );
333 $title = $this->context->getTitle();
334 $article = Article::newFromTitle( $title, $this->context );
335 $this->context->setWikiPage( $article->getPage() );
336 // NS_MEDIAWIKI has no redirects.
337 // It is also used for CSS/JS, so performance matters here...
338 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
339 wfProfileOut( __METHOD__ );
340 return $article;
343 $request = $this->context->getRequest();
345 // Namespace might change when using redirects
346 // Check for redirects ...
347 $action = $request->getVal( 'action', 'view' );
348 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
349 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
350 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
351 !$request->getVal( 'diff' ) && // ... and not when showing diff
352 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
353 // ... and the article is not a non-redirect image page with associated file
354 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
356 // Give extensions a change to ignore/handle redirects as needed
357 $ignoreRedirect = $target = false;
359 wfRunHooks( 'InitializeArticleMaybeRedirect',
360 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
362 // Follow redirects only for... redirects.
363 // If $target is set, then a hook wanted to redirect.
364 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
365 // Is the target already set by an extension?
366 $target = $target ? $target : $article->followRedirect();
367 if ( is_string( $target ) ) {
368 if ( !$wgDisableHardRedirects ) {
369 // we'll need to redirect
370 wfProfileOut( __METHOD__ );
371 return $target;
374 if ( is_object( $target ) ) {
375 // Rewrite environment to redirected article
376 $rarticle = Article::newFromTitle( $target, $this->context );
377 $rarticle->loadPageData();
378 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
379 $rarticle->setRedirectedFrom( $title );
380 $article = $rarticle;
381 $this->context->setTitle( $target );
382 $this->context->setWikiPage( $article->getPage() );
385 } else {
386 $this->context->setTitle( $article->getTitle() );
387 $this->context->setWikiPage( $article->getPage() );
391 wfProfileOut( __METHOD__ );
392 return $article;
396 * Cleaning up request by doing deferred updates, DB transaction, and the output
398 public function finalCleanup() {
399 wfProfileIn( __METHOD__ );
400 // Now commit any transactions, so that unreported errors after
401 // output() don't roll back the whole DB transaction
402 $factory = wfGetLBFactory();
403 $factory->commitMasterChanges();
404 // Output everything!
405 $this->context->getOutput()->output();
406 // Do any deferred jobs
407 DeferredUpdates::doUpdates( 'commit' );
408 $this->doJobs();
409 wfProfileOut( __METHOD__ );
413 * Do a job from the job queue
415 private function doJobs() {
416 global $wgJobRunRate;
418 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
419 return;
421 if ( $wgJobRunRate < 1 ) {
422 $max = mt_getrandmax();
423 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
424 return;
426 $n = 1;
427 } else {
428 $n = intval( $wgJobRunRate );
431 while ( $n-- && false != ( $job = Job::pop() ) ) {
432 $output = $job->toString() . "\n";
433 $t = - microtime( true );
434 $success = $job->run();
435 $t += microtime( true );
436 $t = round( $t * 1000 );
437 if ( !$success ) {
438 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
439 } else {
440 $output .= "Success, Time: $t ms\n";
442 wfDebugLog( 'jobqueue', $output );
447 * Ends this task peacefully
449 public function restInPeace() {
450 MessageCache::logMessages();
451 wfLogProfilingData();
452 // Commit and close up!
453 $factory = wfGetLBFactory();
454 $factory->commitMasterChanges();
455 $factory->shutdown();
456 wfDebug( "Request ended normally\n" );
460 * Perform one of the "standard" actions
462 * @param $page Page
464 private function performAction( Page $page ) {
465 global $wgUseSquid, $wgSquidMaxage;
467 wfProfileIn( __METHOD__ );
469 $request = $this->context->getRequest();
470 $output = $this->context->getOutput();
471 $title = $this->context->getTitle();
472 $user = $this->context->getUser();
474 if ( !wfRunHooks( 'MediaWikiPerformAction',
475 array( $output, $page, $title, $user, $request, $this ) ) )
477 wfProfileOut( __METHOD__ );
478 return;
481 $act = $this->getAction();
483 $action = Action::factory( $act, $page );
484 if ( $action instanceof Action ) {
485 # When it's a known action, let Squid cache things if we can purge them.
486 # If the action is unknown, we don't know what may happen in an extension,
487 # but not caching can be always safe.
488 if ( $wgUseSquid &&
489 in_array( $request->getFullRequestURL(), $title->getSquidURLs() )
491 $output->setSquidMaxage( $wgSquidMaxage );
494 $action->show();
495 wfProfileOut( __METHOD__ );
496 return;
499 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
500 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
503 wfProfileOut( __METHOD__ );
507 * Run the current MediaWiki instance
508 * index.php just calls this
510 public function run() {
511 try {
512 $this->checkMaxLag();
513 $this->main();
514 $this->restInPeace();
515 } catch ( Exception $e ) {
516 MWExceptionHandler::handle( $e );
521 * Checks if the request should abort due to a lagged server,
522 * for given maxlag parameter.
523 * @return bool
525 private function checkMaxLag() {
526 global $wgShowHostnames;
528 wfProfileIn( __METHOD__ );
529 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
530 if ( !is_null( $maxLag ) ) {
531 list( $host, $lag ) = wfGetLB()->getMaxLag();
532 if ( $lag > $maxLag ) {
533 $resp = $this->context->getRequest()->response();
534 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
535 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
536 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
537 $resp->header( 'Content-Type: text/plain' );
538 if( $wgShowHostnames ) {
539 echo "Waiting for $host: $lag seconds lagged\n";
540 } else {
541 echo "Waiting for a database server: $lag seconds lagged\n";
544 wfProfileOut( __METHOD__ );
546 exit;
549 wfProfileOut( __METHOD__ );
550 return true;
553 private function main() {
554 global $wgUseFileCache, $wgTitle, $wgUseAjax;
556 wfProfileIn( __METHOD__ );
558 $request = $this->context->getRequest();
560 // Send Ajax requests to the Ajax dispatcher.
561 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
563 // Set a dummy title, because $wgTitle == null might break things
564 $title = Title::makeTitle( NS_MAIN, 'AJAX' );
565 $this->context->setTitle( $title );
566 $wgTitle = $title;
568 $dispatcher = new AjaxDispatcher();
569 $dispatcher->performAction();
570 wfProfileOut( __METHOD__ );
571 return;
574 // Get title from request parameters,
575 // is set on the fly by parseTitle the first time.
576 $title = $this->getTitle();
577 $action = $this->getAction();
578 $wgTitle = $title;
580 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
581 wfProfileIn( 'main-try-filecache' );
582 if ( HTMLFileCache::useFileCache( $this->context ) ) {
583 // Try low-level file cache hit
584 $cache = HTMLFileCache::newFromTitle( $title, $action );
585 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
586 // Check incoming headers to see if client has this cached
587 $timestamp = $cache->cacheTimestamp();
588 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
589 $cache->loadFromFileCache( $this->context );
591 // Do any stats increment/watchlist stuff
592 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
593 // Tell OutputPage that output is taken care of
594 $this->context->getOutput()->disable();
595 wfProfileOut( 'main-try-filecache' );
596 wfProfileOut( __METHOD__ );
597 return;
600 wfProfileOut( 'main-try-filecache' );
603 $this->performRequest();
604 $this->finalCleanup();
606 wfProfileOut( __METHOD__ );