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->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
440 wfProfileOut( __METHOD__
);
444 * Run the current MediaWiki instance
445 * index.php just calls this
447 public function run() {
449 $this->checkMaxLag();
452 } catch ( ErrorPageError
$e ) {
453 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
454 // they are not internal application faults. As with normal requests, this
455 // should commit, print the output, do deferred updates, jobs, and profiling.
456 wfGetLBFactory()->commitMasterChanges();
457 $e->report(); // display the GUI error
459 if ( function_exists( 'fastcgi_finish_request' ) ) {
460 fastcgi_finish_request();
462 $this->triggerJobs();
463 $this->restInPeace();
464 } catch ( Exception
$e ) {
465 MWExceptionHandler
::handle( $e );
470 * Checks if the request should abort due to a lagged server,
471 * for given maxlag parameter.
474 private function checkMaxLag() {
475 global $wgShowHostnames;
477 wfProfileIn( __METHOD__
);
478 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
479 if ( !is_null( $maxLag ) ) {
480 list( $host, $lag ) = wfGetLB()->getMaxLag();
481 if ( $lag > $maxLag ) {
482 $resp = $this->context
->getRequest()->response();
483 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
484 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
485 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
486 $resp->header( 'Content-Type: text/plain' );
487 if ( $wgShowHostnames ) {
488 echo "Waiting for $host: $lag seconds lagged\n";
490 echo "Waiting for a database server: $lag seconds lagged\n";
493 wfProfileOut( __METHOD__
);
498 wfProfileOut( __METHOD__
);
502 private function main() {
503 global $wgUseFileCache, $wgTitle, $wgUseAjax;
505 wfProfileIn( __METHOD__
);
507 $request = $this->context
->getRequest();
509 // Send Ajax requests to the Ajax dispatcher.
510 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
512 // Set a dummy title, because $wgTitle == null might break things
513 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
514 $this->context
->setTitle( $title );
517 $dispatcher = new AjaxDispatcher();
518 $dispatcher->performAction();
519 wfProfileOut( __METHOD__
);
523 // Get title from request parameters,
524 // is set on the fly by parseTitle the first time.
525 $title = $this->getTitle();
526 $action = $this->getAction();
529 // If the user has forceHTTPS set to true, or if the user
530 // is in a group requiring HTTPS, or if they have the HTTPS
531 // preference set, redirect them to HTTPS.
532 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
533 // isLoggedIn() will do all sorts of weird stuff.
536 $request->getCookie( 'forceHTTPS', '' ) ||
537 // check for prefixed version for currently logged in users
538 $request->getCookie( 'forceHTTPS' ) ||
539 // Avoid checking the user and groups unless it's enabled.
541 $this->context
->getUser()->isLoggedIn()
542 && $this->context
->getUser()->requiresHTTPS()
545 $request->getProtocol() == 'http'
547 $oldUrl = $request->getFullRequestURL();
548 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
550 if ( $request->wasPosted() ) {
551 // This is weird and we'd hope it almost never happens. This
552 // means that a POST came in via HTTP and policy requires us
553 // redirecting to HTTPS. It's likely such a request is going
554 // to fail due to post data being lost, but let's try anyway
555 // and just log the instance.
557 // @todo @fixme See if we could issue a 307 or 308 here, need
558 // to see how clients (automated & browser) behave when we do
559 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
562 // Setup dummy Title, otherwise OutputPage::redirect will fail
563 $title = Title
::newFromText( NS_MAIN
, 'REDIR' );
564 $this->context
->setTitle( $title );
565 $output = $this->context
->getOutput();
566 // Since we only do this redir to change proto, always send a vary header
567 $output->addVaryHeader( 'X-Forwarded-Proto' );
568 $output->redirect( $redirUrl );
570 wfProfileOut( __METHOD__
);
574 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
575 wfProfileIn( 'main-try-filecache' );
576 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
577 // Try low-level file cache hit
578 $cache = HTMLFileCache
::newFromTitle( $title, $action );
579 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
580 // Check incoming headers to see if client has this cached
581 $timestamp = $cache->cacheTimestamp();
582 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
583 $cache->loadFromFileCache( $this->context
);
585 // Do any stats increment/watchlist stuff
586 // Assume we're viewing the latest revision (this should always be the case with file cache)
587 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
588 // Tell OutputPage that output is taken care of
589 $this->context
->getOutput()->disable();
590 wfProfileOut( 'main-try-filecache' );
591 wfProfileOut( __METHOD__
);
595 wfProfileOut( 'main-try-filecache' );
598 // Actually do the work of the request and build up any output
599 $this->performRequest();
601 // Either all DB and deferred updates should happen or none.
602 // The later should not be cancelled due to client disconnect.
603 ignore_user_abort( true );
604 // Now commit any transactions, so that unreported errors after
605 // output() don't roll back the whole DB transaction
606 wfGetLBFactory()->commitMasterChanges();
608 // Output everything!
609 $this->context
->getOutput()->output();
611 wfProfileOut( __METHOD__
);
615 * Ends this task peacefully
617 public function restInPeace() {
618 // Do any deferred jobs
619 DeferredUpdates
::doUpdates( 'commit' );
621 // Log profiling data, e.g. in the database or UDP
622 wfLogProfilingData();
624 // Commit and close up!
625 $factory = wfGetLBFactory();
626 $factory->commitMasterChanges();
627 $factory->shutdown();
629 wfDebug( "Request ended normally\n" );
633 * Potentially open a socket and sent an HTTP request back to the server
634 * to run a specified number of jobs. This registers a callback to cleanup
635 * the socket once it's done.
637 protected function triggerJobs() {
638 global $wgJobRunRate, $wgServer, $wgRunJobsAsync;
640 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
642 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
643 return; // recursion guard
646 $section = new ProfileSection( __METHOD__
);
648 if ( $wgJobRunRate < 1 ) {
649 $max = mt_getrandmax();
650 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
651 return; // the higher $wgJobRunRate, the less likely we return here
655 $n = intval( $wgJobRunRate );
658 if ( !$wgRunJobsAsync ) {
659 // If running jobs asynchronously has been disabled, run the job here
660 // while the user waits
661 SpecialRunJobs
::executeJobs( $n );
666 if ( !JobQueueGroup
::singleton()->queuesHaveJobs( JobQueueGroup
::TYPE_DEFAULT
) ) {
667 return; // do not send request if there are probably no jobs
669 } catch ( JobQueueError
$e ) {
670 MWExceptionHandler
::logException( $e );
671 return; // do not make the site unavailable
674 $query = array( 'title' => 'Special:RunJobs',
675 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() +
5 );
676 $query['signature'] = SpecialRunJobs
::getQuerySignature( $query );
678 $errno = $errstr = null;
679 $info = wfParseUrl( $wgServer );
680 wfSuppressWarnings();
683 isset( $info['port'] ) ?
$info['port'] : 80,
686 // If it takes more than 100ms to connect to ourselves there
687 // is a problem elsewhere.
692 wfDebugLog( 'runJobs', "Failed to start cron API (socket error $errno): $errstr\n" );
693 // Fall back to running the job here while the user waits
694 SpecialRunJobs
::executeJobs( $n );
698 $url = wfAppendQuery( wfScript( 'index' ), $query );
699 $req = "POST $url HTTP/1.1\r\nHost: {$info['host']}\r\nConnection: Close\r\n\r\n";
701 wfDebugLog( 'runJobs', "Running $n job(s) via '$url'\n" );
702 // Send a cron API request to be performed in the background.
703 // Give up if this takes too long to send (which should be rare).
704 stream_set_timeout( $sock, 1 );
705 $bytes = fwrite( $sock, $req );
706 if ( $bytes !== strlen( $req ) ) {
707 wfDebugLog( 'runJobs', "Failed to start cron API (socket write error)\n" );
709 // Do not wait for the response (the script should handle client aborts).
710 // Make sure that we don't close before that script reaches ignore_user_abort().
711 $status = fgets( $sock );
712 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
713 wfDebugLog( 'runJobs', "Failed to start cron API: received '$status'\n" );