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;
68 * Parse the request to get the Title object
70 * @return Title object to be $wgTitle
72 private function parseTitle() {
75 $request = $this->context
->getRequest();
76 $curid = $request->getInt( 'curid' );
77 $title = $request->getVal( 'title' );
78 $action = $request->getVal( 'action', 'view' );
80 if ( $request->getCheck( 'search' ) ) {
81 // Compatibility with old search URLs which didn't use Special:Search
82 // Just check for presence here, so blank requests still
83 // show the search page when using ugly URLs (bug 8054).
84 $ret = SpecialPage
::getTitleFor( 'Search' );
86 // URLs like this are generated by RC, because rc_title isn't always accurate
87 $ret = Title
::newFromID( $curid );
88 } elseif ( $title == '' && $action != 'delete' ) {
89 $ret = Title
::newMainPage();
91 $ret = Title
::newFromURL( $title );
92 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
93 // in wikitext links to tell Parser to make a direct file link
94 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA
) {
95 $ret = Title
::makeTitle( NS_FILE
, $ret->getDBkey() );
97 // Check variant links so that interwiki links don't have to worry
98 // about the possible different language variants
99 if ( count( $wgContLang->getVariants() ) > 1
100 && !is_null( $ret ) && $ret->getArticleID() == 0 )
102 $wgContLang->findVariantLink( $title, $ret );
105 // For non-special titles, check for implicit titles
106 if ( is_null( $ret ) ||
!$ret->isSpecialPage() ) {
107 // We can have urls with just ?diff=,?oldid= or even just ?diff=
108 $oldid = $request->getInt( 'oldid' );
109 $oldid = $oldid ?
$oldid : $request->getInt( 'diff' );
110 // Allow oldid to override a changed or missing title
112 $rev = Revision
::newFromId( $oldid );
113 $ret = $rev ?
$rev->getTitle() : $ret;
117 if ( $ret === null ||
( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
118 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
125 * Get the Title object that we'll be acting on, as specified in the WebRequest
128 public function getTitle() {
129 if( $this->context
->getTitle() === null ){
130 $this->context
->setTitle( $this->parseTitle() );
132 return $this->context
->getTitle();
136 * Returns the name of the action that will be executed.
138 * @return string: action
140 public function getAction() {
141 static $action = null;
143 if ( $action === null ) {
144 $action = Action
::getActionName( $this->context
);
151 * Create an Article object of the appropriate class for the given page.
153 * @deprecated in 1.18; use Article::newFromTitle() instead
154 * @param $title Title
155 * @param $context IContextSource
156 * @return Article object
158 public static function articleFromTitle( $title, IContextSource
$context ) {
159 wfDeprecated( __METHOD__
, '1.18' );
160 return Article
::newFromTitle( $title, $context );
164 * Performs the request.
167 * - local interwiki redirects
174 private function performRequest() {
175 global $wgServer, $wgUsePathInfo, $wgTitle;
177 wfProfileIn( __METHOD__
);
179 $request = $this->context
->getRequest();
180 $title = $this->context
->getTitle();
181 $output = $this->context
->getOutput();
182 $user = $this->context
->getUser();
184 if ( $request->getVal( 'printable' ) === 'yes' ) {
185 $output->setPrintable();
188 $unused = null; // To pass it by reference
189 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
191 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
192 if ( is_null( $title ) ||
( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
193 $title->isSpecial( 'Badtitle' ) )
195 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
196 wfProfileOut( __METHOD__
);
197 throw new BadTitleError();
200 // Check user's permissions to read this page.
201 // We have to check here to catch special pages etc.
202 // We will check again in Article::view().
203 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
204 if ( count( $permErrors ) ) {
205 // Bug 32276: allowing the skin to generate output with $wgTitle or
206 // $this->context->title set to the input title would allow anonymous users to
207 // determine whether a page exists, potentially leaking private data. In fact, the
208 // curid and oldid request parameters would allow page titles to be enumerated even
209 // when they are not guessable. So we reset the title to Special:Badtitle before the
210 // permissions error is displayed.
212 // The skin mostly uses $this->context->getTitle() these days, but some extensions
213 // still use $wgTitle.
215 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
216 $this->context
->setTitle( $badTitle );
217 $wgTitle = $badTitle;
219 wfProfileOut( __METHOD__
);
220 throw new PermissionsError( 'read', $permErrors );
223 $pageView = false; // was an article or special page viewed?
225 // Interwiki redirects
226 if ( $title->getInterwiki() != '' ) {
227 $rdfrom = $request->getVal( 'rdfrom' );
229 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
231 $query = $request->getValues();
232 unset( $query['title'] );
233 $url = $title->getFullURL( $query );
235 // Check for a redirect loop
236 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
237 && $title->isLocal() )
239 // 301 so google et al report the target as the actual url.
240 $output->redirect( $url, 301 );
242 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
243 wfProfileOut( __METHOD__
);
244 throw new BadTitleError();
246 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
247 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
248 && ( $request->getVal( 'title' ) === null ||
249 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
250 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
251 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
253 if ( $title->isSpecialPage() ) {
254 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
256 $title = SpecialPage
::getTitleFor( $name, $subpage );
259 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
260 // Redirect to canonical url, make it a 301 to allow caching
261 if ( $targetUrl == $request->getFullRequestURL() ) {
262 $message = "Redirect loop detected!\n\n" .
263 "This means the wiki got confused about what page was " .
264 "requested; this sometimes happens when moving a wiki " .
265 "to a new server or changing the server configuration.\n\n";
267 if ( $wgUsePathInfo ) {
268 $message .= "The wiki is trying to interpret the page " .
269 "title from the URL path portion (PATH_INFO), which " .
270 "sometimes fails depending on the web server. Try " .
271 "setting \"\$wgUsePathInfo = false;\" in your " .
272 "LocalSettings.php, or check that \$wgArticlePath " .
275 $message .= "Your web server was detected as possibly not " .
276 "supporting URL path components (PATH_INFO) correctly; " .
277 "check your LocalSettings.php for a customized " .
278 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
281 throw new HttpError( 500, $message );
283 $output->setSquidMaxage( 1200 );
284 $output->redirect( $targetUrl, '301' );
287 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
289 // Actions that need to be made when we have a special pages
290 SpecialPageFactory
::executePath( $title, $this->context
);
292 // ...otherwise treat it as an article view. The article
293 // may be a redirect to another article or URL.
294 $article = $this->initializeArticle();
295 if ( is_object( $article ) ) {
298 * $wgArticle is deprecated, do not use it.
299 * @deprecated since 1.18
302 $wgArticle = new DeprecatedGlobal( 'wgArticle', $article, '1.18' );
304 $this->performAction( $article );
305 } elseif ( is_string( $article ) ) {
306 $output->redirect( $article );
308 wfProfileOut( __METHOD__
);
309 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
314 // Promote user to any groups they meet the criteria for
315 $user->addAutopromoteOnceGroups( 'onView' );
318 wfProfileOut( __METHOD__
);
322 * Initialize the main Article object for "standard" actions (view, etc)
323 * Create an Article object for the page, following redirects if needed.
325 * @return mixed an Article, or a string to redirect to another URL
327 private function initializeArticle() {
328 global $wgDisableHardRedirects;
330 wfProfileIn( __METHOD__
);
332 $title = $this->context
->getTitle();
333 $article = Article
::newFromTitle( $title, $this->context
);
334 $this->context
->setWikiPage( $article->getPage() );
335 // NS_MEDIAWIKI has no redirects.
336 // It is also used for CSS/JS, so performance matters here...
337 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
338 wfProfileOut( __METHOD__
);
342 $request = $this->context
->getRequest();
344 // Namespace might change when using redirects
345 // Check for redirects ...
346 $action = $request->getVal( 'action', 'view' );
347 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
348 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
349 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
350 !$request->getVal( 'diff' ) && // ... and not when showing diff
351 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
352 // ... and the article is not a non-redirect image page with associated file
353 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
355 // Give extensions a change to ignore/handle redirects as needed
356 $ignoreRedirect = $target = false;
358 wfRunHooks( 'InitializeArticleMaybeRedirect',
359 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
361 // Follow redirects only for... redirects.
362 // If $target is set, then a hook wanted to redirect.
363 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
364 // Is the target already set by an extension?
365 $target = $target ?
$target : $article->followRedirect();
366 if ( is_string( $target ) ) {
367 if ( !$wgDisableHardRedirects ) {
368 // we'll need to redirect
369 wfProfileOut( __METHOD__
);
373 if ( is_object( $target ) ) {
374 // Rewrite environment to redirected article
375 $rarticle = Article
::newFromTitle( $target, $this->context
);
376 $rarticle->loadPageData();
377 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
378 $rarticle->setRedirectedFrom( $title );
379 $article = $rarticle;
380 $this->context
->setTitle( $target );
381 $this->context
->setWikiPage( $article->getPage() );
385 $this->context
->setTitle( $article->getTitle() );
386 $this->context
->setWikiPage( $article->getPage() );
390 wfProfileOut( __METHOD__
);
395 * Perform one of the "standard" actions
399 private function performAction( Page
$page ) {
400 global $wgUseSquid, $wgSquidMaxage;
402 wfProfileIn( __METHOD__
);
404 $request = $this->context
->getRequest();
405 $output = $this->context
->getOutput();
406 $title = $this->context
->getTitle();
407 $user = $this->context
->getUser();
409 if ( !wfRunHooks( 'MediaWikiPerformAction',
410 array( $output, $page, $title, $user, $request, $this ) ) )
412 wfProfileOut( __METHOD__
);
416 $act = $this->getAction();
418 $action = Action
::factory( $act, $page );
419 if ( $action instanceof Action
) {
420 # Let Squid cache things if we can purge them.
422 in_array( $request->getFullRequestURL(), $title->getSquidURLs() )
424 $output->setSquidMaxage( $wgSquidMaxage );
428 wfProfileOut( __METHOD__
);
432 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
433 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
436 wfProfileOut( __METHOD__
);
440 * Run the current MediaWiki instance
441 * index.php just calls this
443 public function run() {
445 $this->checkMaxLag();
447 $this->restInPeace();
448 } catch ( Exception
$e ) {
449 MWExceptionHandler
::handle( $e );
454 * Checks if the request should abort due to a lagged server,
455 * for given maxlag parameter.
458 private function checkMaxLag() {
459 global $wgShowHostnames;
461 wfProfileIn( __METHOD__
);
462 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
463 if ( !is_null( $maxLag ) ) {
464 list( $host, $lag ) = wfGetLB()->getMaxLag();
465 if ( $lag > $maxLag ) {
466 $resp = $this->context
->getRequest()->response();
467 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
468 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
469 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
470 $resp->header( 'Content-Type: text/plain' );
471 if( $wgShowHostnames ) {
472 echo "Waiting for $host: $lag seconds lagged\n";
474 echo "Waiting for a database server: $lag seconds lagged\n";
477 wfProfileOut( __METHOD__
);
482 wfProfileOut( __METHOD__
);
486 private function main() {
487 global $wgUseFileCache, $wgTitle, $wgUseAjax;
489 wfProfileIn( __METHOD__
);
491 $request = $this->context
->getRequest();
493 // Send Ajax requests to the Ajax dispatcher.
494 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
496 // Set a dummy title, because $wgTitle == null might break things
497 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
498 $this->context
->setTitle( $title );
501 $dispatcher = new AjaxDispatcher();
502 $dispatcher->performAction();
503 wfProfileOut( __METHOD__
);
507 // Get title from request parameters,
508 // is set on the fly by parseTitle the first time.
509 $title = $this->getTitle();
510 $action = $this->getAction();
513 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
514 wfProfileIn( 'main-try-filecache' );
515 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
516 // Try low-level file cache hit
517 $cache = HTMLFileCache
::newFromTitle( $title, $action );
518 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
519 // Check incoming headers to see if client has this cached
520 $timestamp = $cache->cacheTimestamp();
521 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
522 $cache->loadFromFileCache( $this->context
);
524 // Do any stats increment/watchlist stuff
525 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
526 // Tell OutputPage that output is taken care of
527 $this->context
->getOutput()->disable();
528 wfProfileOut( 'main-try-filecache' );
529 wfProfileOut( __METHOD__
);
533 wfProfileOut( 'main-try-filecache' );
536 $this->performRequest();
538 // Now commit any transactions, so that unreported errors after
539 // output() don't roll back the whole DB transaction
540 wfGetLBFactory()->commitMasterChanges();
542 // Output everything!
543 $this->context
->getOutput()->output();
545 wfProfileOut( __METHOD__
);
549 * Ends this task peacefully
551 public function restInPeace() {
552 // Do any deferred jobs
553 DeferredUpdates
::doUpdates( 'commit' );
555 // Execute a job from the queue
558 // Log message usage, if $wgAdaptiveMessageCache is set to true
559 MessageCache
::logMessages();
561 // Log profiling data, e.g. in the database or UDP
562 wfLogProfilingData();
564 // Commit and close up!
565 $factory = wfGetLBFactory();
566 $factory->commitMasterChanges();
567 $factory->shutdown();
569 wfDebug( "Request ended normally\n" );
573 * Do a job from the job queue
575 private function doJobs() {
576 global $wgJobRunRate;
578 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
581 if ( $wgJobRunRate < 1 ) {
582 $max = mt_getrandmax();
583 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
588 $n = intval( $wgJobRunRate );
591 while ( $n-- && false != ( $job = Job
::pop() ) ) {
592 $output = $job->toString() . "\n";
593 $t = - microtime( true );
594 $success = $job->run();
595 $t +
= microtime( true );
596 $t = round( $t * 1000 );
598 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
600 $output .= "Success, Time: $t ms\n";
602 wfDebugLog( 'jobqueue', $output );