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
172 * @throws MWException|PermissionsError|BadTitleError|HttpError
175 private function performRequest() {
176 global $wgServer, $wgUsePathInfo, $wgTitle;
178 wfProfileIn( __METHOD__
);
180 $request = $this->context
->getRequest();
181 $requestTitle = $title = $this->context
->getTitle();
182 $output = $this->context
->getOutput();
183 $user = $this->context
->getUser();
185 if ( $request->getVal( 'printable' ) === 'yes' ) {
186 $output->setPrintable();
189 $unused = null; // To pass it by reference
190 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
192 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
193 if ( is_null( $title ) ||
( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
194 $title->isSpecial( 'Badtitle' ) )
196 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
197 wfProfileOut( __METHOD__
);
198 throw new BadTitleError();
201 // Check user's permissions to read this page.
202 // We have to check here to catch special pages etc.
203 // We will check again in Article::view().
204 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
205 if ( count( $permErrors ) ) {
206 // Bug 32276: allowing the skin to generate output with $wgTitle or
207 // $this->context->title set to the input title would allow anonymous users to
208 // determine whether a page exists, potentially leaking private data. In fact, the
209 // curid and oldid request parameters would allow page titles to be enumerated even
210 // when they are not guessable. So we reset the title to Special:Badtitle before the
211 // permissions error is displayed.
213 // The skin mostly uses $this->context->getTitle() these days, but some extensions
214 // still use $wgTitle.
216 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
217 $this->context
->setTitle( $badTitle );
218 $wgTitle = $badTitle;
220 wfProfileOut( __METHOD__
);
221 throw new PermissionsError( 'read', $permErrors );
224 $pageView = false; // was an article or special page viewed?
226 // Interwiki redirects
227 if ( $title->getInterwiki() != '' ) {
228 $rdfrom = $request->getVal( 'rdfrom' );
230 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
232 $query = $request->getValues();
233 unset( $query['title'] );
234 $url = $title->getFullURL( $query );
236 // Check for a redirect loop
237 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
238 && $title->isLocal() )
240 // 301 so google et al report the target as the actual url.
241 $output->redirect( $url, 301 );
243 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
244 wfProfileOut( __METHOD__
);
245 throw new BadTitleError();
247 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
248 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
249 && ( $request->getVal( 'title' ) === null ||
250 $title->getPrefixedDBkey() != $request->getVal( 'title' ) )
251 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
252 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
254 if ( $title->isSpecialPage() ) {
255 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
257 $title = SpecialPage
::getTitleFor( $name, $subpage );
260 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
261 // Redirect to canonical url, make it a 301 to allow caching
262 if ( $targetUrl == $request->getFullRequestURL() ) {
263 $message = "Redirect loop detected!\n\n" .
264 "This means the wiki got confused about what page was " .
265 "requested; this sometimes happens when moving a wiki " .
266 "to a new server or changing the server configuration.\n\n";
268 if ( $wgUsePathInfo ) {
269 $message .= "The wiki is trying to interpret the page " .
270 "title from the URL path portion (PATH_INFO), which " .
271 "sometimes fails depending on the web server. Try " .
272 "setting \"\$wgUsePathInfo = false;\" in your " .
273 "LocalSettings.php, or check that \$wgArticlePath " .
276 $message .= "Your web server was detected as possibly not " .
277 "supporting URL path components (PATH_INFO) correctly; " .
278 "check your LocalSettings.php for a customized " .
279 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
282 throw new HttpError( 500, $message );
284 $output->setSquidMaxage( 1200 );
285 $output->redirect( $targetUrl, '301' );
288 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
290 // Actions that need to be made when we have a special pages
291 SpecialPageFactory
::executePath( $title, $this->context
);
293 // ...otherwise treat it as an article view. The article
294 // may be a redirect to another article or URL.
295 $article = $this->initializeArticle();
296 if ( is_object( $article ) ) {
299 * $wgArticle is deprecated, do not use it.
300 * @deprecated since 1.18
303 $wgArticle = new DeprecatedGlobal( 'wgArticle', $article, '1.18' );
305 $this->performAction( $article, $requestTitle );
306 } elseif ( is_string( $article ) ) {
307 $output->redirect( $article );
309 wfProfileOut( __METHOD__
);
310 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
311 . " returned neither an object nor a URL" );
316 // Promote user to any groups they meet the criteria for
317 $user->addAutopromoteOnceGroups( 'onView' );
320 wfProfileOut( __METHOD__
);
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 if ( $this->context
->canUseWikiPage() ) {
336 // Try to use request context wiki page, as there
337 // is already data from db saved in per process
338 // cache there from this->getAction() call.
339 $page = $this->context
->getWikiPage();
340 $article = Article
::newFromWikiPage( $page, $this->context
);
342 // This case should not happen, but just in case.
343 $article = Article
::newFromTitle( $title, $this->context
);
344 $this->context
->setWikiPage( $article->getPage() );
347 // NS_MEDIAWIKI has no redirects.
348 // It is also used for CSS/JS, so performance matters here...
349 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
350 wfProfileOut( __METHOD__
);
354 $request = $this->context
->getRequest();
356 // Namespace might change when using redirects
357 // Check for redirects ...
358 $action = $request->getVal( 'action', 'view' );
359 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
360 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
361 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
362 !$request->getVal( 'diff' ) && // ... and not when showing diff
363 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
364 // ... and the article is not a non-redirect image page with associated file
365 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
367 // Give extensions a change to ignore/handle redirects as needed
368 $ignoreRedirect = $target = false;
370 wfRunHooks( 'InitializeArticleMaybeRedirect',
371 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
373 // Follow redirects only for... redirects.
374 // If $target is set, then a hook wanted to redirect.
375 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
376 // Is the target already set by an extension?
377 $target = $target ?
$target : $article->followRedirect();
378 if ( is_string( $target ) ) {
379 if ( !$wgDisableHardRedirects ) {
380 // we'll need to redirect
381 wfProfileOut( __METHOD__
);
385 if ( is_object( $target ) ) {
386 // Rewrite environment to redirected article
387 $rarticle = Article
::newFromTitle( $target, $this->context
);
388 $rarticle->loadPageData();
389 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
390 $rarticle->setRedirectedFrom( $title );
391 $article = $rarticle;
392 $this->context
->setTitle( $target );
393 $this->context
->setWikiPage( $article->getPage() );
397 $this->context
->setTitle( $article->getTitle() );
398 $this->context
->setWikiPage( $article->getPage() );
402 wfProfileOut( __METHOD__
);
407 * Perform one of the "standard" actions
410 * @param $requestTitle The original title, before any redirects were applied
412 private function performAction( Page
$page, Title
$requestTitle ) {
413 global $wgUseSquid, $wgSquidMaxage;
415 wfProfileIn( __METHOD__
);
417 $request = $this->context
->getRequest();
418 $output = $this->context
->getOutput();
419 $title = $this->context
->getTitle();
420 $user = $this->context
->getUser();
422 if ( !wfRunHooks( 'MediaWikiPerformAction',
423 array( $output, $page, $title, $user, $request, $this ) ) )
425 wfProfileOut( __METHOD__
);
429 $act = $this->getAction();
431 $action = Action
::factory( $act, $page );
432 if ( $action instanceof Action
) {
433 # Let Squid cache things if we can purge them.
435 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
437 $output->setSquidMaxage( $wgSquidMaxage );
441 wfProfileOut( __METHOD__
);
445 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
446 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
449 wfProfileOut( __METHOD__
);
453 * Run the current MediaWiki instance
454 * index.php just calls this
456 public function run() {
458 $this->checkMaxLag();
460 $this->restInPeace();
461 } catch ( Exception
$e ) {
462 MWExceptionHandler
::handle( $e );
467 * Checks if the request should abort due to a lagged server,
468 * for given maxlag parameter.
471 private function checkMaxLag() {
472 global $wgShowHostnames;
474 wfProfileIn( __METHOD__
);
475 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
476 if ( !is_null( $maxLag ) ) {
477 list( $host, $lag ) = wfGetLB()->getMaxLag();
478 if ( $lag > $maxLag ) {
479 $resp = $this->context
->getRequest()->response();
480 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
481 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
482 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
483 $resp->header( 'Content-Type: text/plain' );
484 if ( $wgShowHostnames ) {
485 echo "Waiting for $host: $lag seconds lagged\n";
487 echo "Waiting for a database server: $lag seconds lagged\n";
490 wfProfileOut( __METHOD__
);
495 wfProfileOut( __METHOD__
);
499 private function main() {
500 global $wgUseFileCache, $wgTitle, $wgUseAjax;
502 wfProfileIn( __METHOD__
);
504 $request = $this->context
->getRequest();
506 // If the user has forceHTTPS set to true, or if the user
507 // is in a group requiring HTTPS, or if they have the HTTPS
508 // preference set, redirect them to HTTPS.
511 $request->getCookie( 'forceHTTPS' ) ||
512 // Avoid checking the user and groups unless it's enabled.
514 $this->context
->getUser()->isLoggedIn()
515 && $this->context
->getUser()->requiresHTTPS()
518 $request->detectProtocol() == 'http'
520 $oldUrl = $request->getFullRequestURL();
521 $redirUrl = str_replace( 'http://', 'https://', $oldUrl );
523 if ( $request->wasPosted() ) {
524 // This is weird and we'd hope it almost never happens. This
525 // means that a POST came in via HTTP and policy requires us
526 // redirecting to HTTPS. It's likely such a request is going
527 // to fail due to post data being lost, but let's try anyway
528 // and just log the instance.
530 // @todo @fixme See if we could issue a 307 or 308 here, need
531 // to see how clients (automated & browser) behave when we do
532 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
535 // Setup dummy Title, otherwise OutputPage::redirect will fail
536 $title = Title
::newFromText( NS_MAIN
, 'REDIR' );
537 $this->context
->setTitle( $title );
538 $output = $this->context
->getOutput();
539 $output->redirect( $redirUrl );
541 wfProfileOut( __METHOD__
);
545 // Send Ajax requests to the Ajax dispatcher.
546 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
548 // Set a dummy title, because $wgTitle == null might break things
549 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
550 $this->context
->setTitle( $title );
553 $dispatcher = new AjaxDispatcher();
554 $dispatcher->performAction();
555 wfProfileOut( __METHOD__
);
559 // Get title from request parameters,
560 // is set on the fly by parseTitle the first time.
561 $title = $this->getTitle();
562 $action = $this->getAction();
565 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
566 wfProfileIn( 'main-try-filecache' );
567 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
568 // Try low-level file cache hit
569 $cache = HTMLFileCache
::newFromTitle( $title, $action );
570 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
571 // Check incoming headers to see if client has this cached
572 $timestamp = $cache->cacheTimestamp();
573 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
574 $cache->loadFromFileCache( $this->context
);
576 // Do any stats increment/watchlist stuff
577 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
578 // Tell OutputPage that output is taken care of
579 $this->context
->getOutput()->disable();
580 wfProfileOut( 'main-try-filecache' );
581 wfProfileOut( __METHOD__
);
585 wfProfileOut( 'main-try-filecache' );
588 $this->performRequest();
590 // Now commit any transactions, so that unreported errors after
591 // output() don't roll back the whole DB transaction
592 wfGetLBFactory()->commitMasterChanges();
594 // Output everything!
595 $this->context
->getOutput()->output();
597 wfProfileOut( __METHOD__
);
601 * Ends this task peacefully
603 public function restInPeace() {
604 // Do any deferred jobs
605 DeferredUpdates
::doUpdates( 'commit' );
607 // Execute a job from the queue
610 // Log profiling data, e.g. in the database or UDP
611 wfLogProfilingData();
613 // Commit and close up!
614 $factory = wfGetLBFactory();
615 $factory->commitMasterChanges();
616 $factory->shutdown();
618 wfDebug( "Request ended normally\n" );
622 * Do a job from the job queue
624 private function doJobs() {
625 global $wgJobRunRate, $wgPhpCli, $IP;
627 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
631 if ( $wgJobRunRate < 1 ) {
632 $max = mt_getrandmax();
633 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
634 return; // the higher $wgJobRunRate, the less likely we return here
638 $n = intval( $wgJobRunRate );
641 if ( !wfShellExecDisabled() && is_executable( $wgPhpCli ) ) {
642 // Start a background process to run some of the jobs.
643 // This will be asynchronous on *nix though not on Windows.
644 wfProfileIn( __METHOD__
. '-exec' );
646 $cmd = wfShellWikiCmd( "$IP/maintenance/runJobs.php", array( '--maxjobs', $n ) );
647 wfShellExec( "$cmd &", $retVal );
648 wfProfileOut( __METHOD__
. '-exec' );
651 // Fallback to running the jobs here while the user waits
652 $group = JobQueueGroup
::singleton();
654 $job = $group->pop( JobQueueGroup
::USE_CACHE
); // job from any queue
656 $output = $job->toString() . "\n";
657 $t = - microtime( true );
658 wfProfileIn( __METHOD__
. '-' . get_class( $job ) );
659 $success = $job->run();
660 wfProfileOut( __METHOD__
. '-' . get_class( $job ) );
661 $group->ack( $job ); // done
662 $t +
= microtime( true );
663 $t = round( $t * 1000 );
664 if ( $success === false ) {
665 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
667 $output .= "Success, Time: $t ms\n";
669 wfDebugLog( 'jobqueue', $output );
671 } while ( --$n && $job );
672 } catch ( MWException
$e ) {
673 // We don't want exceptions thrown during job execution to
674 // be reported to the user since the output is already sent.
675 // Instead we just log them.
676 wfDebugLog( 'exception', $e->getLogMessage() );