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() == '' ) ) {
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 $this->context
->title
= SpecialPage
::getTitleFor( 'Badtitle' );
152 // Die now before we mess up $wgArticle and the skin stops working
153 throw new ErrorPageError( 'badtitle', 'badtitletext' );
154 // If the user is not logged in, the Namespace:title of the article must be in
155 // the Read array in order for the user to see it. (We have to check here to
156 // catch special pages etc. We check again in Article::view())
157 } elseif ( !$title->userCanRead() ) {
158 $output->loginToUse();
159 // Interwiki redirects
160 } elseif ( $title->getInterwiki() != '' ) {
161 $rdfrom = $request->getVal( 'rdfrom' );
163 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
165 $query = $request->getValues();
166 unset( $query['title'] );
167 $url = $title->getFullURL( $query );
169 // Check for a redirect loop
170 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
171 && $title->isLocal() )
173 // 301 so google et al report the target as the actual url.
174 $output->redirect( $url, 301 );
176 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
177 wfProfileOut( __METHOD__
);
178 throw new ErrorPageError( 'badtitle', 'badtitletext' );
180 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
181 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
182 && ( $request->getVal( 'title' ) === null ||
183 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
184 && !count( $request->getValueNames( array( 'action', 'title' ) ) ) )
186 if ( $title->getNamespace() == NS_SPECIAL
) {
187 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
189 $title = SpecialPage
::getTitleFor( $name, $subpage );
192 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
193 // Redirect to canonical url, make it a 301 to allow caching
194 if ( $targetUrl == $request->getFullRequestURL() ) {
195 $message = "Redirect loop detected!\n\n" .
196 "This means the wiki got confused about what page was " .
197 "requested; this sometimes happens when moving a wiki " .
198 "to a new server or changing the server configuration.\n\n";
200 if ( $wgUsePathInfo ) {
201 $message .= "The wiki is trying to interpret the page " .
202 "title from the URL path portion (PATH_INFO), which " .
203 "sometimes fails depending on the web server. Try " .
204 "setting \"\$wgUsePathInfo = false;\" in your " .
205 "LocalSettings.php, or check that \$wgArticlePath " .
208 $message .= "Your web server was detected as possibly not " .
209 "supporting URL path components (PATH_INFO) correctly; " .
210 "check your LocalSettings.php for a customized " .
211 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
214 wfHttpError( 500, "Internal error", $message );
216 $output->setSquidMaxage( 1200 );
217 $output->redirect( $targetUrl, '301' );
220 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
222 // Actions that need to be made when we have a special pages
223 SpecialPageFactory
::executePath( $title, $this->context
);
225 // ...otherwise treat it as an article view. The article
226 // may be a redirect to another article or URL.
227 $article = $this->initializeArticle();
228 if ( is_object( $article ) ) {
231 * $wgArticle is deprecated, do not use it. This will possibly be removed
232 * entirely in 1.20 or 1.21
233 * @deprecated since 1.18
236 $wgArticle = $article;
238 $this->performAction( $article );
239 } elseif ( is_string( $article ) ) {
240 $output->redirect( $article );
242 wfProfileOut( __METHOD__
);
243 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
248 // Promote user to any groups they meet the criteria for
249 $user->addAutopromoteOnceGroups( 'onView' );
252 wfProfileOut( __METHOD__
);
256 * Create an Article object of the appropriate class for the given page.
258 * @deprecated in 1.18; use Article::newFromTitle() instead
259 * @param $title Title
260 * @param $context RequestContext
261 * @return Article object
263 public static function articleFromTitle( $title, RequestContext
$context ) {
264 return Article
::newFromTitle( $title, $context );
268 * Returns the action that will be executed, not necessarily the one passed
269 * passed through the "action" parameter. Actions disabled in
270 * $wgDisabledActions will be replaced by "nosuchaction"
272 * @return String: action
274 public function getAction() {
275 global $wgDisabledActions;
277 $request = $this->context
->getRequest();
278 $action = $request->getVal( 'action', 'view' );
280 // Check for disabled actions
281 if ( in_array( $action, $wgDisabledActions ) ) {
282 return 'nosuchaction';
285 // Workaround for bug #20966: inability of IE to provide an action dependent
286 // on which submit button is clicked.
287 if ( $action === 'historysubmit' ) {
288 if ( $request->getBool( 'revisiondelete' ) ) {
289 return 'revisiondelete';
293 } elseif ( $action == 'editredlink' ) {
301 * Initialize the main Article object for "standard" actions (view, etc)
302 * Create an Article object for the page, following redirects if needed.
304 * @return mixed an Article, or a string to redirect to another URL
306 private function initializeArticle() {
307 global $wgDisableHardRedirects;
309 wfProfileIn( __METHOD__
);
311 $request = $this->context
->getRequest();
312 $title = $this->context
->getTitle();
314 $action = $request->getVal( 'action', 'view' );
315 $article = Article
::newFromTitle( $title, $this->context
);
316 // NS_MEDIAWIKI has no redirects.
317 // It is also used for CSS/JS, so performance matters here...
318 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
319 wfProfileOut( __METHOD__
);
322 // Namespace might change when using redirects
323 // Check for redirects ...
324 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
325 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
326 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
327 !$request->getVal( 'diff' ) && // ... and not when showing diff
328 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
329 // ... and the article is not a non-redirect image page with associated file
330 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
332 // Give extensions a change to ignore/handle redirects as needed
333 $ignoreRedirect = $target = false;
335 wfRunHooks( 'InitializeArticleMaybeRedirect',
336 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
338 // Follow redirects only for... redirects.
339 // If $target is set, then a hook wanted to redirect.
340 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
341 // Is the target already set by an extension?
342 $target = $target ?
$target : $article->followRedirect();
343 if ( is_string( $target ) ) {
344 if ( !$wgDisableHardRedirects ) {
345 // we'll need to redirect
346 wfProfileOut( __METHOD__
);
350 if ( is_object( $target ) ) {
351 // Rewrite environment to redirected article
352 $rarticle = Article
::newFromTitle( $target, $this->context
);
353 $rarticle->loadPageData();
354 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
355 $rarticle->setRedirectedFrom( $title );
356 $article = $rarticle;
357 $this->context
->setTitle( $target );
361 $this->context
->setTitle( $article->getTitle() );
365 wfProfileOut( __METHOD__
);
370 * Cleaning up request by doing deferred updates, DB transaction, and the output
372 public function finalCleanup() {
373 wfProfileIn( __METHOD__
);
374 // Now commit any transactions, so that unreported errors after
375 // output() don't roll back the whole DB transaction
376 $factory = wfGetLBFactory();
377 $factory->commitMasterChanges();
378 // Output everything!
379 $this->context
->getOutput()->output();
380 // Do any deferred jobs
381 wfDoUpdates( 'commit' );
383 wfProfileOut( __METHOD__
);
387 * Do a job from the job queue
389 private function doJobs() {
390 global $wgJobRunRate;
392 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
395 if ( $wgJobRunRate < 1 ) {
396 $max = mt_getrandmax();
397 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
402 $n = intval( $wgJobRunRate );
405 while ( $n-- && false != ( $job = Job
::pop() ) ) {
406 $output = $job->toString() . "\n";
408 $success = $job->run();
410 $t = round( $t * 1000 );
412 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
414 $output .= "Success, Time: $t ms\n";
416 wfDebugLog( 'jobqueue', $output );
421 * Ends this task peacefully
423 public function restInPeace() {
424 MessageCache
::logMessages();
425 wfLogProfilingData();
426 // Commit and close up!
427 $factory = wfGetLBFactory();
428 $factory->commitMasterChanges();
429 $factory->shutdown();
430 wfDebug( "Request ended normally\n" );
434 * Perform one of the "standard" actions
436 * @param $article Article
438 private function performAction( Page
$article ) {
439 global $wgSquidMaxage, $wgUseExternalEditor;
441 wfProfileIn( __METHOD__
);
443 $request = $this->context
->getRequest();
444 $output = $this->context
->getOutput();
445 $title = $this->context
->getTitle();
446 $user = $this->context
->getUser();
448 if ( !wfRunHooks( 'MediaWikiPerformAction',
449 array( $output, $article, $title, $user, $request, $this ) ) )
451 wfProfileOut( __METHOD__
);
455 $act = $this->getAction();
457 $action = Action
::factory( $act, $article );
458 if ( $action instanceof Action
) {
460 wfProfileOut( __METHOD__
);
466 $output->setSquidMaxage( $wgSquidMaxage );
469 case 'raw': // includes JS/CSS
470 wfProfileIn( __METHOD__
. '-raw' );
471 $raw = new RawPage( $article );
473 wfProfileOut( __METHOD__
. '-raw' );
482 if ( session_id() == '' ) {
483 // Send a cookie so anons get talk message notifications
488 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
489 $internal = $request->getVal( 'internaledit' );
490 $external = $request->getVal( 'externaledit' );
491 $section = $request->getVal( 'section' );
492 $oldid = $request->getVal( 'oldid' );
493 if ( !$wgUseExternalEditor ||
$act == 'submit' ||
$internal ||
494 $section ||
$oldid ||
495 ( !$user->getOption( 'externaleditor' ) && !$external ) )
497 $editor = new EditPage( $article );
499 } elseif ( $wgUseExternalEditor
500 && ( $external ||
$user->getOption( 'externaleditor' ) ) )
502 $mode = $request->getVal( 'mode' );
503 $extedit = new ExternalEdit( $article->getTitle(), $mode );
509 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
510 $output->setSquidMaxage( $wgSquidMaxage );
512 $history = new HistoryPage( $article );
516 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
517 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
520 wfProfileOut( __METHOD__
);
524 * Run the current MediaWiki instance
525 * index.php just calls this
527 public function run() {
529 $this->checkMaxLag( true );
531 $this->restInPeace();
532 } catch ( Exception
$e ) {
533 MWExceptionHandler
::handle( $e );
538 * Checks if the request should abort due to a lagged server,
539 * for given maxlag parameter.
541 * @param boolean $abort True if this class should abort the
542 * script execution. False to return the result as a boolean.
543 * @return boolean True if we passed the check, false if we surpass the maxlag
545 private function checkMaxLag( $abort ) {
546 global $wgShowHostnames;
548 wfProfileIn( __METHOD__
);
549 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
550 if ( !is_null( $maxLag ) ) {
551 $lb = wfGetLB(); // foo()->bar() is not supported in PHP4
552 list( $host, $lag ) = $lb->getMaxLag();
553 if ( $lag > $maxLag ) {
555 $resp = $this->context
->getRequest()->response();
556 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
557 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
558 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
559 $resp->header( 'Content-Type: text/plain' );
560 if( $wgShowHostnames ) {
561 echo "Waiting for $host: $lag seconds lagged\n";
563 echo "Waiting for a database server: $lag seconds lagged\n";
567 wfProfileOut( __METHOD__
);
575 wfProfileOut( __METHOD__
);
579 private function main() {
580 global $wgUseFileCache, $wgTitle, $wgUseAjax;
582 wfProfileIn( __METHOD__
);
584 # Set title from request parameters
585 $wgTitle = $this->getTitle();
586 $action = $this->getAction();
587 $user = $this->context
->getUser();
589 # Send Ajax requests to the Ajax dispatcher.
590 if ( $wgUseAjax && $action == 'ajax' ) {
591 $dispatcher = new AjaxDispatcher();
592 $dispatcher->performAction();
593 wfProfileOut( __METHOD__
);
597 if ( $wgUseFileCache && $wgTitle->getNamespace() != NS_SPECIAL
) {
598 wfProfileIn( 'main-try-filecache' );
599 // Raw pages should handle cache control on their own,
600 // even when using file cache. This reduces hits from clients.
601 if ( HTMLFileCache
::useFileCache() ) {
602 /* Try low-level file cache hit */
603 $cache = new HTMLFileCache( $wgTitle, $action );
604 if ( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
605 /* Check incoming headers to see if client has this cached */
606 $timestamp = $cache->fileCacheTime();
607 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
608 $cache->loadFromFileCache();
610 # Do any stats increment/watchlist stuff
611 $article = WikiPage
::factory( $wgTitle );
612 $article->doViewUpdates( $user );
613 # Tell OutputPage that output is taken care of
614 $this->context
->getOutput()->disable();
615 wfProfileOut( 'main-try-filecache' );
616 wfProfileOut( __METHOD__
);
620 wfProfileOut( 'main-try-filecache' );
623 $this->performRequest();
624 $this->finalCleanup();
626 wfProfileOut( __METHOD__
);