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
39 private $performedAction = 'nosuchaction';
42 * @param $x null|WebRequest
45 public function request( WebRequest
$x = null ) {
46 $old = $this->context
->getRequest();
47 $this->context
->setRequest( $x );
52 * @param $x null|OutputPage
55 public function output( OutputPage
$x = null ) {
56 $old = $this->context
->getOutput();
57 $this->context
->setOutput( $x );
62 * @param IContextSource|null $context
64 public function __construct( IContextSource
$context = null ) {
66 $context = RequestContext
::getMain();
69 $this->context
= $context;
70 $this->context
->setTitle( $this->parseTitle() );
74 * Parse the request to get the Title object
76 * @return Title object to be $wgTitle
78 private function parseTitle() {
81 $request = $this->context
->getRequest();
82 $curid = $request->getInt( 'curid' );
83 $title = $request->getVal( 'title' );
85 if ( $request->getCheck( 'search' ) ) {
86 // Compatibility with old search URLs which didn't use Special:Search
87 // Just check for presence here, so blank requests still
88 // show the search page when using ugly URLs (bug 8054).
89 $ret = SpecialPage
::getTitleFor( 'Search' );
91 // URLs like this are generated by RC, because rc_title isn't always accurate
92 $ret = Title
::newFromID( $curid );
93 } elseif ( $title == '' && $this->getAction() != 'delete' ) {
94 $ret = Title
::newMainPage();
96 $ret = Title
::newFromURL( $title );
97 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
98 // in wikitext links to tell Parser to make a direct file link
99 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA
) {
100 $ret = Title
::makeTitle( NS_FILE
, $ret->getDBkey() );
102 // Check variant links so that interwiki links don't have to worry
103 // about the possible different language variants
104 if ( count( $wgContLang->getVariants() ) > 1
105 && !is_null( $ret ) && $ret->getArticleID() == 0 )
107 $wgContLang->findVariantLink( $title, $ret );
110 // For non-special titles, check for implicit titles
111 if ( is_null( $ret ) ||
!$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 if ( $ret === null ||
( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
123 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
130 * Get the Title object that we'll be acting on, as specified in the WebRequest
133 public function getTitle() {
134 if( $this->context
->getTitle() === null ){
135 $this->context
->setTitle( $this->parseTitle() );
137 return $this->context
->getTitle();
141 * Performs the request.
144 * - local interwiki redirects
151 private function performRequest() {
152 global $wgServer, $wgUsePathInfo, $wgTitle;
154 wfProfileIn( __METHOD__
);
156 $request = $this->context
->getRequest();
157 $title = $this->context
->getTitle();
158 $output = $this->context
->getOutput();
159 $user = $this->context
->getUser();
161 if ( $request->getVal( 'printable' ) === 'yes' ) {
162 $output->setPrintable();
165 $unused = null; // To pass it by reference
166 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
168 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
169 if ( is_null( $title ) ||
( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
170 $title->isSpecial( 'Badtitle' ) )
172 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
173 wfProfileOut( __METHOD__
);
174 throw new ErrorPageError( 'badtitle', 'badtitletext' );
177 // Check user's permissions to read this page.
178 // We have to check here to catch special pages etc.
179 // We will check again in Article::view().
180 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
181 if ( count( $permErrors ) ) {
182 // Bug 32276: allowing the skin to generate output with $wgTitle or
183 // $this->context->title set to the input title would allow anonymous users to
184 // determine whether a page exists, potentially leaking private data. In fact, the
185 // curid and oldid request parameters would allow page titles to be enumerated even
186 // when they are not guessable. So we reset the title to Special:Badtitle before the
187 // permissions error is displayed.
189 // The skin mostly uses $this->context->getTitle() these days, but some extensions
190 // still use $wgTitle.
192 $badTitle = SpecialPage
::getTitleFor( 'Badtitle' );
193 $this->context
->setTitle( $badTitle );
194 $wgTitle = $badTitle;
196 wfProfileOut( __METHOD__
);
197 throw new PermissionsError( 'read', $permErrors );
200 $pageView = false; // was an article or special page viewed?
202 // Interwiki redirects
203 if ( $title->getInterwiki() != '' ) {
204 $rdfrom = $request->getVal( 'rdfrom' );
206 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
208 $query = $request->getValues();
209 unset( $query['title'] );
210 $url = $title->getFullURL( $query );
212 // Check for a redirect loop
213 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
214 && $title->isLocal() )
216 // 301 so google et al report the target as the actual url.
217 $output->redirect( $url, 301 );
219 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
220 wfProfileOut( __METHOD__
);
221 throw new ErrorPageError( 'badtitle', 'badtitletext' );
223 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
224 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
225 && ( $request->getVal( 'title' ) === null ||
226 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
227 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
228 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
230 if ( $title->isSpecialPage() ) {
231 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
233 $title = SpecialPage
::getTitleFor( $name, $subpage );
236 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
237 // Redirect to canonical url, make it a 301 to allow caching
238 if ( $targetUrl == $request->getFullRequestURL() ) {
239 $message = "Redirect loop detected!\n\n" .
240 "This means the wiki got confused about what page was " .
241 "requested; this sometimes happens when moving a wiki " .
242 "to a new server or changing the server configuration.\n\n";
244 if ( $wgUsePathInfo ) {
245 $message .= "The wiki is trying to interpret the page " .
246 "title from the URL path portion (PATH_INFO), which " .
247 "sometimes fails depending on the web server. Try " .
248 "setting \"\$wgUsePathInfo = false;\" in your " .
249 "LocalSettings.php, or check that \$wgArticlePath " .
252 $message .= "Your web server was detected as possibly not " .
253 "supporting URL path components (PATH_INFO) correctly; " .
254 "check your LocalSettings.php for a customized " .
255 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
258 throw new HttpError( 500, $message );
260 $output->setSquidMaxage( 1200 );
261 $output->redirect( $targetUrl, '301' );
264 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
266 // Actions that need to be made when we have a special pages
267 SpecialPageFactory
::executePath( $title, $this->context
);
269 // ...otherwise treat it as an article view. The article
270 // may be a redirect to another article or URL.
271 $article = $this->initializeArticle();
272 if ( is_object( $article ) ) {
275 * $wgArticle is deprecated, do not use it.
276 * This will be removed entirely in 1.20.
277 * @deprecated since 1.18
280 $wgArticle = $article;
282 $this->performAction( $article );
283 } elseif ( is_string( $article ) ) {
284 $output->redirect( $article );
286 wfProfileOut( __METHOD__
);
287 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
292 // Promote user to any groups they meet the criteria for
293 $user->addAutopromoteOnceGroups( 'onView' );
296 wfProfileOut( __METHOD__
);
300 * Create an Article object of the appropriate class for the given page.
302 * @deprecated in 1.18; use Article::newFromTitle() instead
303 * @param $title Title
304 * @param $context IContextSource
305 * @return Article object
307 public static function articleFromTitle( $title, IContextSource
$context ) {
308 wfDeprecated( __METHOD__
, '1.18' );
309 return Article
::newFromTitle( $title, $context );
313 * Returns the action that will be executed, not necessarily the one passed
314 * passed through the "action" parameter. Actions disabled in
315 * $wgDisabledActions will be replaced by "nosuchaction".
317 * The return value is merely a suggestion, not the actually performed action,
318 * which may be different. The actually performed action is determined by performAction().
319 * Requests like action=nonsense will make this function return "nonsense".
320 * Use getPerformedAction() to get the performed action.
322 * @return string: action
324 public function getAction() {
325 global $wgDisabledActions;
327 $request = $this->context
->getRequest();
328 $action = $request->getVal( 'action', 'view' );
330 // Check for disabled actions
331 if ( in_array( $action, $wgDisabledActions ) ) {
332 return 'nosuchaction';
335 // Workaround for bug #20966: inability of IE to provide an action dependent
336 // on which submit button is clicked.
337 if ( $action === 'historysubmit' ) {
338 if ( $request->getBool( 'revisiondelete' ) ) {
339 return 'revisiondelete';
343 } elseif ( $action == 'editredlink' ) {
351 * Initialize the main Article object for "standard" actions (view, etc)
352 * Create an Article object for the page, following redirects if needed.
354 * @return mixed an Article, or a string to redirect to another URL
356 private function initializeArticle() {
357 global $wgDisableHardRedirects;
359 wfProfileIn( __METHOD__
);
361 $title = $this->context
->getTitle();
362 $article = Article
::newFromTitle( $title, $this->context
);
363 $this->context
->setWikiPage( $article->getPage() );
364 // NS_MEDIAWIKI has no redirects.
365 // It is also used for CSS/JS, so performance matters here...
366 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
367 wfProfileOut( __METHOD__
);
371 $request = $this->context
->getRequest();
373 // Namespace might change when using redirects
374 // Check for redirects ...
375 $action = $request->getVal( 'action', 'view' );
376 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
377 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
378 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
379 !$request->getVal( 'diff' ) && // ... and not when showing diff
380 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
381 // ... and the article is not a non-redirect image page with associated file
382 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
384 // Give extensions a change to ignore/handle redirects as needed
385 $ignoreRedirect = $target = false;
387 wfRunHooks( 'InitializeArticleMaybeRedirect',
388 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
390 // Follow redirects only for... redirects.
391 // If $target is set, then a hook wanted to redirect.
392 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
393 // Is the target already set by an extension?
394 $target = $target ?
$target : $article->followRedirect();
395 if ( is_string( $target ) ) {
396 if ( !$wgDisableHardRedirects ) {
397 // we'll need to redirect
398 wfProfileOut( __METHOD__
);
402 if ( is_object( $target ) ) {
403 // Rewrite environment to redirected article
404 $rarticle = Article
::newFromTitle( $target, $this->context
);
405 $rarticle->loadPageData();
406 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
407 $rarticle->setRedirectedFrom( $title );
408 $article = $rarticle;
409 $this->context
->setTitle( $target );
410 $this->context
->setWikiPage( $article->getPage() );
414 $this->context
->setTitle( $article->getTitle() );
415 $this->context
->setWikiPage( $article->getPage() );
419 wfProfileOut( __METHOD__
);
424 * Cleaning up request by doing deferred updates, DB transaction, and the output
426 public function finalCleanup() {
427 wfProfileIn( __METHOD__
);
428 // Now commit any transactions, so that unreported errors after
429 // output() don't roll back the whole DB transaction
430 $factory = wfGetLBFactory();
431 $factory->commitMasterChanges();
432 // Output everything!
433 $this->context
->getOutput()->output();
434 // Do any deferred jobs
435 DeferredUpdates
::doUpdates( 'commit' );
437 wfProfileOut( __METHOD__
);
441 * Do a job from the job queue
443 private function doJobs() {
444 global $wgJobRunRate;
446 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
449 if ( $wgJobRunRate < 1 ) {
450 $max = mt_getrandmax();
451 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
456 $n = intval( $wgJobRunRate );
459 while ( $n-- && false != ( $job = Job
::pop() ) ) {
460 $output = $job->toString() . "\n";
462 $success = $job->run();
464 $t = round( $t * 1000 );
466 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
468 $output .= "Success, Time: $t ms\n";
470 wfDebugLog( 'jobqueue', $output );
475 * Ends this task peacefully
477 public function restInPeace() {
478 MessageCache
::logMessages();
479 wfLogProfilingData();
480 // Commit and close up!
481 $factory = wfGetLBFactory();
482 $factory->commitMasterChanges();
483 $factory->shutdown();
484 wfDebug( "Request ended normally\n" );
488 * Perform one of the "standard" actions
490 * @param $article Article
492 private function performAction( Page
$article ) {
493 global $wgSquidMaxage;
495 wfProfileIn( __METHOD__
);
497 $request = $this->context
->getRequest();
498 $output = $this->context
->getOutput();
499 $title = $this->context
->getTitle();
500 $user = $this->context
->getUser();
502 if ( !wfRunHooks( 'MediaWikiPerformAction',
503 array( $output, $article, $title, $user, $request, $this ) ) )
505 wfProfileOut( __METHOD__
);
509 $act = $this->getAction();
511 $action = Action
::factory( $act, $article );
512 if ( $action instanceof Action
) {
513 $this->performedAction
= $act;
515 wfProfileOut( __METHOD__
);
521 $output->setSquidMaxage( $wgSquidMaxage );
522 $this->performedAction
= $act;
529 $this->performedAction
= $act;
533 if ( session_id() == '' ) {
534 // Send a cookie so anons get talk message notifications
539 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
540 $this->performedAction
= 'edit';
541 if ( ExternalEdit
::useExternalEngine( $this->context
, 'edit' )
542 && $act == 'edit' && !$request->getVal( 'section' )
543 && !$request->getVal( 'oldid' ) )
545 $extedit = new ExternalEdit( $this->context
);
548 $editor = new EditPage( $article );
554 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
555 $this->performedAction
= 'nosuchaction';
556 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
559 wfProfileOut( __METHOD__
);
563 * Returns the real action as determined by performAction.
564 * Do not use internally in this class as it depends on the actions by this class.
568 * @return string: action
570 public function getPerformedAction() {
571 return $this->performedAction
;
575 * Run the current MediaWiki instance
576 * index.php just calls this
578 public function run() {
580 $this->checkMaxLag();
582 $this->restInPeace();
583 } catch ( Exception
$e ) {
584 MWExceptionHandler
::handle( $e );
589 * Checks if the request should abort due to a lagged server,
590 * for given maxlag parameter.
593 private function checkMaxLag() {
594 global $wgShowHostnames;
596 wfProfileIn( __METHOD__
);
597 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
598 if ( !is_null( $maxLag ) ) {
599 list( $host, $lag ) = wfGetLB()->getMaxLag();
600 if ( $lag > $maxLag ) {
601 $resp = $this->context
->getRequest()->response();
602 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
603 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
604 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
605 $resp->header( 'Content-Type: text/plain' );
606 if( $wgShowHostnames ) {
607 echo "Waiting for $host: $lag seconds lagged\n";
609 echo "Waiting for a database server: $lag seconds lagged\n";
612 wfProfileOut( __METHOD__
);
617 wfProfileOut( __METHOD__
);
621 private function main() {
622 global $wgUseFileCache, $wgTitle, $wgUseAjax;
624 wfProfileIn( __METHOD__
);
626 # Set title from request parameters
627 $wgTitle = $this->getTitle();
628 $action = $this->getAction();
630 # Send Ajax requests to the Ajax dispatcher.
631 if ( $wgUseAjax && $action == 'ajax' ) {
632 $dispatcher = new AjaxDispatcher();
633 $dispatcher->performAction();
634 wfProfileOut( __METHOD__
);
638 if ( $wgUseFileCache && $this->getTitle()->getNamespace() >= 0 ) {
639 wfProfileIn( 'main-try-filecache' );
640 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
641 /* Try low-level file cache hit */
642 $cache = HTMLFileCache
::newFromTitle( $this->getTitle(), $action );
643 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
644 /* Check incoming headers to see if client has this cached */
645 $timestamp = $cache->cacheTimestamp();
646 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
647 $cache->loadFromFileCache( $this->context
);
649 # Do any stats increment/watchlist stuff
650 $this->context
->getWikiPage()->doViewUpdates( $this->context
->getUser() );
651 # Tell OutputPage that output is taken care of
652 $this->context
->getOutput()->disable();
653 wfProfileOut( 'main-try-filecache' );
654 wfProfileOut( __METHOD__
);
658 wfProfileOut( 'main-try-filecache' );
661 $this->performRequest();
662 $this->finalCleanup();
664 wfProfileOut( __METHOD__
);