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();
42 $this->context
->setRequest( $x );
48 * @param null|OutputPage $x
51 public function output( OutputPage
$x = null ) {
52 $old = $this->context
->getOutput();
54 $this->context
->setOutput( $x );
60 * @param IContextSource|null $context
62 public function __construct( IContextSource
$context = null ) {
64 $context = RequestContext
::getMain();
67 $this->context
= $context;
71 * Parse the request to get the Title object
73 * @return Title Title object to be $wgTitle
75 private function parseTitle() {
78 $request = $this->context
->getRequest();
79 $curid = $request->getInt( 'curid' );
80 $title = $request->getVal( 'title' );
81 $action = $request->getVal( 'action', 'view' );
83 if ( $request->getCheck( 'search' ) ) {
84 // Compatibility with old search URLs which didn't use Special:Search
85 // Just check for presence here, so blank requests still
86 // show the search page when using ugly URLs (bug 8054).
87 $ret = SpecialPage
::getTitleFor( 'Search' );
89 // URLs like this are generated by RC, because rc_title isn't always accurate
90 $ret = Title
::newFromID( $curid );
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 );
107 // If title is not provided, always allow oldid and diff to set the title.
108 // If title is provided, allow oldid and diff to override the title, unless
109 // we are talking about a special page which might use these parameters for
111 if ( $ret === null ||
!$ret->isSpecialPage() ) {
112 // We can have urls with just ?diff=,?oldid= or even just ?diff=
113 $oldid = $request->getInt( 'oldid' );
114 $oldid = $oldid ?
$oldid : $request->getInt( 'diff' );
115 // Allow oldid to override a changed or missing title
117 $rev = Revision
::newFromId( $oldid );
118 $ret = $rev ?
$rev->getTitle() : $ret;
122 // Use the main page as default title if nothing else has been provided
124 && strval( $title ) === ''
125 && !$request->getCheck( 'curid' )
126 && $action !== 'delete'
128 $ret = Title
::newMainPage();
131 if ( $ret === null ||
( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
132 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
139 * Get the Title object that we'll be acting on, as specified in the WebRequest
142 public function getTitle() {
143 if ( $this->context
->getTitle() === null ) {
144 $this->context
->setTitle( $this->parseTitle() );
146 return $this->context
->getTitle();
150 * Returns the name of the action that will be executed.
152 * @return string Action
154 public function getAction() {
155 static $action = null;
157 if ( $action === null ) {
158 $action = Action
::getActionName( $this->context
);
165 * Performs the request.
168 * - local interwiki redirects
173 * @throws MWException|PermissionsError|BadTitleError|HttpError
176 private function performRequest() {
177 global $wgServer, $wgUsePathInfo, $wgTitle;
179 wfProfileIn( __METHOD__
);
181 $request = $this->context
->getRequest();
182 $requestTitle = $title = $this->context
->getTitle();
183 $output = $this->context
->getOutput();
184 $user = $this->context
->getUser();
186 if ( $request->getVal( 'printable' ) === 'yes' ) {
187 $output->setPrintable();
190 $unused = null; // To pass it by reference
191 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
193 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
194 if ( is_null( $title ) ||
( $title->getDBkey() == '' && !$title->isExternal() )
195 ||
$title->isSpecial( 'Badtitle' )
197 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
198 wfProfileOut( __METHOD__
);
199 throw new BadTitleError();
202 // Check user's permissions to read this page.
203 // We have to check here to catch special pages etc.
204 // We will check again in Article::view().
205 $permErrors = $title->isSpecial( 'RunJobs' )
206 ?
array() // relies on HMAC key signature alone
207 : $title->getUserPermissionsErrors( 'read', $user );
208 if ( count( $permErrors ) ) {
209 // Bug 32276: allowing the skin to generate output with $wgTitle or
210 // $this->context->title set to the input title would allow anonymous users to
211 // determine whether a page exists, potentially leaking private data. In fact, the
212 // curid and oldid request parameters would allow page titles to be enumerated even
213 // when they are not guessable. So we reset the title to Special:Badtitle before the
214 // permissions error is displayed.
216 // The skin mostly uses $this->context->getTitle() these days, but some extensions
217 // still use $wgTitle.
219 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
220 $this->context
->setTitle( $badTitle );
221 $wgTitle = $badTitle;
223 wfProfileOut( __METHOD__
);
224 throw new PermissionsError( 'read', $permErrors );
227 $pageView = false; // was an article or special page viewed?
229 // Interwiki redirects
230 if ( $title->isExternal() ) {
231 $rdfrom = $request->getVal( 'rdfrom' );
233 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
235 $query = $request->getValues();
236 unset( $query['title'] );
237 $url = $title->getFullURL( $query );
239 // Check for a redirect loop
240 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
243 // 301 so google et al report the target as the actual url.
244 $output->redirect( $url, 301 );
246 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
247 wfProfileOut( __METHOD__
);
248 throw new BadTitleError();
250 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
251 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
252 && ( $request->getVal( 'title' ) === null
253 ||
$title->getPrefixedDBkey() != $request->getVal( 'title' ) )
254 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
255 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) )
257 if ( $title->isSpecialPage() ) {
258 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
260 $title = SpecialPage
::getTitleFor( $name, $subpage );
263 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
264 // Redirect to canonical url, make it a 301 to allow caching
265 if ( $targetUrl == $request->getFullRequestURL() ) {
266 $message = "Redirect loop detected!\n\n" .
267 "This means the wiki got confused about what page was " .
268 "requested; this sometimes happens when moving a wiki " .
269 "to a new server or changing the server configuration.\n\n";
271 if ( $wgUsePathInfo ) {
272 $message .= "The wiki is trying to interpret the page " .
273 "title from the URL path portion (PATH_INFO), which " .
274 "sometimes fails depending on the web server. Try " .
275 "setting \"\$wgUsePathInfo = false;\" in your " .
276 "LocalSettings.php, or check that \$wgArticlePath " .
279 $message .= "Your web server was detected as possibly not " .
280 "supporting URL path components (PATH_INFO) correctly; " .
281 "check your LocalSettings.php for a customized " .
282 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
285 throw new HttpError( 500, $message );
287 $output->setSquidMaxage( 1200 );
288 $output->redirect( $targetUrl, '301' );
291 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
293 // Actions that need to be made when we have a special pages
294 SpecialPageFactory
::executePath( $title, $this->context
);
296 // ...otherwise treat it as an article view. The article
297 // may be a redirect to another article or URL.
298 $article = $this->initializeArticle();
299 if ( is_object( $article ) ) {
301 $this->performAction( $article, $requestTitle );
302 } elseif ( is_string( $article ) ) {
303 $output->redirect( $article );
305 wfProfileOut( __METHOD__
);
306 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
307 . " returned neither an object nor a URL" );
312 // Promote user to any groups they meet the criteria for
313 $user->addAutopromoteOnceGroups( 'onView' );
316 wfProfileOut( __METHOD__
);
320 * Initialize the main Article object for "standard" actions (view, etc)
321 * Create an Article object for the page, following redirects if needed.
323 * @return mixed An Article, or a string to redirect to another URL
325 private function initializeArticle() {
326 global $wgDisableHardRedirects;
328 wfProfileIn( __METHOD__
);
330 $title = $this->context
->getTitle();
331 if ( $this->context
->canUseWikiPage() ) {
332 // Try to use request context wiki page, as there
333 // is already data from db saved in per process
334 // cache there from this->getAction() call.
335 $page = $this->context
->getWikiPage();
336 $article = Article
::newFromWikiPage( $page, $this->context
);
338 // This case should not happen, but just in case.
339 $article = Article
::newFromTitle( $title, $this->context
);
340 $this->context
->setWikiPage( $article->getPage() );
343 // NS_MEDIAWIKI has no redirects.
344 // It is also used for CSS/JS, so performance matters here...
345 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
346 wfProfileOut( __METHOD__
);
350 $request = $this->context
->getRequest();
352 // Namespace might change when using redirects
353 // Check for redirects ...
354 $action = $request->getVal( 'action', 'view' );
355 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
356 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
357 && !$request->getVal( 'oldid' ) // ... and are not old revisions
358 && !$request->getVal( 'diff' ) // ... and not when showing diff
359 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
360 // ... and the article is not a non-redirect image page with associated file
361 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
363 // Give extensions a change to ignore/handle redirects as needed
364 $ignoreRedirect = $target = false;
366 wfRunHooks( 'InitializeArticleMaybeRedirect',
367 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
369 // Follow redirects only for... redirects.
370 // If $target is set, then a hook wanted to redirect.
371 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
372 // Is the target already set by an extension?
373 $target = $target ?
$target : $article->followRedirect();
374 if ( is_string( $target ) ) {
375 if ( !$wgDisableHardRedirects ) {
376 // we'll need to redirect
377 wfProfileOut( __METHOD__
);
381 if ( is_object( $target ) ) {
382 // Rewrite environment to redirected article
383 $rarticle = Article
::newFromTitle( $target, $this->context
);
384 $rarticle->loadPageData();
385 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
386 $rarticle->setRedirectedFrom( $title );
387 $article = $rarticle;
388 $this->context
->setTitle( $target );
389 $this->context
->setWikiPage( $article->getPage() );
393 $this->context
->setTitle( $article->getTitle() );
394 $this->context
->setWikiPage( $article->getPage() );
398 wfProfileOut( __METHOD__
);
403 * Perform one of the "standard" actions
406 * @param Title $requestTitle The original title, before any redirects were applied
408 private function performAction( Page
$page, Title
$requestTitle ) {
409 global $wgUseSquid, $wgSquidMaxage;
411 wfProfileIn( __METHOD__
);
413 $request = $this->context
->getRequest();
414 $output = $this->context
->getOutput();
415 $title = $this->context
->getTitle();
416 $user = $this->context
->getUser();
418 if ( !wfRunHooks( 'MediaWikiPerformAction',
419 array( $output, $page, $title, $user, $request, $this ) )
421 wfProfileOut( __METHOD__
);
425 $act = $this->getAction();
427 $action = Action
::factory( $act, $page, $this->context
);
429 if ( $action instanceof Action
) {
430 # Let Squid cache things if we can purge them.
432 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
434 $output->setSquidMaxage( $wgSquidMaxage );
438 wfProfileOut( __METHOD__
);
442 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
443 $output->setStatusCode( 404 );
444 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
447 wfProfileOut( __METHOD__
);
451 * Run the current MediaWiki instance
452 * index.php just calls this
454 public function run() {
456 $this->checkMaxLag();
459 } catch ( ErrorPageError
$e ) {
460 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
461 // they are not internal application faults. As with normal requests, this
462 // should commit, print the output, do deferred updates, jobs, and profiling.
463 wfGetLBFactory()->commitMasterChanges();
464 $e->report(); // display the GUI error
466 if ( function_exists( 'fastcgi_finish_request' ) ) {
467 fastcgi_finish_request();
469 $this->triggerJobs();
470 $this->restInPeace();
471 } catch ( Exception
$e ) {
472 MWExceptionHandler
::handle( $e );
477 * Checks if the request should abort due to a lagged server,
478 * for given maxlag parameter.
481 private function checkMaxLag() {
482 global $wgShowHostnames;
484 wfProfileIn( __METHOD__
);
485 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
486 if ( !is_null( $maxLag ) ) {
487 list( $host, $lag ) = wfGetLB()->getMaxLag();
488 if ( $lag > $maxLag ) {
489 $resp = $this->context
->getRequest()->response();
490 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
491 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
492 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
493 $resp->header( 'Content-Type: text/plain' );
494 if ( $wgShowHostnames ) {
495 echo "Waiting for $host: $lag seconds lagged\n";
497 echo "Waiting for a database server: $lag seconds lagged\n";
500 wfProfileOut( __METHOD__
);
505 wfProfileOut( __METHOD__
);
509 private function main() {
510 global $wgUseFileCache, $wgTitle, $wgUseAjax;
512 wfProfileIn( __METHOD__
);
514 $request = $this->context
->getRequest();
516 // Send Ajax requests to the Ajax dispatcher.
517 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
519 // Set a dummy title, because $wgTitle == null might break things
520 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
521 $this->context
->setTitle( $title );
524 $dispatcher = new AjaxDispatcher();
525 $dispatcher->performAction();
526 wfProfileOut( __METHOD__
);
530 // Get title from request parameters,
531 // is set on the fly by parseTitle the first time.
532 $title = $this->getTitle();
533 $action = $this->getAction();
536 // If the user has forceHTTPS set to true, or if the user
537 // is in a group requiring HTTPS, or if they have the HTTPS
538 // preference set, redirect them to HTTPS.
539 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
540 // isLoggedIn() will do all sorts of weird stuff.
542 $request->getProtocol() == 'http' &&
544 $request->getCookie( 'forceHTTPS', '' ) ||
545 // check for prefixed version for currently logged in users
546 $request->getCookie( 'forceHTTPS' ) ||
547 // Avoid checking the user and groups unless it's enabled.
549 $this->context
->getUser()->isLoggedIn()
550 && $this->context
->getUser()->requiresHTTPS()
554 $oldUrl = $request->getFullRequestURL();
555 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
557 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
558 if ( wfRunHooks( 'BeforeHttpsRedirect', array( $this->context
, &$redirUrl ) ) ) {
560 if ( $request->wasPosted() ) {
561 // This is weird and we'd hope it almost never happens. This
562 // means that a POST came in via HTTP and policy requires us
563 // redirecting to HTTPS. It's likely such a request is going
564 // to fail due to post data being lost, but let's try anyway
565 // and just log the instance.
567 // @todo FIXME: See if we could issue a 307 or 308 here, need
568 // to see how clients (automated & browser) behave when we do
569 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
571 // Setup dummy Title, otherwise OutputPage::redirect will fail
572 $title = Title
::newFromText( NS_MAIN
, 'REDIR' );
573 $this->context
->setTitle( $title );
574 $output = $this->context
->getOutput();
575 // Since we only do this redir to change proto, always send a vary header
576 $output->addVaryHeader( 'X-Forwarded-Proto' );
577 $output->redirect( $redirUrl );
579 wfProfileOut( __METHOD__
);
584 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
585 wfProfileIn( 'main-try-filecache' );
586 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
587 // Try low-level file cache hit
588 $cache = HTMLFileCache
::newFromTitle( $title, $action );
589 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
590 // Check incoming headers to see if client has this cached
591 $timestamp = $cache->cacheTimestamp();
592 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
593 $cache->loadFromFileCache( $this->context
);
595 // Do any stats increment/watchlist stuff
596 // Assume we're viewing the latest revision (this should always be the case with file cache)
597 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
598 // Tell OutputPage that output is taken care of
599 $this->context
->getOutput()->disable();
600 wfProfileOut( 'main-try-filecache' );
601 wfProfileOut( __METHOD__
);
605 wfProfileOut( 'main-try-filecache' );
608 // Actually do the work of the request and build up any output
609 $this->performRequest();
611 // Either all DB and deferred updates should happen or none.
612 // The later should not be cancelled due to client disconnect.
613 ignore_user_abort( true );
614 // Now commit any transactions, so that unreported errors after
615 // output() don't roll back the whole DB transaction
616 wfGetLBFactory()->commitMasterChanges();
618 // Output everything!
619 $this->context
->getOutput()->output();
621 wfProfileOut( __METHOD__
);
625 * Ends this task peacefully
627 public function restInPeace() {
628 // Do any deferred jobs
629 DeferredUpdates
::doUpdates( 'commit' );
631 // Log profiling data, e.g. in the database or UDP
632 wfLogProfilingData();
634 // Commit and close up!
635 $factory = wfGetLBFactory();
636 $factory->commitMasterChanges();
637 $factory->shutdown();
639 wfDebug( "Request ended normally\n" );
643 * Potentially open a socket and sent an HTTP request back to the server
644 * to run a specified number of jobs. This registers a callback to cleanup
645 * the socket once it's done.
647 protected function triggerJobs() {
648 global $wgJobRunRate, $wgServer, $wgRunJobsAsync;
650 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
652 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
653 return; // recursion guard
656 $section = new ProfileSection( __METHOD__
);
658 if ( $wgJobRunRate < 1 ) {
659 $max = mt_getrandmax();
660 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
661 return; // the higher $wgJobRunRate, the less likely we return here
665 $n = intval( $wgJobRunRate );
668 if ( !$wgRunJobsAsync ) {
669 // Fall back to running the job here while the user waits
670 $runner = new JobRunner();
671 $runner->run( array( 'maxJobs' => $n ) );
676 if ( !JobQueueGroup
::singleton()->queuesHaveJobs( JobQueueGroup
::TYPE_DEFAULT
) ) {
677 return; // do not send request if there are probably no jobs
679 } catch ( JobQueueError
$e ) {
680 MWExceptionHandler
::logException( $e );
681 return; // do not make the site unavailable
684 $query = array( 'title' => 'Special:RunJobs',
685 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() +
5 );
686 $query['signature'] = SpecialRunJobs
::getQuerySignature( $query );
688 $errno = $errstr = null;
689 $info = wfParseUrl( $wgServer );
690 wfSuppressWarnings();
693 isset( $info['port'] ) ?
$info['port'] : 80,
696 // If it takes more than 100ms to connect to ourselves there
697 // is a problem elsewhere.
702 wfDebugLog( 'runJobs', "Failed to start cron API (socket error $errno): $errstr\n" );
703 // Fall back to running the job here while the user waits
704 $runner = new JobRunner();
705 $runner->run( array( 'maxJobs' => $n ) );
709 $url = wfAppendQuery( wfScript( 'index' ), $query );
710 $req = "POST $url HTTP/1.1\r\nHost: {$info['host']}\r\nConnection: Close\r\n\r\n";
712 wfDebugLog( 'runJobs', "Running $n job(s) via '$url'\n" );
713 // Send a cron API request to be performed in the background.
714 // Give up if this takes too long to send (which should be rare).
715 stream_set_timeout( $sock, 1 );
716 $bytes = fwrite( $sock, $req );
717 if ( $bytes !== strlen( $req ) ) {
718 wfDebugLog( 'runJobs', "Failed to start cron API (socket write error)\n" );
720 // Do not wait for the response (the script should handle client aborts).
721 // Make sure that we don't close before that script reaches ignore_user_abort().
722 $status = fgets( $sock );
723 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
724 wfDebugLog( 'runJobs', "Failed to start cron API: received '$status'\n" );