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
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() == '' ) ) {
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 ( $title instanceof BadTitle
) {
151 throw new ErrorPageError( 'badtitle', 'badtitletext' );
152 // If the user is not logged in, the Namespace:title of the article must be in
153 // the Read array in order for the user to see it. (We have to check here to
154 // catch special pages etc. We check again in Article::view())
155 } elseif ( !$title->userCanRead() ) {
156 $output->loginToUse();
157 // Interwiki redirects
158 } elseif ( $title->getInterwiki() != '' ) {
159 $rdfrom = $request->getVal( 'rdfrom' );
161 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
163 $query = $request->getValues();
164 unset( $query['title'] );
165 $url = $title->getFullURL( $query );
167 // Check for a redirect loop
168 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
169 && $title->isLocal() )
171 // 301 so google et al report the target as the actual url.
172 $output->redirect( $url, 301 );
174 $this->context
->setTitle( new BadTitle
);
175 wfProfileOut( __METHOD__
);
176 throw new ErrorPageError( 'badtitle', 'badtitletext' );
178 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
179 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
180 && ( $request->getVal( 'title' ) === null ||
181 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
182 && !count( $request->getValueNames( array( 'action', 'title' ) ) ) )
184 if ( $title->getNamespace() == NS_SPECIAL
) {
185 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
187 $title = SpecialPage
::getTitleFor( $name, $subpage );
190 $targetUrl = $title->getFullURL();
191 // Redirect to canonical url, make it a 301 to allow caching
192 if ( $targetUrl == $request->getFullRequestURL() ) {
193 $message = "Redirect loop detected!\n\n" .
194 "This means the wiki got confused about what page was " .
195 "requested; this sometimes happens when moving a wiki " .
196 "to a new server or changing the server configuration.\n\n";
198 if ( $wgUsePathInfo ) {
199 $message .= "The wiki is trying to interpret the page " .
200 "title from the URL path portion (PATH_INFO), which " .
201 "sometimes fails depending on the web server. Try " .
202 "setting \"\$wgUsePathInfo = false;\" in your " .
203 "LocalSettings.php, or check that \$wgArticlePath " .
206 $message .= "Your web server was detected as possibly not " .
207 "supporting URL path components (PATH_INFO) correctly; " .
208 "check your LocalSettings.php for a customized " .
209 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
212 wfHttpError( 500, "Internal error", $message );
214 $output->setSquidMaxage( 1200 );
215 $output->redirect( $targetUrl, '301' );
218 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
220 // Actions that need to be made when we have a special pages
221 SpecialPageFactory
::executePath( $title, $this->context
);
223 // ...otherwise treat it as an article view. The article
224 // may be a redirect to another article or URL.
225 $article = $this->initializeArticle();
226 if ( is_object( $article ) ) {
229 * $wgArticle is deprecated, do not use it. This will possibly be removed
230 * entirely in 1.20 or 1.21
231 * @deprecated since 1.18
234 $wgArticle = $article;
236 $this->performAction( $article );
237 } elseif ( is_string( $article ) ) {
238 $output->redirect( $article );
240 wfProfileOut( __METHOD__
);
241 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
246 // Promote user to any groups they meet the criteria for
247 $user->addAutopromoteOnceGroups( 'onView' );
250 wfProfileOut( __METHOD__
);
254 * Create an Article object of the appropriate class for the given page.
256 * @deprecated in 1.18; use Article::newFromTitle() instead
257 * @param $title Title
258 * @param $context RequestContext
259 * @return Article object
261 public static function articleFromTitle( $title, RequestContext
$context ) {
262 return Article
::newFromTitle( $title, $context );
266 * Returns the action that will be executed, not necessarily the one passed
267 * passed through the "action" parameter. Actions disabled in
268 * $wgDisabledActions will be replaced by "nosuchaction"
270 * @return String: action
272 public function getAction() {
273 global $wgDisabledActions;
275 $request = $this->context
->getRequest();
276 $action = $request->getVal( 'action', 'view' );
278 // Check for disabled actions
279 if ( in_array( $action, $wgDisabledActions ) ) {
280 return 'nosuchaction';
283 // Workaround for bug #20966: inability of IE to provide an action dependent
284 // on which submit button is clicked.
285 if ( $action === 'historysubmit' ) {
286 if ( $request->getBool( 'revisiondelete' ) ) {
287 return 'revisiondelete';
291 } elseif ( $action == 'editredlink' ) {
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 global $wgDisableHardRedirects;
307 wfProfileIn( __METHOD__
);
309 $request = $this->context
->getRequest();
310 $title = $this->context
->getTitle();
312 $action = $request->getVal( 'action', 'view' );
313 $article = Article
::newFromTitle( $title, $this->context
);
314 // NS_MEDIAWIKI has no redirects.
315 // It is also used for CSS/JS, so performance matters here...
316 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
317 wfProfileOut( __METHOD__
);
320 // Namespace might change when using redirects
321 // Check for redirects ...
322 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
323 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
324 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
325 !$request->getVal( 'diff' ) && // ... and not when showing diff
326 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
327 // ... and the article is not a non-redirect image page with associated file
328 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
330 // Give extensions a change to ignore/handle redirects as needed
331 $ignoreRedirect = $target = false;
333 wfRunHooks( 'InitializeArticleMaybeRedirect',
334 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
336 // Follow redirects only for... redirects.
337 // If $target is set, then a hook wanted to redirect.
338 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
339 // Is the target already set by an extension?
340 $target = $target ?
$target : $article->followRedirect();
341 if ( is_string( $target ) ) {
342 if ( !$wgDisableHardRedirects ) {
343 // we'll need to redirect
344 wfProfileOut( __METHOD__
);
348 if ( is_object( $target ) ) {
349 // Rewrite environment to redirected article
350 $rarticle = Article
::newFromTitle( $target, $this->context
);
351 $rarticle->loadPageData();
352 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
353 $rarticle->setRedirectedFrom( $title );
354 $article = $rarticle;
355 $this->context
->setTitle( $target );
359 $this->context
->setTitle( $article->getTitle() );
363 wfProfileOut( __METHOD__
);
368 * Cleaning up request by doing deferred updates, DB transaction, and the output
370 public function finalCleanup() {
371 wfProfileIn( __METHOD__
);
372 // Now commit any transactions, so that unreported errors after
373 // output() don't roll back the whole DB transaction
374 $factory = wfGetLBFactory();
375 $factory->commitMasterChanges();
376 // Output everything!
377 $this->context
->getOutput()->output();
378 // Do any deferred jobs
379 wfDoUpdates( 'commit' );
381 wfProfileOut( __METHOD__
);
385 * Do a job from the job queue
387 private function doJobs() {
388 global $wgJobRunRate;
390 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
393 if ( $wgJobRunRate < 1 ) {
394 $max = mt_getrandmax();
395 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
400 $n = intval( $wgJobRunRate );
403 while ( $n-- && false != ( $job = Job
::pop() ) ) {
404 $output = $job->toString() . "\n";
406 $success = $job->run();
408 $t = round( $t * 1000 );
410 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
412 $output .= "Success, Time: $t ms\n";
414 wfDebugLog( 'jobqueue', $output );
419 * Ends this task peacefully
421 public function restInPeace() {
422 MessageCache
::logMessages();
423 wfLogProfilingData();
424 // Commit and close up!
425 $factory = wfGetLBFactory();
426 $factory->commitMasterChanges();
427 $factory->shutdown();
428 wfDebug( "Request ended normally\n" );
432 * Perform one of the "standard" actions
434 * @param $article Article
436 private function performAction( Page
$article ) {
437 global $wgSquidMaxage, $wgUseExternalEditor;
439 wfProfileIn( __METHOD__
);
441 $request = $this->context
->getRequest();
442 $output = $this->context
->getOutput();
443 $title = $this->context
->getTitle();
444 $user = $this->context
->getUser();
446 if ( !wfRunHooks( 'MediaWikiPerformAction',
447 array( $output, $article, $title, $user, $request, $this ) ) )
449 wfProfileOut( __METHOD__
);
453 $act = $this->getAction();
455 $action = Action
::factory( $act, $article );
456 if ( $action instanceof Action
) {
458 wfProfileOut( __METHOD__
);
464 $output->setSquidMaxage( $wgSquidMaxage );
467 case 'raw': // includes JS/CSS
468 wfProfileIn( __METHOD__
. '-raw' );
469 $raw = new RawPage( $article );
471 wfProfileOut( __METHOD__
. '-raw' );
480 if ( session_id() == '' ) {
481 // Send a cookie so anons get talk message notifications
486 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
487 $internal = $request->getVal( 'internaledit' );
488 $external = $request->getVal( 'externaledit' );
489 $section = $request->getVal( 'section' );
490 $oldid = $request->getVal( 'oldid' );
491 if ( !$wgUseExternalEditor ||
$act == 'submit' ||
$internal ||
492 $section ||
$oldid ||
493 ( !$user->getOption( 'externaleditor' ) && !$external ) )
495 $editor = new EditPage( $article );
497 } elseif ( $wgUseExternalEditor
498 && ( $external ||
$user->getOption( 'externaleditor' ) ) )
500 $mode = $request->getVal( 'mode' );
501 $extedit = new ExternalEdit( $article->getTitle(), $mode );
507 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
508 $output->setSquidMaxage( $wgSquidMaxage );
510 $history = new HistoryPage( $article );
514 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
515 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
518 wfProfileOut( __METHOD__
);
522 * Run the current MediaWiki instance
523 * index.php just calls this
525 public function run() {
527 $this->checkMaxLag( true );
529 $this->restInPeace();
530 } catch ( Exception
$e ) {
531 MWExceptionHandler
::handle( $e );
536 * Checks if the request should abort due to a lagged server,
537 * for given maxlag parameter.
539 * @param boolean $abort True if this class should abort the
540 * script execution. False to return the result as a boolean.
541 * @return boolean True if we passed the check, false if we surpass the maxlag
543 private function checkMaxLag( $abort ) {
544 global $wgShowHostnames;
546 wfProfileIn( __METHOD__
);
547 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
548 if ( !is_null( $maxLag ) ) {
549 $lb = wfGetLB(); // foo()->bar() is not supported in PHP4
550 list( $host, $lag ) = $lb->getMaxLag();
551 if ( $lag > $maxLag ) {
553 $resp = $this->context
->getRequest()->response();
554 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
555 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
556 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
557 $resp->header( 'Content-Type: text/plain' );
558 if( $wgShowHostnames ) {
559 echo "Waiting for $host: $lag seconds lagged\n";
561 echo "Waiting for a database server: $lag seconds lagged\n";
565 wfProfileOut( __METHOD__
);
573 wfProfileOut( __METHOD__
);
577 private function main() {
578 global $wgUseFileCache, $wgTitle, $wgUseAjax;
580 wfProfileIn( __METHOD__
);
582 # Set title from request parameters
583 $wgTitle = $this->getTitle();
584 $action = $this->getAction();
585 $user = $this->context
->getUser();
587 # Send Ajax requests to the Ajax dispatcher.
588 if ( $wgUseAjax && $action == 'ajax' ) {
589 $dispatcher = new AjaxDispatcher();
590 $dispatcher->performAction();
591 wfProfileOut( __METHOD__
);
595 if ( $wgUseFileCache && $wgTitle->getNamespace() != NS_SPECIAL
) {
596 wfProfileIn( 'main-try-filecache' );
597 // Raw pages should handle cache control on their own,
598 // even when using file cache. This reduces hits from clients.
599 if ( HTMLFileCache
::useFileCache() ) {
600 /* Try low-level file cache hit */
601 $cache = new HTMLFileCache( $wgTitle, $action );
602 if ( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
603 /* Check incoming headers to see if client has this cached */
604 $timestamp = $cache->fileCacheTime();
605 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
606 $cache->loadFromFileCache();
608 # Do any stats increment/watchlist stuff
609 $article = WikiPage
::factory( $wgTitle );
610 $article->doViewUpdates( $user );
611 # Tell OutputPage that output is taken care of
612 $this->context
->getOutput()->disable();
613 wfProfileOut( 'main-try-filecache' );
614 wfProfileOut( __METHOD__
);
618 wfProfileOut( 'main-try-filecache' );
621 $this->performRequest();
622 $this->finalCleanup();
624 wfProfileOut( __METHOD__
);