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
24 * The MediaWiki class is the helper class for the index.php entry point.
26 * @internal documentation reviewed 15 Mar 2010
31 * TODO: fold $output, etc, into this
37 * @param $x null|WebRequest
40 public function request( WebRequest
$x = null ) {
41 $old = $this->context
->getRequest();
42 $this->context
->setRequest( $x );
47 * @param $x null|OutputPage
50 public function output( OutputPage
$x = null ) {
51 $old = $this->context
->getOutput();
52 $this->context
->setOutput( $x );
57 * @param IContextSource|null $context
59 public function __construct( IContextSource
$context = null ) {
61 $context = RequestContext
::getMain();
64 $this->context
= $context;
65 $this->context
->setTitle( $this->parseTitle() );
69 * Parse the request to get the Title object
71 * @return Title object to be $wgTitle
73 private function parseTitle() {
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' );
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();
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
113 $rev = Revision
::newFromId( $oldid );
114 $ret = $rev ?
$rev->getTitle() : $ret;
118 if ( $ret === null ||
( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
119 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
126 * Get the Title object that we'll be acting on, as specified in the WebRequest
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.
140 * - local interwiki redirects
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' );
202 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
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 );
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() );
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 " .
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 " .
254 throw new HttpError( 500, $message );
256 $output->setSquidMaxage( 1200 );
257 $output->redirect( $targetUrl, '301' );
260 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
262 // Actions that need to be made when we have a special pages
263 SpecialPageFactory
::executePath( $title, $this->context
);
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 ) ) {
271 * $wgArticle is deprecated, do not use it.
272 * @deprecated since 1.18
275 $wgArticle = new DeprecatedGlobal( 'wgArticle', $article, '1.18' );
277 $this->performAction( $article );
278 } elseif ( is_string( $article ) ) {
279 $output->redirect( $article );
281 wfProfileOut( __METHOD__
);
282 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
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
);
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__
);
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__
);
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() );
386 $this->context
->setTitle( $article->getTitle() );
387 $this->context
->setWikiPage( $article->getPage() );
391 wfProfileOut( __METHOD__
);
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' );
409 wfProfileOut( __METHOD__
);
413 * Do a job from the job queue
415 private function doJobs() {
416 global $wgJobRunRate;
418 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
421 if ( $wgJobRunRate < 1 ) {
422 $max = mt_getrandmax();
423 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
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 );
438 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
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
464 private function performAction( Page
$page ) {
465 wfProfileIn( __METHOD__
);
467 $request = $this->context
->getRequest();
468 $output = $this->context
->getOutput();
469 $title = $this->context
->getTitle();
470 $user = $this->context
->getUser();
472 if ( !wfRunHooks( 'MediaWikiPerformAction',
473 array( $output, $page, $title, $user, $request, $this ) ) )
475 wfProfileOut( __METHOD__
);
479 $act = $this->getAction();
481 $action = Action
::factory( $act, $page );
482 if ( $action instanceof Action
) {
484 wfProfileOut( __METHOD__
);
488 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
489 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
492 wfProfileOut( __METHOD__
);
496 * Run the current MediaWiki instance
497 * index.php just calls this
499 public function run() {
501 $this->checkMaxLag();
503 $this->restInPeace();
504 } catch ( Exception
$e ) {
505 MWExceptionHandler
::handle( $e );
510 * Checks if the request should abort due to a lagged server,
511 * for given maxlag parameter.
514 private function checkMaxLag() {
515 global $wgShowHostnames;
517 wfProfileIn( __METHOD__
);
518 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
519 if ( !is_null( $maxLag ) ) {
520 list( $host, $lag ) = wfGetLB()->getMaxLag();
521 if ( $lag > $maxLag ) {
522 $resp = $this->context
->getRequest()->response();
523 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
524 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
525 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
526 $resp->header( 'Content-Type: text/plain' );
527 if( $wgShowHostnames ) {
528 echo "Waiting for $host: $lag seconds lagged\n";
530 echo "Waiting for a database server: $lag seconds lagged\n";
533 wfProfileOut( __METHOD__
);
538 wfProfileOut( __METHOD__
);
542 private function main() {
543 global $wgUseFileCache, $wgTitle, $wgUseAjax;
545 wfProfileIn( __METHOD__
);
547 $request = $this->context
->getRequest();
549 // Send Ajax requests to the Ajax dispatcher.
550 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
552 // Set a dummy title, because $wgTitle == null might break things
553 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
554 $this->context
->setTitle( $title );
557 $dispatcher = new AjaxDispatcher();
558 $dispatcher->performAction();
559 wfProfileOut( __METHOD__
);
563 // Get title from request parameters,
564 // is set on the fly by parseTitle the first time.
565 $title = $this->getTitle();
566 $action = $this->getAction();
569 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
570 wfProfileIn( 'main-try-filecache' );
571 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
572 // Try low-level file cache hit
573 $cache = HTMLFileCache
::newFromTitle( $title, $action );
574 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
575 // Check incoming headers to see if client has this cached
576 $timestamp = $cache->cacheTimestamp();
577 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
578 $cache->loadFromFileCache( $this->context
);
580 // Do any stats increment/watchlist stuff
581 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
582 // Tell OutputPage that output is taken care of
583 $this->context
->getOutput()->disable();
584 wfProfileOut( 'main-try-filecache' );
585 wfProfileOut( __METHOD__
);
589 wfProfileOut( 'main-try-filecache' );
592 $this->performRequest();
593 $this->finalCleanup();
595 wfProfileOut( __METHOD__
);