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.
38 * @param IContextSource|null $context
40 public function __construct( IContextSource
$context = null ) {
42 $context = RequestContext
::getMain();
45 $this->context
= $context;
46 $this->config
= $context->getConfig();
50 * Parse the request to get the Title object
52 * @return Title Title object to be $wgTitle
54 private function parseTitle() {
57 $request = $this->context
->getRequest();
58 $curid = $request->getInt( 'curid' );
59 $title = $request->getVal( 'title' );
60 $action = $request->getVal( 'action', 'view' );
62 if ( $request->getCheck( 'search' ) ) {
63 // Compatibility with old search URLs which didn't use Special:Search
64 // Just check for presence here, so blank requests still
65 // show the search page when using ugly URLs (bug 8054).
66 $ret = SpecialPage
::getTitleFor( 'Search' );
68 // URLs like this are generated by RC, because rc_title isn't always accurate
69 $ret = Title
::newFromID( $curid );
71 $ret = Title
::newFromURL( $title );
72 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
73 // in wikitext links to tell Parser to make a direct file link
74 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA
) {
75 $ret = Title
::makeTitle( NS_FILE
, $ret->getDBkey() );
77 // Check variant links so that interwiki links don't have to worry
78 // about the possible different language variants
79 if ( count( $wgContLang->getVariants() ) > 1
80 && !is_null( $ret ) && $ret->getArticleID() == 0
82 $wgContLang->findVariantLink( $title, $ret );
86 // If title is not provided, always allow oldid and diff to set the title.
87 // If title is provided, allow oldid and diff to override the title, unless
88 // we are talking about a special page which might use these parameters for
90 if ( $ret === null ||
!$ret->isSpecialPage() ) {
91 // We can have urls with just ?diff=,?oldid= or even just ?diff=
92 $oldid = $request->getInt( 'oldid' );
93 $oldid = $oldid ?
$oldid : $request->getInt( 'diff' );
94 // Allow oldid to override a changed or missing title
96 $rev = Revision
::newFromId( $oldid );
97 $ret = $rev ?
$rev->getTitle() : $ret;
101 // Use the main page as default title if nothing else has been provided
103 && strval( $title ) === ''
104 && !$request->getCheck( 'curid' )
105 && $action !== 'delete'
107 $ret = Title
::newMainPage();
110 if ( $ret === null ||
( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
111 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
118 * Get the Title object that we'll be acting on, as specified in the WebRequest
121 public function getTitle() {
122 if ( !$this->context
->hasTitle() ) {
123 $this->context
->setTitle( $this->parseTitle() );
125 return $this->context
->getTitle();
129 * Returns the name of the action that will be executed.
131 * @return string Action
133 public function getAction() {
134 static $action = null;
136 if ( $action === null ) {
137 $action = Action
::getActionName( $this->context
);
144 * Performs the request.
147 * - local interwiki redirects
152 * @throws MWException|PermissionsError|BadTitleError|HttpError
155 private function performRequest() {
158 wfProfileIn( __METHOD__
);
160 $request = $this->context
->getRequest();
161 $requestTitle = $title = $this->context
->getTitle();
162 $output = $this->context
->getOutput();
163 $user = $this->context
->getUser();
165 if ( $request->getVal( 'printable' ) === 'yes' ) {
166 $output->setPrintable();
169 $unused = null; // To pass it by reference
170 Hooks
::run( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
172 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
173 if ( is_null( $title ) ||
( $title->getDBkey() == '' && !$title->isExternal() )
174 ||
$title->isSpecial( 'Badtitle' )
176 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
177 wfProfileOut( __METHOD__
);
178 throw new BadTitleError();
181 // Check user's permissions to read this page.
182 // We have to check here to catch special pages etc.
183 // We will check again in Article::view().
184 $permErrors = $title->isSpecial( 'RunJobs' )
185 ?
array() // relies on HMAC key signature alone
186 : $title->getUserPermissionsErrors( 'read', $user );
187 if ( count( $permErrors ) ) {
188 // Bug 32276: allowing the skin to generate output with $wgTitle or
189 // $this->context->title set to the input title would allow anonymous users to
190 // determine whether a page exists, potentially leaking private data. In fact, the
191 // curid and oldid request parameters would allow page titles to be enumerated even
192 // when they are not guessable. So we reset the title to Special:Badtitle before the
193 // permissions error is displayed.
195 // The skin mostly uses $this->context->getTitle() these days, but some extensions
196 // still use $wgTitle.
198 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
199 $this->context
->setTitle( $badTitle );
200 $wgTitle = $badTitle;
202 wfProfileOut( __METHOD__
);
203 throw new PermissionsError( 'read', $permErrors );
206 $pageView = false; // was an article or special page viewed?
208 // Interwiki redirects
209 if ( $title->isExternal() ) {
210 $rdfrom = $request->getVal( 'rdfrom' );
212 $url = $title->getFullURL( array( 'rdfrom' => $rdfrom ) );
214 $query = $request->getValues();
215 unset( $query['title'] );
216 $url = $title->getFullURL( $query );
218 // Check for a redirect loop
219 if ( !preg_match( '/^' . preg_quote( $this->config
->get( 'Server' ), '/' ) . '/', $url )
222 // 301 so google et al report the target as the actual url.
223 $output->redirect( $url, 301 );
225 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
226 wfProfileOut( __METHOD__
);
227 throw new BadTitleError();
229 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
230 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
231 && ( $request->getVal( 'title' ) === null
232 ||
$title->getPrefixedDBkey() != $request->getVal( 'title' ) )
233 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
234 && Hooks
::run( 'TestCanonicalRedirect', array( $request, $title, $output ) )
236 if ( $title->isSpecialPage() ) {
237 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
239 $title = SpecialPage
::getTitleFor( $name, $subpage );
242 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
243 // Redirect to canonical url, make it a 301 to allow caching
244 if ( $targetUrl == $request->getFullRequestURL() ) {
245 $message = "Redirect loop detected!\n\n" .
246 "This means the wiki got confused about what page was " .
247 "requested; this sometimes happens when moving a wiki " .
248 "to a new server or changing the server configuration.\n\n";
250 if ( $this->config
->get( 'UsePathInfo' ) ) {
251 $message .= "The wiki is trying to interpret the page " .
252 "title from the URL path portion (PATH_INFO), which " .
253 "sometimes fails depending on the web server. Try " .
254 "setting \"\$wgUsePathInfo = false;\" in your " .
255 "LocalSettings.php, or check that \$wgArticlePath " .
258 $message .= "Your web server was detected as possibly not " .
259 "supporting URL path components (PATH_INFO) correctly; " .
260 "check your LocalSettings.php for a customized " .
261 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
264 throw new HttpError( 500, $message );
266 $output->setSquidMaxage( 1200 );
267 $output->redirect( $targetUrl, '301' );
270 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
272 // Actions that need to be made when we have a special pages
273 SpecialPageFactory
::executePath( $title, $this->context
);
275 // ...otherwise treat it as an article view. The article
276 // may be a redirect to another article or URL.
277 $article = $this->initializeArticle();
278 if ( is_object( $article ) ) {
280 $this->performAction( $article, $requestTitle );
281 } elseif ( is_string( $article ) ) {
282 $output->redirect( $article );
284 wfProfileOut( __METHOD__
);
285 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle()"
286 . " returned neither an object nor a URL" );
291 // Promote user to any groups they meet the criteria for
292 $user->addAutopromoteOnceGroups( 'onView' );
295 wfProfileOut( __METHOD__
);
299 * Initialize the main Article object for "standard" actions (view, etc)
300 * Create an Article object for the page, following redirects if needed.
302 * @return mixed An Article, or a string to redirect to another URL
304 private function initializeArticle() {
305 wfProfileIn( __METHOD__
);
307 $title = $this->context
->getTitle();
308 if ( $this->context
->canUseWikiPage() ) {
309 // Try to use request context wiki page, as there
310 // is already data from db saved in per process
311 // cache there from this->getAction() call.
312 $page = $this->context
->getWikiPage();
313 $article = Article
::newFromWikiPage( $page, $this->context
);
315 // This case should not happen, but just in case.
316 $article = Article
::newFromTitle( $title, $this->context
);
317 $this->context
->setWikiPage( $article->getPage() );
320 // NS_MEDIAWIKI has no redirects.
321 // It is also used for CSS/JS, so performance matters here...
322 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
323 wfProfileOut( __METHOD__
);
327 $request = $this->context
->getRequest();
329 // Namespace might change when using redirects
330 // Check for redirects ...
331 $action = $request->getVal( 'action', 'view' );
332 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
333 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
334 && !$request->getVal( 'oldid' ) // ... and are not old revisions
335 && !$request->getVal( 'diff' ) // ... and not when showing diff
336 && $request->getVal( 'redirect' ) != 'no' // ... unless explicitly told not to
337 // ... and the article is not a non-redirect image page with associated file
338 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
340 // Give extensions a change to ignore/handle redirects as needed
341 $ignoreRedirect = $target = false;
343 Hooks
::run( 'InitializeArticleMaybeRedirect',
344 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
346 // Follow redirects only for... redirects.
347 // If $target is set, then a hook wanted to redirect.
348 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
349 // Is the target already set by an extension?
350 $target = $target ?
$target : $article->followRedirect();
351 if ( is_string( $target ) ) {
352 if ( !$this->config
->get( 'DisableHardRedirects' ) ) {
353 // we'll need to redirect
354 wfProfileOut( __METHOD__
);
358 if ( is_object( $target ) ) {
359 // Rewrite environment to redirected article
360 $rarticle = Article
::newFromTitle( $target, $this->context
);
361 $rarticle->loadPageData();
362 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
363 $rarticle->setRedirectedFrom( $title );
364 $article = $rarticle;
365 $this->context
->setTitle( $target );
366 $this->context
->setWikiPage( $article->getPage() );
370 $this->context
->setTitle( $article->getTitle() );
371 $this->context
->setWikiPage( $article->getPage() );
375 wfProfileOut( __METHOD__
);
380 * Perform one of the "standard" actions
383 * @param Title $requestTitle The original title, before any redirects were applied
385 private function performAction( Page
$page, Title
$requestTitle ) {
386 wfProfileIn( __METHOD__
);
388 $request = $this->context
->getRequest();
389 $output = $this->context
->getOutput();
390 $title = $this->context
->getTitle();
391 $user = $this->context
->getUser();
393 if ( !Hooks
::run( 'MediaWikiPerformAction',
394 array( $output, $page, $title, $user, $request, $this ) )
396 wfProfileOut( __METHOD__
);
400 $act = $this->getAction();
402 $action = Action
::factory( $act, $page, $this->context
);
404 if ( $action instanceof Action
) {
405 # Let Squid cache things if we can purge them.
406 if ( $this->config
->get( 'UseSquid' ) &&
407 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
409 $output->setSquidMaxage( $this->config
->get( 'SquidMaxage' ) );
413 wfProfileOut( __METHOD__
);
417 if ( Hooks
::run( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
418 $output->setStatusCode( 404 );
419 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
422 wfProfileOut( __METHOD__
);
426 * Run the current MediaWiki instance
427 * index.php just calls this
429 public function run() {
431 $this->checkMaxLag();
434 } catch ( ErrorPageError
$e ) {
435 // Bug 62091: while exceptions are convenient to bubble up GUI errors,
436 // they are not internal application faults. As with normal requests, this
437 // should commit, print the output, do deferred updates, jobs, and profiling.
438 wfGetLBFactory()->commitMasterChanges();
439 $e->report(); // display the GUI error
441 if ( function_exists( 'fastcgi_finish_request' ) ) {
442 fastcgi_finish_request();
444 $this->triggerJobs();
445 $this->restInPeace();
446 } catch ( Exception
$e ) {
447 MWExceptionHandler
::handleException( $e );
452 * Checks if the request should abort due to a lagged server,
453 * for given maxlag parameter.
456 private function checkMaxLag() {
457 wfProfileIn( __METHOD__
);
458 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
459 if ( !is_null( $maxLag ) ) {
460 list( $host, $lag ) = wfGetLB()->getMaxLag();
461 if ( $lag > $maxLag ) {
462 $resp = $this->context
->getRequest()->response();
463 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
464 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
465 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
466 $resp->header( 'Content-Type: text/plain' );
467 if ( $this->config
->get( 'ShowHostnames' ) ) {
468 echo "Waiting for $host: $lag seconds lagged\n";
470 echo "Waiting for a database server: $lag seconds lagged\n";
473 wfProfileOut( __METHOD__
);
478 wfProfileOut( __METHOD__
);
482 private function main() {
485 wfProfileIn( __METHOD__
);
487 $request = $this->context
->getRequest();
489 // Send Ajax requests to the Ajax dispatcher.
490 if ( $this->config
->get( 'UseAjax' ) && $request->getVal( 'action', 'view' ) == 'ajax' ) {
492 // Set a dummy title, because $wgTitle == null might break things
493 $title = Title
::makeTitle( NS_MAIN
, 'AJAX' );
494 $this->context
->setTitle( $title );
497 $dispatcher = new AjaxDispatcher( $this->config
);
498 $dispatcher->performAction( $this->context
->getUser() );
499 wfProfileOut( __METHOD__
);
503 // Get title from request parameters,
504 // is set on the fly by parseTitle the first time.
505 $title = $this->getTitle();
506 $action = $this->getAction();
509 // If the user has forceHTTPS set to true, or if the user
510 // is in a group requiring HTTPS, or if they have the HTTPS
511 // preference set, redirect them to HTTPS.
512 // Note: Do this after $wgTitle is setup, otherwise the hooks run from
513 // isLoggedIn() will do all sorts of weird stuff.
515 $request->getProtocol() == 'http' &&
517 $request->getCookie( 'forceHTTPS', '' ) ||
518 // check for prefixed version for currently logged in users
519 $request->getCookie( 'forceHTTPS' ) ||
520 // Avoid checking the user and groups unless it's enabled.
522 $this->context
->getUser()->isLoggedIn()
523 && $this->context
->getUser()->requiresHTTPS()
527 $oldUrl = $request->getFullRequestURL();
528 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
530 // ATTENTION: This hook is likely to be removed soon due to overall design of the system.
531 if ( Hooks
::run( 'BeforeHttpsRedirect', array( $this->context
, &$redirUrl ) ) ) {
533 if ( $request->wasPosted() ) {
534 // This is weird and we'd hope it almost never happens. This
535 // means that a POST came in via HTTP and policy requires us
536 // redirecting to HTTPS. It's likely such a request is going
537 // to fail due to post data being lost, but let's try anyway
538 // and just log the instance.
540 // @todo FIXME: See if we could issue a 307 or 308 here, need
541 // to see how clients (automated & browser) behave when we do
542 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
544 // Setup dummy Title, otherwise OutputPage::redirect will fail
545 $title = Title
::newFromText( NS_MAIN
, 'REDIR' );
546 $this->context
->setTitle( $title );
547 $output = $this->context
->getOutput();
548 // Since we only do this redir to change proto, always send a vary header
549 $output->addVaryHeader( 'X-Forwarded-Proto' );
550 $output->redirect( $redirUrl );
552 wfProfileOut( __METHOD__
);
557 if ( $this->config
->get( 'UseFileCache' ) && $title->getNamespace() >= 0 ) {
558 wfProfileIn( 'main-try-filecache' );
559 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
560 // Try low-level file cache hit
561 $cache = new HTMLFileCache( $title, $action );
562 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
563 // Check incoming headers to see if client has this cached
564 $timestamp = $cache->cacheTimestamp();
565 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
566 $cache->loadFromFileCache( $this->context
);
568 // Do any stats increment/watchlist stuff
569 // Assume we're viewing the latest revision (this should always be the case with file cache)
570 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
571 // Tell OutputPage that output is taken care of
572 $this->context
->getOutput()->disable();
573 wfProfileOut( 'main-try-filecache' );
574 wfProfileOut( __METHOD__
);
578 wfProfileOut( 'main-try-filecache' );
581 // Actually do the work of the request and build up any output
582 $this->performRequest();
584 // Either all DB and deferred updates should happen or none.
585 // The later should not be cancelled due to client disconnect.
586 ignore_user_abort( true );
587 // Now commit any transactions, so that unreported errors after
588 // output() don't roll back the whole DB transaction
589 wfGetLBFactory()->commitMasterChanges();
591 // Output everything!
592 $this->context
->getOutput()->output();
594 wfProfileOut( __METHOD__
);
598 * Ends this task peacefully
600 public function restInPeace() {
601 // Do any deferred jobs
602 DeferredUpdates
::doUpdates( 'commit' );
604 // Log profiling data, e.g. in the database or UDP
605 wfLogProfilingData();
607 // Commit and close up!
608 $factory = wfGetLBFactory();
609 $factory->commitMasterChanges();
610 $factory->shutdown();
612 wfDebug( "Request ended normally\n" );
616 * Potentially open a socket and sent an HTTP request back to the server
617 * to run a specified number of jobs. This registers a callback to cleanup
618 * the socket once it's done.
620 protected function triggerJobs() {
621 $jobRunRate = $this->config
->get( 'JobRunRate' );
622 if ( $jobRunRate <= 0 ||
wfReadOnly() ) {
624 } elseif ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
625 return; // recursion guard
628 $section = new ProfileSection( __METHOD__
);
630 if ( $jobRunRate < 1 ) {
631 $max = mt_getrandmax();
632 if ( mt_rand( 0, $max ) > $max * $jobRunRate ) {
633 return; // the higher the job run rate, the less likely we return here
637 $n = intval( $jobRunRate );
640 if ( !$this->config
->get( 'RunJobsAsync' ) ) {
641 // Fall back to running the job here while the user waits
642 $runner = new JobRunner();
643 $runner->run( array( 'maxJobs' => $n ) );
648 if ( !JobQueueGroup
::singleton()->queuesHaveJobs( JobQueueGroup
::TYPE_DEFAULT
) ) {
649 return; // do not send request if there are probably no jobs
651 } catch ( JobQueueError
$e ) {
652 MWExceptionHandler
::logException( $e );
653 return; // do not make the site unavailable
656 $query = array( 'title' => 'Special:RunJobs',
657 'tasks' => 'jobs', 'maxjobs' => $n, 'sigexpiry' => time() +
5 );
658 $query['signature'] = SpecialRunJobs
::getQuerySignature(
659 $query, $this->config
->get( 'SecretKey' ) );
661 $errno = $errstr = null;
662 $info = wfParseUrl( $this->config
->get( 'Server' ) );
663 wfSuppressWarnings();
666 isset( $info['port'] ) ?
$info['port'] : 80,
669 // If it takes more than 100ms to connect to ourselves there
670 // is a problem elsewhere.
675 wfDebugLog( 'runJobs', "Failed to start cron API (socket error $errno): $errstr\n" );
676 // Fall back to running the job here while the user waits
677 $runner = new JobRunner();
678 $runner->run( array( 'maxJobs' => $n ) );
682 $url = wfAppendQuery( wfScript( 'index' ), $query );
683 $req = "POST $url HTTP/1.1\r\nHost: {$info['host']}\r\nConnection: Close\r\nContent-Length: 0\r\n\r\n";
685 wfDebugLog( 'runJobs', "Running $n job(s) via '$url'\n" );
686 // Send a cron API request to be performed in the background.
687 // Give up if this takes too long to send (which should be rare).
688 stream_set_timeout( $sock, 1 );
689 $bytes = fwrite( $sock, $req );
690 if ( $bytes !== strlen( $req ) ) {
691 wfDebugLog( 'runJobs', "Failed to start cron API (socket write error)\n" );
693 // Do not wait for the response (the script should handle client aborts).
694 // Make sure that we don't close before that script reaches ignore_user_abort().
695 $status = fgets( $sock );
696 if ( !preg_match( '#^HTTP/\d\.\d 202 #', $status ) ) {
697 wfDebugLog( 'runJobs', "Failed to start cron API: received '$status'\n" );