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 // check variant links so that interwiki links don't have to worry
82 // about the possible different language variants
83 if ( count( $wgContLang->getVariants() ) > 1
84 && !is_null( $ret ) && $ret->getArticleID() == 0 )
86 $wgContLang->findVariantLink( $title, $ret );
89 // For non-special titles, check for implicit titles
90 if ( is_null( $ret ) ||
$ret->getNamespace() != NS_SPECIAL
) {
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 if ( $ret === null ||
( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
102 $ret = SpecialPage
::getTitleFor( 'Badtitle' );
109 * Get the Title object that we'll be acting on, as specified in the WebRequest
112 public function getTitle(){
113 if( $this->context
->getTitle() === null ){
114 $this->context
->setTitle( $this->parseTitle() );
116 return $this->context
->getTitle();
120 * Performs the request.
123 * - local interwiki redirects
130 private function performRequest() {
131 global $wgServer, $wgUsePathInfo;
133 wfProfileIn( __METHOD__
);
135 $request = $this->context
->getRequest();
136 $title = $this->context
->getTitle();
137 $output = $this->context
->getOutput();
138 $user = $this->context
->getUser();
140 if ( $request->getVal( 'printable' ) === 'yes' ) {
141 $output->setPrintable();
144 $pageView = false; // was an article or special page viewed?
146 wfRunHooks( 'BeforeInitialize',
147 array( &$title, null, &$output, &$user, $request, $this ) );
149 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
150 if ( is_null( $title ) ||
( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
151 $title->isSpecial( 'Badtitle' ) )
153 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
154 throw new ErrorPageError( 'badtitle', 'badtitletext' );
155 // If the user is not logged in, the Namespace:title of the article must be in
156 // the Read array in order for the user to see it. (We have to check here to
157 // catch special pages etc. We check again in Article::view())
158 } elseif ( !$title->userCanRead() ) {
159 $output->loginToUse();
160 // Interwiki redirects
161 } elseif ( $title->getInterwiki() != '' ) {
162 $rdfrom = $request->getVal( 'rdfrom' );
164 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
166 $query = $request->getValues();
167 unset( $query['title'] );
168 $url = $title->getFullURL( $query );
170 // Check for a redirect loop
171 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
172 && $title->isLocal() )
174 // 301 so google et al report the target as the actual url.
175 $output->redirect( $url, 301 );
177 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
178 wfProfileOut( __METHOD__
);
179 throw new ErrorPageError( 'badtitle', 'badtitletext' );
181 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
182 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
183 && ( $request->getVal( 'title' ) === null ||
184 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
185 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
186 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
188 if ( $title->getNamespace() == NS_SPECIAL
) {
189 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
191 $title = SpecialPage
::getTitleFor( $name, $subpage );
194 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
195 // Redirect to canonical url, make it a 301 to allow caching
196 if ( $targetUrl == $request->getFullRequestURL() ) {
197 $message = "Redirect loop detected!\n\n" .
198 "This means the wiki got confused about what page was " .
199 "requested; this sometimes happens when moving a wiki " .
200 "to a new server or changing the server configuration.\n\n";
202 if ( $wgUsePathInfo ) {
203 $message .= "The wiki is trying to interpret the page " .
204 "title from the URL path portion (PATH_INFO), which " .
205 "sometimes fails depending on the web server. Try " .
206 "setting \"\$wgUsePathInfo = false;\" in your " .
207 "LocalSettings.php, or check that \$wgArticlePath " .
210 $message .= "Your web server was detected as possibly not " .
211 "supporting URL path components (PATH_INFO) correctly; " .
212 "check your LocalSettings.php for a customized " .
213 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
216 throw new HttpError( 500, $message );
218 $output->setSquidMaxage( 1200 );
219 $output->redirect( $targetUrl, '301' );
222 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
224 // Actions that need to be made when we have a special pages
225 SpecialPageFactory
::executePath( $title, $this->context
);
227 // ...otherwise treat it as an article view. The article
228 // may be a redirect to another article or URL.
229 $article = $this->initializeArticle();
230 if ( is_object( $article ) ) {
233 * $wgArticle is deprecated, do not use it. This will possibly be removed
234 * entirely in 1.20 or 1.21
235 * @deprecated since 1.18
238 $wgArticle = $article;
240 $this->performAction( $article );
241 } elseif ( is_string( $article ) ) {
242 $output->redirect( $article );
244 wfProfileOut( __METHOD__
);
245 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
250 // Promote user to any groups they meet the criteria for
251 $user->addAutopromoteOnceGroups( 'onView' );
254 wfProfileOut( __METHOD__
);
258 * Create an Article object of the appropriate class for the given page.
260 * @deprecated in 1.18; use Article::newFromTitle() instead
261 * @param $title Title
262 * @param $context IContextSource
263 * @return Article object
265 public static function articleFromTitle( $title, IContextSource
$context ) {
266 return Article
::newFromTitle( $title, $context );
270 * Returns the action that will be executed, not necessarily the one passed
271 * passed through the "action" parameter. Actions disabled in
272 * $wgDisabledActions will be replaced by "nosuchaction"
274 * @return String: action
276 public function getAction() {
277 global $wgDisabledActions;
279 $request = $this->context
->getRequest();
280 $action = $request->getVal( 'action', 'view' );
282 // Check for disabled actions
283 if ( in_array( $action, $wgDisabledActions ) ) {
284 return 'nosuchaction';
287 // Workaround for bug #20966: inability of IE to provide an action dependent
288 // on which submit button is clicked.
289 if ( $action === 'historysubmit' ) {
290 if ( $request->getBool( 'revisiondelete' ) ) {
291 return 'revisiondelete';
295 } elseif ( $action == 'editredlink' ) {
303 * Initialize the main Article object for "standard" actions (view, etc)
304 * Create an Article object for the page, following redirects if needed.
306 * @return mixed an Article, or a string to redirect to another URL
308 private function initializeArticle() {
309 global $wgDisableHardRedirects;
311 wfProfileIn( __METHOD__
);
313 $request = $this->context
->getRequest();
314 $title = $this->context
->getTitle();
316 $action = $request->getVal( 'action', 'view' );
317 $article = Article
::newFromTitle( $title, $this->context
);
318 // NS_MEDIAWIKI has no redirects.
319 // It is also used for CSS/JS, so performance matters here...
320 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
321 wfProfileOut( __METHOD__
);
324 // Namespace might change when using redirects
325 // Check for redirects ...
326 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
327 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
328 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
329 !$request->getVal( 'diff' ) && // ... and not when showing diff
330 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
331 // ... and the article is not a non-redirect image page with associated file
332 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
334 // Give extensions a change to ignore/handle redirects as needed
335 $ignoreRedirect = $target = false;
337 wfRunHooks( 'InitializeArticleMaybeRedirect',
338 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
340 // Follow redirects only for... redirects.
341 // If $target is set, then a hook wanted to redirect.
342 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
343 // Is the target already set by an extension?
344 $target = $target ?
$target : $article->followRedirect();
345 if ( is_string( $target ) ) {
346 if ( !$wgDisableHardRedirects ) {
347 // we'll need to redirect
348 wfProfileOut( __METHOD__
);
352 if ( is_object( $target ) ) {
353 // Rewrite environment to redirected article
354 $rarticle = Article
::newFromTitle( $target, $this->context
);
355 $rarticle->loadPageData();
356 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
357 $rarticle->setRedirectedFrom( $title );
358 $article = $rarticle;
359 $this->context
->setTitle( $target );
363 $this->context
->setTitle( $article->getTitle() );
367 wfProfileOut( __METHOD__
);
372 * Cleaning up request by doing deferred updates, DB transaction, and the output
374 public function finalCleanup() {
375 wfProfileIn( __METHOD__
);
376 // Now commit any transactions, so that unreported errors after
377 // output() don't roll back the whole DB transaction
378 $factory = wfGetLBFactory();
379 $factory->commitMasterChanges();
380 // Output everything!
381 $this->context
->getOutput()->output();
382 // Do any deferred jobs
383 DeferredUpdates
::doUpdates( 'commit' );
385 wfProfileOut( __METHOD__
);
389 * Do a job from the job queue
391 private function doJobs() {
392 global $wgJobRunRate;
394 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
397 if ( $wgJobRunRate < 1 ) {
398 $max = mt_getrandmax();
399 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
404 $n = intval( $wgJobRunRate );
407 while ( $n-- && false != ( $job = Job
::pop() ) ) {
408 $output = $job->toString() . "\n";
410 $success = $job->run();
412 $t = round( $t * 1000 );
414 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
416 $output .= "Success, Time: $t ms\n";
418 wfDebugLog( 'jobqueue', $output );
423 * Ends this task peacefully
425 public function restInPeace() {
426 MessageCache
::logMessages();
427 wfLogProfilingData();
428 // Commit and close up!
429 $factory = wfGetLBFactory();
430 $factory->commitMasterChanges();
431 $factory->shutdown();
432 wfDebug( "Request ended normally\n" );
436 * Perform one of the "standard" actions
438 * @param $article Article
440 private function performAction( Page
$article ) {
441 global $wgSquidMaxage, $wgUseExternalEditor;
443 wfProfileIn( __METHOD__
);
445 $request = $this->context
->getRequest();
446 $output = $this->context
->getOutput();
447 $title = $this->context
->getTitle();
448 $user = $this->context
->getUser();
450 if ( !wfRunHooks( 'MediaWikiPerformAction',
451 array( $output, $article, $title, $user, $request, $this ) ) )
453 wfProfileOut( __METHOD__
);
457 $act = $this->getAction();
459 $action = Action
::factory( $act, $article );
460 if ( $action instanceof Action
) {
462 wfProfileOut( __METHOD__
);
468 $output->setSquidMaxage( $wgSquidMaxage );
478 if ( session_id() == '' ) {
479 // Send a cookie so anons get talk message notifications
484 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
485 $internal = $request->getVal( 'internaledit' );
486 $external = $request->getVal( 'externaledit' );
487 $section = $request->getVal( 'section' );
488 $oldid = $request->getVal( 'oldid' );
489 if ( !$wgUseExternalEditor ||
$act == 'submit' ||
$internal ||
490 $section ||
$oldid ||
491 ( !$user->getOption( 'externaleditor' ) && !$external ) )
493 $editor = new EditPage( $article );
495 } elseif ( $wgUseExternalEditor
496 && ( $external ||
$user->getOption( 'externaleditor' ) ) )
498 $mode = $request->getVal( 'mode' );
499 $extedit = new ExternalEdit( $article->getTitle(), $mode );
505 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
506 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
509 wfProfileOut( __METHOD__
);
513 * Run the current MediaWiki instance
514 * index.php just calls this
516 public function run() {
518 $this->checkMaxLag();
520 $this->restInPeace();
521 } catch ( Exception
$e ) {
522 MWExceptionHandler
::handle( $e );
527 * Checks if the request should abort due to a lagged server,
528 * for given maxlag parameter.
530 private function checkMaxLag() {
531 global $wgShowHostnames;
533 wfProfileIn( __METHOD__
);
534 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
535 if ( !is_null( $maxLag ) ) {
536 list( $host, $lag ) = wfGetLB()->getMaxLag();
537 if ( $lag > $maxLag ) {
538 $resp = $this->context
->getRequest()->response();
539 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
540 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
541 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
542 $resp->header( 'Content-Type: text/plain' );
543 if( $wgShowHostnames ) {
544 echo "Waiting for $host: $lag seconds lagged\n";
546 echo "Waiting for a database server: $lag seconds lagged\n";
549 wfProfileOut( __METHOD__
);
554 wfProfileOut( __METHOD__
);
558 private function main() {
559 global $wgUseFileCache, $wgTitle, $wgUseAjax;
561 wfProfileIn( __METHOD__
);
563 # Set title from request parameters
564 $wgTitle = $this->getTitle();
565 $action = $this->getAction();
566 $user = $this->context
->getUser();
568 # Send Ajax requests to the Ajax dispatcher.
569 if ( $wgUseAjax && $action == 'ajax' ) {
570 $dispatcher = new AjaxDispatcher();
571 $dispatcher->performAction();
572 wfProfileOut( __METHOD__
);
576 if ( $wgUseFileCache && $wgTitle->getNamespace() >= 0 ) {
577 wfProfileIn( 'main-try-filecache' );
578 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
579 /* Try low-level file cache hit */
580 $cache = HTMLFileCache
::newFromTitle( $wgTitle, $action );
581 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
582 /* Check incoming headers to see if client has this cached */
583 $timestamp = $cache->cacheTimestamp();
584 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
585 $cache->loadFromFileCache( $this->context
);
587 # Do any stats increment/watchlist stuff
588 $article = WikiPage
::factory( $wgTitle );
589 $article->doViewUpdates( $user );
590 # Tell OutputPage that output is taken care of
591 $this->context
->getOutput()->disable();
592 wfProfileOut( 'main-try-filecache' );
593 wfProfileOut( __METHOD__
);
597 wfProfileOut( 'main-try-filecache' );
600 $this->performRequest();
601 $this->finalCleanup();
603 wfProfileOut( __METHOD__
);