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( RequestContext
$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 && !is_null( $ret ) && $ret->getArticleID() == 0 ){
84 $wgContLang->findVariantLink( $title, $ret );
87 // For non-special titles, check for implicit titles
88 if ( is_null( $ret ) ||
$ret->getNamespace() != NS_SPECIAL
) {
89 // We can have urls with just ?diff=,?oldid= or even just ?diff=
90 $oldid = $request->getInt( 'oldid' );
91 $oldid = $oldid ?
$oldid : $request->getInt( 'diff' );
92 // Allow oldid to override a changed or missing title
94 $rev = Revision
::newFromId( $oldid );
95 $ret = $rev ?
$rev->getTitle() : $ret;
99 if( $ret === null ||
( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ){
106 * Get the Title object that we'll be acting on, as specified in the WebRequest
109 public function getTitle(){
110 if( $this->context
->getTitle() === null ){
111 $this->context
->setTitle( $this->parseTitle() );
113 return $this->context
->getTitle();
117 * Performs the request.
120 * - local interwiki redirects
127 public function performRequest() {
128 global $wgServer, $wgUsePathInfo;
130 wfProfileIn( __METHOD__
);
132 $request = $this->context
->getRequest();
133 $title = $this->context
->getTitle();
134 $output = $this->context
->getOutput();
135 $user = $this->context
->getUser();
137 if ( $request->getVal( 'printable' ) === 'yes' ) {
138 $output->setPrintable();
141 $pageView = false; // was an article or special page viewed?
143 wfRunHooks( 'BeforeInitialize',
144 array( &$title, null, &$output, &$user, $request, $this ) );
146 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
147 if ( $title instanceof BadTitle
) {
148 throw new ErrorPageError( 'badtitle', 'badtitletext' );
149 // If the user is not logged in, the Namespace:title of the article must be in
150 // the Read array in order for the user to see it. (We have to check here to
151 // catch special pages etc. We check again in Article::view())
152 } elseif ( !$title->userCanRead() ) {
153 $output->loginToUse();
154 // Interwiki redirects
155 } elseif ( $title->getInterwiki() != '' ) {
156 $rdfrom = $request->getVal( 'rdfrom' );
158 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
160 $query = $request->getValues();
161 unset( $query['title'] );
162 $url = $title->getFullURL( $query );
164 // Check for a redirect loop
165 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url ) && $title->isLocal() ) {
166 // 301 so google et al report the target as the actual url.
167 $output->redirect( $url, 301 );
169 $this->context
->setTitle( new BadTitle
);
170 wfProfileOut( __METHOD__
);
171 throw new ErrorPageError( 'badtitle', 'badtitletext' );
173 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
174 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
175 && ( $request->getVal( 'title' ) === null ||
$title->getPrefixedDBKey() != $request->getVal( 'title' ) )
176 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
178 if ( $title->getNamespace() == NS_SPECIAL
) {
179 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
181 $title = SpecialPage
::getTitleFor( $name, $subpage );
184 $targetUrl = $title->getFullURL();
185 // Redirect to canonical url, make it a 301 to allow caching
186 if ( $targetUrl == $request->getFullRequestURL() ) {
187 $message = "Redirect loop detected!\n\n" .
188 "This means the wiki got confused about what page was " .
189 "requested; this sometimes happens when moving a wiki " .
190 "to a new server or changing the server configuration.\n\n";
192 if ( $wgUsePathInfo ) {
193 $message .= "The wiki is trying to interpret the page " .
194 "title from the URL path portion (PATH_INFO), which " .
195 "sometimes fails depending on the web server. Try " .
196 "setting \"\$wgUsePathInfo = false;\" in your " .
197 "LocalSettings.php, or check that \$wgArticlePath " .
200 $message .= "Your web server was detected as possibly not " .
201 "supporting URL path components (PATH_INFO) correctly; " .
202 "check your LocalSettings.php for a customized " .
203 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
206 wfHttpError( 500, "Internal error", $message );
208 $output->setSquidMaxage( 1200 );
209 $output->redirect( $targetUrl, '301' );
212 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
214 // Actions that need to be made when we have a special pages
215 SpecialPageFactory
::executePath( $title, $this->context
);
217 // ...otherwise treat it as an article view. The article
218 // may be a redirect to another article or URL.
219 $article = $this->initializeArticle();
220 if ( is_object( $article ) ) {
223 * $wgArticle is deprecated, do not use it. This will possibly be removed
224 * entirely in 1.20 or 1.21
225 * @deprecated since 1.19
228 $wgArticle = $article;
230 $this->performAction( $article );
231 } elseif ( is_string( $article ) ) {
232 $output->redirect( $article );
234 wfProfileOut( __METHOD__
);
235 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
240 // Promote user to any groups they meet the criteria for
241 $user->addAutopromoteOnceGroups( 'onView' );
244 wfProfileOut( __METHOD__
);
248 * Create an Article object of the appropriate class for the given page.
250 * @deprecated in 1.19; use Article::newFromTitle() instead
251 * @param $title Title
252 * @param $context RequestContext
253 * @return Article object
255 public static function articleFromTitle( $title, RequestContext
$context ) {
256 return Article
::newFromTitle( $title, $context );
260 * Returns the action that will be executed, not necesserly the one passed
261 * passed through the "action" parameter. Actions disabled in
262 * $wgDisabledActions will be replaced by "nosuchaction"
264 * @return String: action
266 public function getAction() {
267 global $wgDisabledActions;
269 $request = $this->context
->getRequest();
270 $action = $request->getVal( 'action', 'view' );
272 // Check for disabled actions
273 if ( in_array( $action, $wgDisabledActions ) ) {
274 return 'nosuchaction';
277 // Workaround for bug #20966: inability of IE to provide an action dependent
278 // on which submit button is clicked.
279 if ( $action === 'historysubmit' ) {
280 if ( $request->getBool( 'revisiondelete' ) ) {
281 return 'revisiondelete';
285 } elseif ( $action == 'editredlink' ) {
293 * Initialize the main Article object for "standard" actions (view, etc)
294 * Create an Article object for the page, following redirects if needed.
296 * @return mixed an Article, or a string to redirect to another URL
298 private function initializeArticle() {
299 global $wgDisableHardRedirects;
301 wfProfileIn( __METHOD__
);
303 $request = $this->context
->getRequest();
304 $title = $this->context
->getTitle();
306 $action = $request->getVal( 'action', 'view' );
307 $article = Article
::newFromTitle( $title, $this->context
);
308 // NS_MEDIAWIKI has no redirects.
309 // It is also used for CSS/JS, so performance matters here...
310 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
311 wfProfileOut( __METHOD__
);
314 // Namespace might change when using redirects
315 // Check for redirects ...
316 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
317 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
318 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
319 !$request->getVal( 'diff' ) && // ... and not when showing diff
320 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
321 // ... and the article is not a non-redirect image page with associated file
322 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
324 // Give extensions a change to ignore/handle redirects as needed
325 $ignoreRedirect = $target = false;
327 wfRunHooks( 'InitializeArticleMaybeRedirect',
328 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
330 // Follow redirects only for... redirects.
331 // If $target is set, then a hook wanted to redirect.
332 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
333 // Is the target already set by an extension?
334 $target = $target ?
$target : $article->followRedirect();
335 if ( is_string( $target ) ) {
336 if ( !$wgDisableHardRedirects ) {
337 // we'll need to redirect
338 wfProfileOut( __METHOD__
);
342 if ( is_object( $target ) ) {
343 // Rewrite environment to redirected article
344 $rarticle = Article
::newFromTitle( $target, $this->context
);
345 $rarticle->loadPageData();
346 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
347 $rarticle->setRedirectedFrom( $title );
348 $article = $rarticle;
349 $this->context
->setTitle( $target );
353 $this->context
->setTitle( $article->getTitle() );
356 wfProfileOut( __METHOD__
);
361 * Cleaning up request by doing deferred updates, DB transaction, and the output
363 public function finalCleanup() {
364 wfProfileIn( __METHOD__
);
365 // Now commit any transactions, so that unreported errors after
366 // output() don't roll back the whole DB transaction
367 $factory = wfGetLBFactory();
368 $factory->commitMasterChanges();
369 // Output everything!
370 $this->context
->getOutput()->output();
371 // Do any deferred jobs
372 wfDoUpdates( 'commit' );
374 wfProfileOut( __METHOD__
);
378 * Do a job from the job queue
380 private function doJobs() {
381 global $wgJobRunRate;
383 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
386 if ( $wgJobRunRate < 1 ) {
387 $max = mt_getrandmax();
388 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
393 $n = intval( $wgJobRunRate );
396 while ( $n-- && false != ( $job = Job
::pop() ) ) {
397 $output = $job->toString() . "\n";
399 $success = $job->run();
401 $t = round( $t * 1000 );
403 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
405 $output .= "Success, Time: $t ms\n";
407 wfDebugLog( 'jobqueue', $output );
412 * Ends this task peacefully
414 public function restInPeace() {
415 MessageCache
::logMessages();
416 wfLogProfilingData();
417 // Commit and close up!
418 $factory = wfGetLBFactory();
419 $factory->commitMasterChanges();
420 $factory->shutdown();
421 wfDebug( "Request ended normally\n" );
425 * Perform one of the "standard" actions
427 * @param $article Article
429 private function performAction( Page
$article ) {
430 global $wgSquidMaxage, $wgUseExternalEditor;
432 wfProfileIn( __METHOD__
);
434 $request = $this->context
->getRequest();
435 $output = $this->context
->getOutput();
436 $title = $this->context
->getTitle();
437 $user = $this->context
->getUser();
439 if ( !wfRunHooks( 'MediaWikiPerformAction',
440 array( $output, $article, $title, $user, $request, $this ) ) )
442 wfProfileOut( __METHOD__
);
446 $act = $this->getAction();
448 $action = Action
::factory( $act, $article );
449 if( $action instanceof Action
){
451 wfProfileOut( __METHOD__
);
457 $output->setSquidMaxage( $wgSquidMaxage );
460 case 'raw': // includes JS/CSS
461 wfProfileIn( __METHOD__
. '-raw' );
462 $raw = new RawPage( $article );
464 wfProfileOut( __METHOD__
. '-raw' );
475 if ( session_id() == '' ) {
476 // Send a cookie so anons get talk message notifications
481 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
482 $internal = $request->getVal( 'internaledit' );
483 $external = $request->getVal( 'externaledit' );
484 $section = $request->getVal( 'section' );
485 $oldid = $request->getVal( 'oldid' );
486 if ( !$wgUseExternalEditor ||
$act == 'submit' ||
$internal ||
487 $section ||
$oldid ||
( !$user->getOption( 'externaleditor' ) && !$external ) ) {
488 $editor = new EditPage( $article );
490 } elseif ( $wgUseExternalEditor && ( $external ||
$user->getOption( 'externaleditor' ) ) ) {
491 $mode = $request->getVal( 'mode' );
492 $extedit = new ExternalEdit( $article, $mode );
498 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
499 $output->setSquidMaxage( $wgSquidMaxage );
501 $history = new HistoryPage( $article );
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
518 $this->checkMaxLag( true );
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 * @param boolean $abort True if this class should abort the
531 * script execution. False to return the result as a boolean.
532 * @return boolean True if we passed the check, false if we surpass the maxlag
534 function checkMaxLag( $abort ) {
535 global $wgShowHostnames;
537 wfProfileIn( __METHOD__
);
538 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
539 if ( !is_null( $maxLag ) ) {
540 $lb = wfGetLB(); // foo()->bar() is not supported in PHP4
541 list( $host, $lag ) = $lb->getMaxLag();
542 if ( $lag > $maxLag ) {
544 header( 'HTTP/1.1 503 Service Unavailable' );
545 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
546 header( 'X-Database-Lag: ' . intval( $lag ) );
547 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";
555 wfProfileOut( __METHOD__
);
562 wfProfileOut( __METHOD__
);
567 global $wgUseFileCache, $wgTitle, $wgUseAjax;
569 wfProfileIn( __METHOD__
);
571 # Set title from request parameters
572 $wgTitle = $this->getTitle();
573 $action = $this->getAction();
575 # Send Ajax requests to the Ajax dispatcher.
576 if ( $wgUseAjax && $action == 'ajax' ) {
577 $dispatcher = new AjaxDispatcher();
578 $dispatcher->performAction();
579 wfProfileOut( __METHOD__
);
583 if ( $wgUseFileCache && $wgTitle->getNamespace() != NS_SPECIAL
) {
584 wfProfileIn( 'main-try-filecache' );
585 // Raw pages should handle cache control on their own,
586 // even when using file cache. This reduces hits from clients.
587 if ( HTMLFileCache
::useFileCache() ) {
588 /* Try low-level file cache hit */
589 $cache = new HTMLFileCache( $wgTitle, $action );
590 if ( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
591 /* Check incoming headers to see if client has this cached */
592 if ( !$this->context
->getOutput()->checkLastModified( $cache->fileCacheTime() ) ) {
593 $cache->loadFromFileCache();
595 # Do any stats increment/watchlist stuff
596 $article = Article
::newFromTitle( $wgTitle, $this->context
);
597 $article->viewUpdates();
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 $this->performRequest();
609 $this->finalCleanup();
611 wfProfileOut( __METHOD__
);