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 * This will be removed entirely in 1.20.
273 * @deprecated since 1.18
276 $wgArticle = $article;
278 $this->performAction( $article );
279 } elseif ( is_string( $article ) ) {
280 $output->redirect( $article );
282 wfProfileOut( __METHOD__
);
283 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
288 // Promote user to any groups they meet the criteria for
289 $user->addAutopromoteOnceGroups( 'onView' );
292 wfProfileOut( __METHOD__
);
296 * Create an Article object of the appropriate class for the given page.
298 * @deprecated in 1.18; use Article::newFromTitle() instead
299 * @param $title Title
300 * @param $context IContextSource
301 * @return Article object
303 public static function articleFromTitle( $title, IContextSource
$context ) {
304 wfDeprecated( __METHOD__
, '1.18' );
305 return Article
::newFromTitle( $title, $context );
309 * Returns the name of the action that will be executed.
311 * @return string: action
313 public function getAction() {
314 static $action = null;
316 if ( $action === null ) {
317 $action = Action
::getActionName( $this->context
);
324 * Initialize the main Article object for "standard" actions (view, etc)
325 * Create an Article object for the page, following redirects if needed.
327 * @return mixed an Article, or a string to redirect to another URL
329 private function initializeArticle() {
330 global $wgDisableHardRedirects;
332 wfProfileIn( __METHOD__
);
334 $title = $this->context
->getTitle();
335 $article = Article
::newFromTitle( $title, $this->context
);
336 $this->context
->setWikiPage( $article->getPage() );
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__
);
344 $request = $this->context
->getRequest();
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() ) )
357 // Give extensions a change to ignore/handle redirects as needed
358 $ignoreRedirect = $target = false;
360 wfRunHooks( 'InitializeArticleMaybeRedirect',
361 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
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__
);
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() );
387 $this->context
->setTitle( $article->getTitle() );
388 $this->context
->setWikiPage( $article->getPage() );
392 wfProfileOut( __METHOD__
);
397 * Cleaning up request by doing deferred updates, DB transaction, and the output
399 public function finalCleanup() {
400 wfProfileIn( __METHOD__
);
401 // Now commit any transactions, so that unreported errors after
402 // output() don't roll back the whole DB transaction
403 $factory = wfGetLBFactory();
404 $factory->commitMasterChanges();
405 // Output everything!
406 $this->context
->getOutput()->output();
407 // Do any deferred jobs
408 DeferredUpdates
::doUpdates( 'commit' );
410 wfProfileOut( __METHOD__
);
414 * Do a job from the job queue
416 private function doJobs() {
417 global $wgJobRunRate;
419 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
422 if ( $wgJobRunRate < 1 ) {
423 $max = mt_getrandmax();
424 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
429 $n = intval( $wgJobRunRate );
432 while ( $n-- && false != ( $job = Job
::pop() ) ) {
433 $output = $job->toString() . "\n";
434 $t = - microtime( true );
435 $success = $job->run();
436 $t +
= microtime( true );
437 $t = round( $t * 1000 );
439 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
441 $output .= "Success, Time: $t ms\n";
443 wfDebugLog( 'jobqueue', $output );
448 * Ends this task peacefully
450 public function restInPeace() {
451 MessageCache
::logMessages();
452 wfLogProfilingData();
453 // Commit and close up!
454 $factory = wfGetLBFactory();
455 $factory->commitMasterChanges();
456 $factory->shutdown();
457 wfDebug( "Request ended normally\n" );
461 * Perform one of the "standard" actions
465 private function performAction( Page
$page ) {
466 wfProfileIn( __METHOD__
);
468 $request = $this->context
->getRequest();
469 $output = $this->context
->getOutput();
470 $title = $this->context
->getTitle();
471 $user = $this->context
->getUser();
473 if ( !wfRunHooks( 'MediaWikiPerformAction',
474 array( $output, $page, $title, $user, $request, $this ) ) )
476 wfProfileOut( __METHOD__
);
480 $act = $this->getAction();
482 $action = Action
::factory( $act, $page );
483 if ( $action instanceof Action
) {
485 wfProfileOut( __METHOD__
);
489 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
490 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
493 wfProfileOut( __METHOD__
);
497 * Run the current MediaWiki instance
498 * index.php just calls this
500 public function run() {
502 $this->checkMaxLag();
504 $this->restInPeace();
505 } catch ( Exception
$e ) {
506 MWExceptionHandler
::handle( $e );
511 * Checks if the request should abort due to a lagged server,
512 * for given maxlag parameter.
515 private function checkMaxLag() {
516 global $wgShowHostnames;
518 wfProfileIn( __METHOD__
);
519 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
520 if ( !is_null( $maxLag ) ) {
521 list( $host, $lag ) = wfGetLB()->getMaxLag();
522 if ( $lag > $maxLag ) {
523 $resp = $this->context
->getRequest()->response();
524 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
525 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
526 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
527 $resp->header( 'Content-Type: text/plain' );
528 if( $wgShowHostnames ) {
529 echo "Waiting for $host: $lag seconds lagged\n";
531 echo "Waiting for a database server: $lag seconds lagged\n";
534 wfProfileOut( __METHOD__
);
539 wfProfileOut( __METHOD__
);
543 private function main() {
544 global $wgUseFileCache, $wgTitle, $wgUseAjax;
546 wfProfileIn( __METHOD__
);
548 $request = $this->context
->getRequest();
550 // Send Ajax requests to the Ajax dispatcher.
551 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
553 // Set a dummy title, because $wgTitle == null might break things
554 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
555 $this->context
->setTitle( $title );
558 $dispatcher = new AjaxDispatcher();
559 $dispatcher->performAction();
560 wfProfileOut( __METHOD__
);
564 // Get title from request parameters,
565 // is set on the fly by parseTitle the first time.
566 $title = $this->getTitle();
567 $action = $this->getAction();
570 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
571 wfProfileIn( 'main-try-filecache' );
572 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
573 // Try low-level file cache hit
574 $cache = HTMLFileCache
::newFromTitle( $title, $action );
575 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
576 // Check incoming headers to see if client has this cached
577 $timestamp = $cache->cacheTimestamp();
578 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
579 $cache->loadFromFileCache( $this->context
);
581 // Do any stats increment/watchlist stuff
582 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
583 // Tell OutputPage that output is taken care of
584 $this->context
->getOutput()->disable();
585 wfProfileOut( 'main-try-filecache' );
586 wfProfileOut( __METHOD__
);
590 wfProfileOut( 'main-try-filecache' );
593 $this->performRequest();
594 $this->finalCleanup();
596 wfProfileOut( __METHOD__
);