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
30 * @todo Fold $output, etc, into this
36 * @param null|WebRequest $x
39 public function request( WebRequest
$x = null ) {
40 $old = $this->context
->getRequest();
41 $this->context
->setRequest( $x );
46 * @param null|OutputPage $x
49 public function output( OutputPage
$x = null ) {
50 $old = $this->context
->getOutput();
51 $this->context
->setOutput( $x );
56 * @param IContextSource|null $context
58 public function __construct( IContextSource
$context = null ) {
60 $context = RequestContext
::getMain();
63 $this->context
= $context;
67 * Parse the request to get the Title object
69 * @return Title Title object to be $wgTitle
71 private function parseTitle() {
74 $request = $this->context
->getRequest();
75 $curid = $request->getInt( 'curid' );
76 $title = $request->getVal( 'title' );
77 $action = $request->getVal( 'action', 'view' );
79 if ( $request->getCheck( 'search' ) ) {
80 // Compatibility with old search URLs which didn't use Special:Search
81 // Just check for presence here, so blank requests still
82 // show the search page when using ugly URLs (bug 8054).
83 $ret = SpecialPage
::getTitleFor( 'Search' );
85 // URLs like this are generated by RC, because rc_title isn't always accurate
86 $ret = Title
::newFromID( $curid );
88 $ret = Title
::newFromURL( $title );
89 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
90 // in wikitext links to tell Parser to make a direct file link
91 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA
) {
92 $ret = Title
::makeTitle( NS_FILE
, $ret->getDBkey() );
94 // Check variant links so that interwiki links don't have to worry
95 // about the possible different language variants
96 if ( count( $wgContLang->getVariants() ) > 1
97 && !is_null( $ret ) && $ret->getArticleID() == 0
99 $wgContLang->findVariantLink( $title, $ret );
103 // If title is not provided, always allow oldid and diff to set the title.
104 // If title is provided, allow oldid and diff to override the title, unless
105 // we are talking about a special page which might use these parameters for
107 if ( $ret === null ||
!$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 // Use the main page as default title if nothing else has been provided
120 && strval( $title ) === ''
121 && !$request->getCheck( 'curid' )
122 && $action !== 'delete'
124 $ret = Title
::newMainPage();
127 if ( $ret === null ||
( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
128 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
135 * Get the Title object that we'll be acting on, as specified in the WebRequest
138 public function getTitle() {
139 if ( $this->context
->getTitle() === null ) {
140 $this->context
->setTitle( $this->parseTitle() );
142 return $this->context
->getTitle();
146 * Returns the name of the action that will be executed.
148 * @return string Action
150 public function getAction() {
151 static $action = null;
153 if ( $action === null ) {
154 $action = Action
::getActionName( $this->context
);
161 * Performs the request.
164 * - local interwiki redirects
169 * @throws MWException|PermissionsError|BadTitleError|HttpError
172 private function performRequest() {
173 global $wgServer, $wgUsePathInfo, $wgTitle;
175 wfProfileIn( __METHOD__
);
177 $request = $this->context
->getRequest();
178 $requestTitle = $title = $this->context
->getTitle();
179 $output = $this->context
->getOutput();
180 $user = $this->context
->getUser();
182 if ( $request->getVal( 'printable' ) === 'yes' ) {
183 $output->setPrintable();
186 $unused = null; // To pass it by reference
187 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
189 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
190 if ( is_null( $title ) ||
( $title->getDBkey() == '' && !$title->isExternal() )
191 ||
$title->isSpecial( 'Badtitle' )
193 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
194 wfProfileOut( __METHOD__
);
195 throw new BadTitleError();
198 // Check user's permissions to read this page.
199 // We have to check here to catch special pages etc.
200 // We will check again in Article::view().
201 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
202 if ( count( $permErrors ) ) {
203 // Bug 32276: allowing the skin to generate output with $wgTitle or
204 // $this->context->title set to the input title would allow anonymous users to
205 // determine whether a page exists, potentially leaking private data. In fact, the
206 // curid and oldid request parameters would allow page titles to be enumerated even
207 // when they are not guessable. So we reset the title to Special:Badtitle before the
208 // permissions error is displayed.
210 // The skin mostly uses $this->context->getTitle() these days, but some extensions
211 // still use $wgTitle.
213 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
214 $this->context
->setTitle( $badTitle );
215 $wgTitle = $badTitle;
217 wfProfileOut( __METHOD__
);
218 throw new PermissionsError( 'read', $permErrors );
221 $pageView = false; // was an article or special page viewed?
223 // Interwiki redirects
224 if ( $title->isExternal() ) {
225 $rdfrom = $request->getVal( 'rdfrom' );
227 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
229 $query = $request->getValues();
230 unset( $query['title'] );
231 $url = $title->getFullURL( $query );
233 // Check for a redirect loop
234 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
237 // 301 so google et al report the target as the actual url.
238 $output->redirect( $url, 301 );
240 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
241 wfProfileOut( __METHOD__
);
242 throw new BadTitleError();
244 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
245 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
246 && ( $request->getVal( 'title' ) === null
247 ||
$title->getPrefixedDBkey() != $request->getVal( 'title' ) )
248 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
249 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) )
251 if ( $title->isSpecialPage() ) {
252 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
254 $title = SpecialPage
::getTitleFor( $name, $subpage );
257 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
258 // Redirect to canonical url, make it a 301 to allow caching
259 if ( $targetUrl == $request->getFullRequestURL() ) {
260 $message = "Redirect loop detected!\n\n" .
261 "This means the wiki got confused about what page was " .
262 "requested; this sometimes happens when moving a wiki " .
263 "to a new server or changing the server configuration.\n\n";
265 if ( $wgUsePathInfo ) {
266 $message .= "The wiki is trying to interpret the page " .
267 "title from the URL path portion (PATH_INFO), which " .
268 "sometimes fails depending on the web server. Try " .
269 "setting \"\$wgUsePathInfo = false;\" in your " .
270 "LocalSettings.php, or check that \$wgArticlePath " .
273 $message .= "Your web server was detected as possibly not " .
274 "supporting URL path components (PATH_INFO) correctly; " .
275 "check your LocalSettings.php for a customized " .
276 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
279 throw new HttpError( 500, $message );
281 $output->setSquidMaxage( 1200 );
282 $output->redirect( $targetUrl, '301' );
285 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
287 // Actions that need to be made when we have a special pages
288 SpecialPageFactory
::executePath( $title, $this->context
);
290 // ...otherwise treat it as an article view. The article
291 // may be a redirect to another article or URL.
292 $article = $this->initializeArticle();
293 if ( is_object( $article ) ) {
295 $this->performAction( $article, $requestTitle );
296 } elseif ( is_string( $article ) ) {
297 $output->redirect( $article );
299 wfProfileOut( __METHOD__
);
300 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
301 . " returned neither an object nor a URL" );
306 // Promote user to any groups they meet the criteria for
307 $user->addAutopromoteOnceGroups( 'onView' );
310 wfProfileOut( __METHOD__
);
314 * Initialize the main Article object for "standard" actions (view, etc)
315 * Create an Article object for the page, following redirects if needed.
317 * @return mixed An Article, or a string to redirect to another URL
319 private function initializeArticle() {
320 global $wgDisableHardRedirects;
322 wfProfileIn( __METHOD__
);
324 $title = $this->context
->getTitle();
325 if ( $this->context
->canUseWikiPage() ) {
326 // Try to use request context wiki page, as there
327 // is already data from db saved in per process
328 // cache there from this->getAction() call.
329 $page = $this->context
->getWikiPage();
330 $article = Article
::newFromWikiPage( $page, $this->context
);
332 // This case should not happen, but just in case.
333 $article = Article
::newFromTitle( $title, $this->context
);
334 $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 * Perform one of the "standard" actions
400 * @param Title $requestTitle The original title, before any redirects were applied
402 private function performAction( Page
$page, Title
$requestTitle ) {
403 global $wgUseSquid, $wgSquidMaxage;
405 wfProfileIn( __METHOD__
);
407 $request = $this->context
->getRequest();
408 $output = $this->context
->getOutput();
409 $title = $this->context
->getTitle();
410 $user = $this->context
->getUser();
412 if ( !wfRunHooks( 'MediaWikiPerformAction',
413 array( $output, $page, $title, $user, $request, $this ) )
415 wfProfileOut( __METHOD__
);
419 $act = $this->getAction();
421 $action = Action
::factory( $act, $page, $this->context
);
423 if ( $action instanceof Action
) {
424 # Let Squid cache things if we can purge them.
426 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
428 $output->setSquidMaxage( $wgSquidMaxage );
432 wfProfileOut( __METHOD__
);
436 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
437 $output->setStatusCode( 404 );
438 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
441 wfProfileOut( __METHOD__
);
445 * Run the current MediaWiki instance
446 * index.php just calls this
448 public function run() {
450 $this->checkMaxLag();
453 } catch ( ErrorPageError
$e ) {
454 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
455 // they are not internal application faults. As with normal requests, this
456 // should commit, print the output, do deferred updates, jobs, and profiling.
457 wfGetLBFactory()->commitMasterChanges();
458 $e->report(); // display the GUI error
460 if ( function_exists( 'fastcgi_finish_request' ) ) {
461 fastcgi_finish_request();
463 $this->triggerJobs();
464 $this->restInPeace();
465 } catch ( Exception
$e ) {
466 MWExceptionHandler
::handle( $e );
471 * Checks if the request should abort due to a lagged server,
472 * for given maxlag parameter.
475 private function checkMaxLag() {
476 global $wgShowHostnames;
478 wfProfileIn( __METHOD__
);
479 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
480 if ( !is_null( $maxLag ) ) {
481 list( $host, $lag ) = wfGetLB()->getMaxLag();
482 if ( $lag > $maxLag ) {
483 $resp = $this->context
->getRequest()->response();
484 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
485 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
486 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
487 $resp->header( 'Content-Type: text/plain' );
488 if ( $wgShowHostnames ) {
489 echo "Waiting for $host: $lag seconds lagged\n";
491 echo "Waiting for a database server: $lag seconds lagged\n";
494 wfProfileOut( __METHOD__
);
499 wfProfileOut( __METHOD__
);
503 private function main() {
504 global $wgUseFileCache, $wgTitle, $wgUseAjax;
506 wfProfileIn( __METHOD__
);
508 $request = $this->context
->getRequest();
510 // Send Ajax requests to the Ajax dispatcher.
511 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
513 // Set a dummy title, because $wgTitle == null might break things
514 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
515 $this->context
->setTitle( $title );
518 $dispatcher = new AjaxDispatcher();
519 $dispatcher->performAction();
520 wfProfileOut( __METHOD__
);
524 // Get title from request parameters,
525 // is set on the fly by parseTitle the first time.
526 $title = $this->getTitle();
527 $action = $this->getAction();
530 // If the user has forceHTTPS set to true, or if the user
531 // is in a group requiring HTTPS, or if they have the HTTPS
532 // preference set, redirect them to HTTPS.
533 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
534 // isLoggedIn() will do all sorts of weird stuff.
536 $request->getProtocol() == 'http' &&
538 $request->getCookie( 'forceHTTPS', '' ) ||
539 // check for prefixed version for currently logged in users
540 $request->getCookie( 'forceHTTPS' ) ||
541 // Avoid checking the user and groups unless it's enabled.
543 $this->context
->getUser()->isLoggedIn()
544 && $this->context
->getUser()->requiresHTTPS()
548 $oldUrl = $request->getFullRequestURL();
549 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
551 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
552 if ( wfRunHooks( 'BeforeHttpsRedirect', array( $this->context
, &$redirUrl ) ) ) {
554 if ( $request->wasPosted() ) {
555 // This is weird and we'd hope it almost never happens. This
556 // means that a POST came in via HTTP and policy requires us
557 // redirecting to HTTPS. It's likely such a request is going
558 // to fail due to post data being lost, but let's try anyway
559 // and just log the instance.
561 // @todo @fixme See if we could issue a 307 or 308 here, need
562 // to see how clients (automated & browser) behave when we do
563 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
565 // Setup dummy Title, otherwise OutputPage::redirect will fail
566 $title = Title
::newFromText( NS_MAIN
, 'REDIR' );
567 $this->context
->setTitle( $title );
568 $output = $this->context
->getOutput();
569 // Since we only do this redir to change proto, always send a vary header
570 $output->addVaryHeader( 'X-Forwarded-Proto' );
571 $output->redirect( $redirUrl );
573 wfProfileOut( __METHOD__
);
578 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
579 wfProfileIn( 'main-try-filecache' );
580 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
581 // Try low-level file cache hit
582 $cache = HTMLFileCache
::newFromTitle( $title, $action );
583 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
584 // Check incoming headers to see if client has this cached
585 $timestamp = $cache->cacheTimestamp();
586 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
587 $cache->loadFromFileCache( $this->context
);
589 // Do any stats increment/watchlist stuff
590 // Assume we're viewing the latest revision (this should always be the case with file cache)
591 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
592 // Tell OutputPage that output is taken care of
593 $this->context
->getOutput()->disable();
594 wfProfileOut( 'main-try-filecache' );
595 wfProfileOut( __METHOD__
);
599 wfProfileOut( 'main-try-filecache' );
602 // Actually do the work of the request and build up any output
603 $this->performRequest();
605 // Either all DB and deferred updates should happen or none.
606 // The later should not be cancelled due to client disconnect.
607 ignore_user_abort( true );
608 // Now commit any transactions, so that unreported errors after
609 // output() don't roll back the whole DB transaction
610 wfGetLBFactory()->commitMasterChanges();
612 // Output everything!
613 $this->context
->getOutput()->output();
615 wfProfileOut( __METHOD__
);
619 * Ends this task peacefully
621 public function restInPeace() {
622 // Do any deferred jobs
623 DeferredUpdates
::doUpdates( 'commit' );
625 // Log profiling data, e.g. in the database or UDP
626 wfLogProfilingData();
628 // Commit and close up!
629 $factory = wfGetLBFactory();
630 $factory->commitMasterChanges();
631 $factory->shutdown();
633 wfDebug( "Request ended normally\n" );
637 * Potentially open a socket and sent an HTTP request back to the server
638 * to run a specified number of jobs. This registers a callback to cleanup
639 * the socket once it's done.
641 protected function triggerJobs() {
642 global $wgJobRunRate, $wgServer, $wgRunJobsAsync;
644 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
646 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
647 return; // recursion guard
650 $section = new ProfileSection( __METHOD__
);
652 if ( $wgJobRunRate < 1 ) {
653 $max = mt_getrandmax();
654 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
655 return; // the higher $wgJobRunRate, the less likely we return here
659 $n = intval( $wgJobRunRate );
662 if ( !$wgRunJobsAsync ) {
663 // If running jobs asynchronously has been disabled, run the job here
664 // while the user waits
665 SpecialRunJobs
::executeJobs( $n );
670 if ( !JobQueueGroup
::singleton()->queuesHaveJobs( JobQueueGroup
::TYPE_DEFAULT
) ) {
671 return; // do not send request if there are probably no jobs
673 } catch ( JobQueueError
$e ) {
674 MWExceptionHandler
::logException( $e );
675 return; // do not make the site unavailable
678 $query = array( 'title' => 'Special:RunJobs',
679 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() +
5 );
680 $query['signature'] = SpecialRunJobs
::getQuerySignature( $query );
682 $errno = $errstr = null;
683 $info = wfParseUrl( $wgServer );
684 wfSuppressWarnings();
687 isset( $info['port'] ) ?
$info['port'] : 80,
690 // If it takes more than 100ms to connect to ourselves there
691 // is a problem elsewhere.
696 wfDebugLog( 'runJobs', "Failed to start cron API (socket error $errno): $errstr\n" );
697 // Fall back to running the job here while the user waits
698 SpecialRunJobs
::executeJobs( $n );
702 $url = wfAppendQuery( wfScript( 'index' ), $query );
703 $req = "POST $url HTTP/1.1\r\nHost: {$info['host']}\r\nConnection: Close\r\n\r\n";
705 wfDebugLog( 'runJobs', "Running $n job(s) via '$url'\n" );
706 // Send a cron API request to be performed in the background.
707 // Give up if this takes too long to send (which should be rare).
708 stream_set_timeout( $sock, 1 );
709 $bytes = fwrite( $sock, $req );
710 if ( $bytes !== strlen( $req ) ) {
711 wfDebugLog( 'runJobs', "Failed to start cron API (socket write error)\n" );
713 // Do not wait for the response (the script should handle client aborts).
714 // Make sure that we don't close before that script reaches ignore_user_abort().
715 $status = fgets( $sock );
716 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
717 wfDebugLog( 'runJobs', "Failed to start cron API: received '$status'\n" );