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 wfRunHooks( 'BeforeInitialize',
150 array( &$title, null, &$output, &$user, $request, $this ) );
152 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
153 if ( is_null( $title ) ||
( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
154 $title->isSpecial( 'Badtitle' ) )
156 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
157 wfProfileOut( __METHOD__
);
158 throw new ErrorPageError( 'badtitle', 'badtitletext' );
161 // Check user's permissions to read this page.
162 // We have to check here to catch special pages etc.
163 // We will check again in Article::view().
164 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
165 if ( count( $permErrors ) ) {
166 wfProfileOut( __METHOD__
);
167 throw new PermissionsError( 'read', $permErrors );
170 $pageView = false; // was an article or special page viewed?
172 // Interwiki redirects
173 if ( $title->getInterwiki() != '' ) {
174 $rdfrom = $request->getVal( 'rdfrom' );
176 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
178 $query = $request->getValues();
179 unset( $query['title'] );
180 $url = $title->getFullURL( $query );
182 // Check for a redirect loop
183 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
184 && $title->isLocal() )
186 // 301 so google et al report the target as the actual url.
187 $output->redirect( $url, 301 );
189 $this->context
->setTitle( SpecialPage
::getTitleFor( 'Badtitle' ) );
190 wfProfileOut( __METHOD__
);
191 throw new ErrorPageError( 'badtitle', 'badtitletext' );
193 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
194 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
195 && ( $request->getVal( 'title' ) === null ||
196 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
197 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
198 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
200 if ( $title->isSpecialPage() ) {
201 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
203 $title = SpecialPage
::getTitleFor( $name, $subpage );
206 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
207 // Redirect to canonical url, make it a 301 to allow caching
208 if ( $targetUrl == $request->getFullRequestURL() ) {
209 $message = "Redirect loop detected!\n\n" .
210 "This means the wiki got confused about what page was " .
211 "requested; this sometimes happens when moving a wiki " .
212 "to a new server or changing the server configuration.\n\n";
214 if ( $wgUsePathInfo ) {
215 $message .= "The wiki is trying to interpret the page " .
216 "title from the URL path portion (PATH_INFO), which " .
217 "sometimes fails depending on the web server. Try " .
218 "setting \"\$wgUsePathInfo = false;\" in your " .
219 "LocalSettings.php, or check that \$wgArticlePath " .
222 $message .= "Your web server was detected as possibly not " .
223 "supporting URL path components (PATH_INFO) correctly; " .
224 "check your LocalSettings.php for a customized " .
225 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
228 throw new HttpError( 500, $message );
230 $output->setSquidMaxage( 1200 );
231 $output->redirect( $targetUrl, '301' );
234 } elseif ( NS_SPECIAL
== $title->getNamespace() ) {
236 // Actions that need to be made when we have a special pages
237 SpecialPageFactory
::executePath( $title, $this->context
);
239 // ...otherwise treat it as an article view. The article
240 // may be a redirect to another article or URL.
241 $article = $this->initializeArticle();
242 if ( is_object( $article ) ) {
245 * $wgArticle is deprecated, do not use it. This will possibly be removed
246 * entirely in 1.20 or 1.21
247 * @deprecated since 1.18
250 $wgArticle = $article;
252 $this->performAction( $article );
253 } elseif ( is_string( $article ) ) {
254 $output->redirect( $article );
256 wfProfileOut( __METHOD__
);
257 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
262 // Promote user to any groups they meet the criteria for
263 $user->addAutopromoteOnceGroups( 'onView' );
266 wfProfileOut( __METHOD__
);
270 * Create an Article object of the appropriate class for the given page.
272 * @deprecated in 1.18; use Article::newFromTitle() instead
273 * @param $title Title
274 * @param $context IContextSource
275 * @return Article object
277 public static function articleFromTitle( $title, IContextSource
$context ) {
278 return Article
::newFromTitle( $title, $context );
282 * Returns the action that will be executed, not necessarily the one passed
283 * passed through the "action" parameter. Actions disabled in
284 * $wgDisabledActions will be replaced by "nosuchaction"
286 * @return String: action
288 public function getAction() {
289 global $wgDisabledActions;
291 $request = $this->context
->getRequest();
292 $action = $request->getVal( 'action', 'view' );
294 // Check for disabled actions
295 if ( in_array( $action, $wgDisabledActions ) ) {
296 return 'nosuchaction';
299 // Workaround for bug #20966: inability of IE to provide an action dependent
300 // on which submit button is clicked.
301 if ( $action === 'historysubmit' ) {
302 if ( $request->getBool( 'revisiondelete' ) ) {
303 return 'revisiondelete';
307 } elseif ( $action == 'editredlink' ) {
315 * Initialize the main Article object for "standard" actions (view, etc)
316 * Create an Article object for the page, following redirects if needed.
318 * @return mixed an Article, or a string to redirect to another URL
320 private function initializeArticle() {
321 global $wgDisableHardRedirects;
323 wfProfileIn( __METHOD__
);
325 $request = $this->context
->getRequest();
326 $title = $this->context
->getTitle();
328 $action = $request->getVal( 'action', 'view' );
329 $article = Article
::newFromTitle( $title, $this->context
);
330 // NS_MEDIAWIKI has no redirects.
331 // It is also used for CSS/JS, so performance matters here...
332 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
333 wfProfileOut( __METHOD__
);
336 // Namespace might change when using redirects
337 // Check for redirects ...
338 $file = ( $title->getNamespace() == NS_FILE
) ?
$article->getFile() : null;
339 if ( ( $action == 'view' ||
$action == 'render' ) // ... for actions that show content
340 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
341 !$request->getVal( 'diff' ) && // ... and not when showing diff
342 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
343 // ... and the article is not a non-redirect image page with associated file
344 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
346 // Give extensions a change to ignore/handle redirects as needed
347 $ignoreRedirect = $target = false;
349 wfRunHooks( 'InitializeArticleMaybeRedirect',
350 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
352 // Follow redirects only for... redirects.
353 // If $target is set, then a hook wanted to redirect.
354 if ( !$ignoreRedirect && ( $target ||
$article->isRedirect() ) ) {
355 // Is the target already set by an extension?
356 $target = $target ?
$target : $article->followRedirect();
357 if ( is_string( $target ) ) {
358 if ( !$wgDisableHardRedirects ) {
359 // we'll need to redirect
360 wfProfileOut( __METHOD__
);
364 if ( is_object( $target ) ) {
365 // Rewrite environment to redirected article
366 $rarticle = Article
::newFromTitle( $target, $this->context
);
367 $rarticle->loadPageData();
368 if ( $rarticle->exists() ||
( is_object( $file ) && !$file->isLocal() ) ) {
369 $rarticle->setRedirectedFrom( $title );
370 $article = $rarticle;
371 $this->context
->setTitle( $target );
375 $this->context
->setTitle( $article->getTitle() );
379 wfProfileOut( __METHOD__
);
384 * Cleaning up request by doing deferred updates, DB transaction, and the output
386 public function finalCleanup() {
387 wfProfileIn( __METHOD__
);
388 // Now commit any transactions, so that unreported errors after
389 // output() don't roll back the whole DB transaction
390 $factory = wfGetLBFactory();
391 $factory->commitMasterChanges();
392 // Output everything!
393 $this->context
->getOutput()->output();
394 // Do any deferred jobs
395 DeferredUpdates
::doUpdates( 'commit' );
397 wfProfileOut( __METHOD__
);
401 * Do a job from the job queue
403 private function doJobs() {
404 global $wgJobRunRate;
406 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
409 if ( $wgJobRunRate < 1 ) {
410 $max = mt_getrandmax();
411 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
416 $n = intval( $wgJobRunRate );
419 while ( $n-- && false != ( $job = Job
::pop() ) ) {
420 $output = $job->toString() . "\n";
422 $success = $job->run();
424 $t = round( $t * 1000 );
426 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
428 $output .= "Success, Time: $t ms\n";
430 wfDebugLog( 'jobqueue', $output );
435 * Ends this task peacefully
437 public function restInPeace() {
438 MessageCache
::logMessages();
439 wfLogProfilingData();
440 // Commit and close up!
441 $factory = wfGetLBFactory();
442 $factory->commitMasterChanges();
443 $factory->shutdown();
444 wfDebug( "Request ended normally\n" );
448 * Perform one of the "standard" actions
450 * @param $article Article
452 private function performAction( Page
$article ) {
453 global $wgSquidMaxage, $wgUseExternalEditor;
455 wfProfileIn( __METHOD__
);
457 $request = $this->context
->getRequest();
458 $output = $this->context
->getOutput();
459 $title = $this->context
->getTitle();
460 $user = $this->context
->getUser();
462 if ( !wfRunHooks( 'MediaWikiPerformAction',
463 array( $output, $article, $title, $user, $request, $this ) ) )
465 wfProfileOut( __METHOD__
);
469 $act = $this->getAction();
471 $action = Action
::factory( $act, $article );
472 if ( $action instanceof Action
) {
474 wfProfileOut( __METHOD__
);
480 $output->setSquidMaxage( $wgSquidMaxage );
490 if ( session_id() == '' ) {
491 // Send a cookie so anons get talk message notifications
496 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
497 $internal = $request->getVal( 'internaledit' );
498 $external = $request->getVal( 'externaledit' );
499 $section = $request->getVal( 'section' );
500 $oldid = $request->getVal( 'oldid' );
501 if ( !$wgUseExternalEditor ||
$act == 'submit' ||
$internal ||
502 $section ||
$oldid ||
503 ( !$user->getOption( 'externaleditor' ) && !$external ) )
505 $editor = new EditPage( $article );
507 } elseif ( $wgUseExternalEditor
508 && ( $external ||
$user->getOption( 'externaleditor' ) ) )
510 $mode = $request->getVal( 'mode' );
511 $extedit = new ExternalEdit( $article->getTitle(), $mode );
517 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
518 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
521 wfProfileOut( __METHOD__
);
525 * Run the current MediaWiki instance
526 * index.php just calls this
528 public function run() {
530 $this->checkMaxLag();
532 $this->restInPeace();
533 } catch ( Exception
$e ) {
534 MWExceptionHandler
::handle( $e );
539 * Checks if the request should abort due to a lagged server,
540 * for given maxlag parameter.
542 private function checkMaxLag() {
543 global $wgShowHostnames;
545 wfProfileIn( __METHOD__
);
546 $maxLag = $this->context
->getRequest()->getVal( 'maxlag' );
547 if ( !is_null( $maxLag ) ) {
548 list( $host, $lag ) = wfGetLB()->getMaxLag();
549 if ( $lag > $maxLag ) {
550 $resp = $this->context
->getRequest()->response();
551 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
552 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
553 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
554 $resp->header( 'Content-Type: text/plain' );
555 if( $wgShowHostnames ) {
556 echo "Waiting for $host: $lag seconds lagged\n";
558 echo "Waiting for a database server: $lag seconds lagged\n";
561 wfProfileOut( __METHOD__
);
566 wfProfileOut( __METHOD__
);
570 private function main() {
571 global $wgUseFileCache, $wgTitle, $wgUseAjax;
573 wfProfileIn( __METHOD__
);
575 # Set title from request parameters
576 $wgTitle = $this->getTitle();
577 $action = $this->getAction();
578 $user = $this->context
->getUser();
580 # Send Ajax requests to the Ajax dispatcher.
581 if ( $wgUseAjax && $action == 'ajax' ) {
582 $dispatcher = new AjaxDispatcher();
583 $dispatcher->performAction();
584 wfProfileOut( __METHOD__
);
588 if ( $wgUseFileCache && $wgTitle->getNamespace() >= 0 ) {
589 wfProfileIn( 'main-try-filecache' );
590 if ( HTMLFileCache
::useFileCache( $this->context
) ) {
591 /* Try low-level file cache hit */
592 $cache = HTMLFileCache
::newFromTitle( $wgTitle, $action );
593 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
594 /* Check incoming headers to see if client has this cached */
595 $timestamp = $cache->cacheTimestamp();
596 if ( !$this->context
->getOutput()->checkLastModified( $timestamp ) ) {
597 $cache->loadFromFileCache( $this->context
);
599 # Do any stats increment/watchlist stuff
600 $article = WikiPage
::factory( $wgTitle );
601 $article->doViewUpdates( $user );
602 # Tell OutputPage that output is taken care of
603 $this->context
->getOutput()->disable();
604 wfProfileOut( 'main-try-filecache' );
605 wfProfileOut( __METHOD__
);
609 wfProfileOut( 'main-try-filecache' );
612 $this->performRequest();
613 $this->finalCleanup();
615 wfProfileOut( __METHOD__
);