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
36 public function request( WebRequest
$x = null ){
37 $old = $this->context
->getRequest();
38 $this->context
->setRequest( $x );
42 public function output( OutputPage
$x = null ){
43 $old = $this->context
->getOutput();
44 $this->context
->setOutput( $x );
48 public function __construct( IContextSource
$context = null ) {
50 $context = RequestContext
::getMain();
53 $this->context
= $context;
54 $this->context
->setTitle( $this->parseTitle() );
58 * Parse the request to get the Title object
60 * @return Title object to be $wgTitle
62 private function parseTitle() {
65 $request = $this->context
->getRequest();
66 $curid = $request->getInt( 'curid' );
67 $title = $request->getVal( 'title' );
69 if ( $request->getCheck( 'search' ) ) {
70 // Compatibility with old search URLs which didn't use Special:Search
71 // Just check for presence here, so blank requests still
72 // show the search page when using ugly URLs (bug 8054).
73 $ret = SpecialPage
::getTitleFor( 'Search' );
75 // URLs like this are generated by RC, because rc_title isn't always accurate
76 $ret = Title
::newFromID( $curid );
77 } elseif ( $title == '' && $this->getAction() != 'delete' ) {
78 $ret = Title
::newMainPage();
80 $ret = Title
::newFromURL( $title );
81 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
82 // in wikitext links to tell Parser to make a direct file link
83 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA
) {
84 $ret = Title
::makeTitle( NS_FILE
, $ret->getDBkey() );
86 // Check variant links so that interwiki links don't have to worry
87 // about the possible different language variants
88 if ( count( $wgContLang->getVariants() ) > 1
89 && !is_null( $ret ) && $ret->getArticleID() == 0 )
91 $wgContLang->findVariantLink( $title, $ret );
94 // For non-special titles, check for implicit titles
95 if ( is_null( $ret ) ||
!$ret->isSpecialPage() ) {
96 // We can have urls with just ?diff=,?oldid= or even just ?diff=
97 $oldid = $request->getInt( 'oldid' );
98 $oldid = $oldid ?
$oldid : $request->getInt( 'diff' );
99 // Allow oldid to override a changed or missing title
101 $rev = Revision
::newFromId( $oldid );
102 $ret = $rev ?
$rev->getTitle() : $ret;
106 if ( $ret === null ||
( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
107 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
114 * Get the Title object that we'll be acting on, as specified in the WebRequest
117 public function getTitle(){
118 if( $this->context
->getTitle() === null ){
119 $this->context
->setTitle( $this->parseTitle() );
121 return $this->context
->getTitle();
125 * Performs the request.
128 * - local interwiki redirects
135 private function performRequest() {
136 global $wgServer, $wgUsePathInfo;
138 wfProfileIn( __METHOD__
);
140 $request = $this->context
->getRequest();
141 $title = $this->context
->getTitle();
142 $output = $this->context
->getOutput();
143 $user = $this->context
->getUser();
145 if ( $request->getVal( 'printable' ) === 'yes' ) {
146 $output->setPrintable();
149 $pageView = false; // was an article or special page viewed?
151 wfRunHooks( 'BeforeInitialize',
152 array( &$title, null, &$output, &$user, $request, $this ) );
154 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
155 if ( is_null( $title ) ||
( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
156 $title->isSpecial( 'Badtitle' ) )
158 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
159 throw new ErrorPageError( 'badtitle', 'badtitletext' );
160 // If the user is not logged in, the Namespace:title of the article must be in
161 // the Read array in order for the user to see it. (We have to check here to
162 // catch special pages etc. We check again in Article::view())
163 } elseif ( !$title->userCanRead() ) {
164 $output->loginToUse();
165 // Interwiki redirects
166 } elseif ( $title->getInterwiki() != '' ) {
167 $rdfrom = $request->getVal( 'rdfrom' );
169 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
171 $query = $request->getValues();
172 unset( $query['title'] );
173 $url = $title->getFullURL( $query );
175 // Check for a redirect loop
176 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
177 && $title->isLocal() )
179 // 301 so google et al report the target as the actual url.
180 $output->redirect( $url, 301 );
182 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
183 wfProfileOut( __METHOD__
);
184 throw new ErrorPageError( 'badtitle', 'badtitletext' );
186 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
187 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
188 && ( $request->getVal( 'title' ) === null ||
189 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
190 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
191 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
193 if ( $title->isSpecialPage() ) {
194 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
196 $title = SpecialPage
::getTitleFor( $name, $subpage );
199 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
200 // Redirect to canonical url, make it a 301 to allow caching
201 if ( $targetUrl == $request->getFullRequestURL() ) {
202 $message = "Redirect loop detected!\n\n" .
203 "This means the wiki got confused about what page was " .
204 "requested; this sometimes happens when moving a wiki " .
205 "to a new server or changing the server configuration.\n\n";
207 if ( $wgUsePathInfo ) {
208 $message .= "The wiki is trying to interpret the page " .
209 "title from the URL path portion (PATH_INFO), which " .
210 "sometimes fails depending on the web server. Try " .
211 "setting \"\$wgUsePathInfo = false;\" in your " .
212 "LocalSettings.php, or check that \$wgArticlePath " .
215 $message .= "Your web server was detected as possibly not " .
216 "supporting URL path components (PATH_INFO) correctly; " .
217 "check your LocalSettings.php for a customized " .
218 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
221 throw new HttpError( 500, $message );
223 $output->setSquidMaxage( 1200 );
224 $output->redirect( $targetUrl, '301' );
227 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
229 // Actions that need to be made when we have a special pages
230 SpecialPageFactory
::executePath( $title, $this->context
);
232 // ...otherwise treat it as an article view. The article
233 // may be a redirect to another article or URL.
234 $article = $this->initializeArticle();
235 if ( is_object( $article ) ) {
238 * $wgArticle is deprecated, do not use it. This will possibly be removed
239 * entirely in 1.20 or 1.21
240 * @deprecated since 1.18
243 $wgArticle = $article;
245 $this->performAction( $article );
246 } elseif ( is_string( $article ) ) {
247 $output->redirect( $article );
249 wfProfileOut( __METHOD__
);
250 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
255 // Promote user to any groups they meet the criteria for
256 $user->addAutopromoteOnceGroups( 'onView' );
259 wfProfileOut( __METHOD__
);
263 * Create an Article object of the appropriate class for the given page.
265 * @deprecated in 1.18; use Article::newFromTitle() instead
266 * @param $title Title
267 * @param $context IContextSource
268 * @return Article object
270 public static function articleFromTitle( $title, IContextSource
$context ) {
271 return Article
::newFromTitle( $title, $context );
275 * Returns the action that will be executed, not necessarily the one passed
276 * passed through the "action" parameter. Actions disabled in
277 * $wgDisabledActions will be replaced by "nosuchaction"
279 * @return String: action
281 public function getAction() {
282 global $wgDisabledActions;
284 $request = $this->context
->getRequest();
285 $action = $request->getVal( 'action', 'view' );
287 // Check for disabled actions
288 if ( in_array( $action, $wgDisabledActions ) ) {
289 return 'nosuchaction';
292 // Workaround for bug #20966: inability of IE to provide an action dependent
293 // on which submit button is clicked.
294 if ( $action === 'historysubmit' ) {
295 if ( $request->getBool( 'revisiondelete' ) ) {
296 return 'revisiondelete';
300 } elseif ( $action == 'editredlink' ) {
308 * Initialize the main Article object for "standard" actions (view, etc)
309 * Create an Article object for the page, following redirects if needed.
311 * @return mixed an Article, or a string to redirect to another URL
313 private function initializeArticle() {
314 global $wgDisableHardRedirects;
316 wfProfileIn( __METHOD__
);
318 $request = $this->context
->getRequest();
319 $title = $this->context
->getTitle();
321 $action = $request->getVal( 'action', 'view' );
322 $article = Article
::newFromTitle( $title, $this->context
);
323 // NS_MEDIAWIKI has no redirects.
324 // It is also used for CSS/JS, so performance matters here...
325 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
326 wfProfileOut( __METHOD__
);
329 // Namespace might change when using redirects
330 // Check for redirects ...
331 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
332 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
333 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
334 !$request->getVal( 'diff' ) && // ... and not when showing diff
335 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
336 // ... and the article is not a non-redirect image page with associated file
337 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
339 // Give extensions a change to ignore/handle redirects as needed
340 $ignoreRedirect = $target = false;
342 wfRunHooks( 'InitializeArticleMaybeRedirect',
343 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
345 // Follow redirects only for... redirects.
346 // If $target is set, then a hook wanted to redirect.
347 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
348 // Is the target already set by an extension?
349 $target = $target ?
$target : $article->followRedirect();
350 if ( is_string( $target ) ) {
351 if ( !$wgDisableHardRedirects ) {
352 // we'll need to redirect
353 wfProfileOut( __METHOD__
);
357 if ( is_object( $target ) ) {
358 // Rewrite environment to redirected article
359 $rarticle = Article
::newFromTitle( $target, $this->context
);
360 $rarticle->loadPageData();
361 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
362 $rarticle->setRedirectedFrom( $title );
363 $article = $rarticle;
364 $this->context
->setTitle( $target );
368 $this->context
->setTitle( $article->getTitle() );
372 wfProfileOut( __METHOD__
);
377 * Cleaning up request by doing deferred updates, DB transaction, and the output
379 public function finalCleanup() {
380 wfProfileIn( __METHOD__
);
381 // Now commit any transactions, so that unreported errors after
382 // output() don't roll back the whole DB transaction
383 $factory = wfGetLBFactory();
384 $factory->commitMasterChanges();
385 // Output everything!
386 $this->context
->getOutput()->output();
387 // Do any deferred jobs
388 DeferredUpdates
::doUpdates( 'commit' );
390 wfProfileOut( __METHOD__
);
394 * Do a job from the job queue
396 private function doJobs() {
397 global $wgJobRunRate;
399 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
402 if ( $wgJobRunRate < 1 ) {
403 $max = mt_getrandmax();
404 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
409 $n = intval( $wgJobRunRate );
412 while ( $n-- && false != ( $job = Job
::pop() ) ) {
413 $output = $job->toString() . "\n";
415 $success = $job->run();
417 $t = round( $t * 1000 );
419 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
421 $output .= "Success, Time: $t ms\n";
423 wfDebugLog( 'jobqueue', $output );
428 * Ends this task peacefully
430 public function restInPeace() {
431 MessageCache
::logMessages();
432 wfLogProfilingData();
433 // Commit and close up!
434 $factory = wfGetLBFactory();
435 $factory->commitMasterChanges();
436 $factory->shutdown();
437 wfDebug( "Request ended normally\n" );
441 * Perform one of the "standard" actions
443 * @param $article Article
445 private function performAction( Page
$article ) {
446 global $wgSquidMaxage, $wgUseExternalEditor;
448 wfProfileIn( __METHOD__
);
450 $request = $this->context
->getRequest();
451 $output = $this->context
->getOutput();
452 $title = $this->context
->getTitle();
453 $user = $this->context
->getUser();
455 if ( !wfRunHooks( 'MediaWikiPerformAction',
456 array( $output, $article, $title, $user, $request, $this ) ) )
458 wfProfileOut( __METHOD__
);
462 $act = $this->getAction();
464 $action = Action
::factory( $act, $article );
465 if ( $action instanceof Action
) {
467 wfProfileOut( __METHOD__
);
473 $output->setSquidMaxage( $wgSquidMaxage );
483 if ( session_id() == '' ) {
484 // Send a cookie so anons get talk message notifications
489 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
490 $internal = $request->getVal( 'internaledit' );
491 $external = $request->getVal( 'externaledit' );
492 $section = $request->getVal( 'section' );
493 $oldid = $request->getVal( 'oldid' );
494 if ( !$wgUseExternalEditor ||
$act == 'submit' ||
$internal ||
495 $section ||
$oldid ||
496 ( !$user->getOption( 'externaleditor' ) && !$external ) )
498 $editor = new EditPage( $article );
500 } elseif ( $wgUseExternalEditor
501 && ( $external ||
$user->getOption( 'externaleditor' ) ) )
503 $mode = $request->getVal( 'mode' );
504 $extedit = new ExternalEdit( $article->getTitle(), $mode );
510 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
511 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
514 wfProfileOut( __METHOD__
);
518 * Run the current MediaWiki instance
519 * index.php just calls this
521 public function run() {
523 $this->checkMaxLag();
525 $this->restInPeace();
526 } catch ( Exception
$e ) {
527 MWExceptionHandler
::handle( $e );
532 * Checks if the request should abort due to a lagged server,
533 * for given maxlag parameter.
535 private function checkMaxLag() {
536 global $wgShowHostnames;
538 wfProfileIn( __METHOD__
);
539 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
540 if ( !is_null( $maxLag ) ) {
541 list( $host, $lag ) = wfGetLB()->getMaxLag();
542 if ( $lag > $maxLag ) {
543 $resp = $this->context
->getRequest()->response();
544 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
545 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
546 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
547 $resp->header( 'Content-Type: text/plain' );
548 if( $wgShowHostnames ) {
549 echo "Waiting for $host: $lag seconds lagged\n";
551 echo "Waiting for a database server: $lag seconds lagged\n";
554 wfProfileOut( __METHOD__
);
559 wfProfileOut( __METHOD__
);
563 private function main() {
564 global $wgUseFileCache, $wgTitle, $wgUseAjax;
566 wfProfileIn( __METHOD__
);
568 # Set title from request parameters
569 $wgTitle = $this->getTitle();
570 $action = $this->getAction();
571 $user = $this->context
->getUser();
573 # Send Ajax requests to the Ajax dispatcher.
574 if ( $wgUseAjax && $action == 'ajax' ) {
575 $dispatcher = new AjaxDispatcher();
576 $dispatcher->performAction();
577 wfProfileOut( __METHOD__
);
581 if ( $wgUseFileCache && $wgTitle->getNamespace() >= 0 ) {
582 wfProfileIn( 'main-try-filecache' );
583 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
584 /* Try low-level file cache hit */
585 $cache = HTMLFileCache
::newFromTitle( $wgTitle, $action );
586 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
587 /* Check incoming headers to see if client has this cached */
588 $timestamp = $cache->cacheTimestamp();
589 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
590 $cache->loadFromFileCache( $this->context
);
592 # Do any stats increment/watchlist stuff
593 $article = WikiPage
::factory( $wgTitle );
594 $article->doViewUpdates( $user );
595 # Tell OutputPage that output is taken care of
596 $this->context
->getOutput()->disable();
597 wfProfileOut( 'main-try-filecache' );
598 wfProfileOut( __METHOD__
);
602 wfProfileOut( 'main-try-filecache' );
605 $this->performRequest();
606 $this->finalCleanup();
608 wfProfileOut( __METHOD__
);