Rename messages from r90670
[mediawiki.git] / includes / Wiki.php
blob1ab94c23b67302139691f308ab4a735613921192
1 <?php
2 /**
3 * MediaWiki is the to-be base class for this whole project
5 * @internal documentation reviewed 15 Mar 2010
6 */
7 class MediaWiki {
9 /**
10 * TODO: fold $output, etc, into this
11 * @var RequestContext
13 private $context;
15 public function request( WebRequest $x = null ){
16 $old = $this->context->getRequest();
17 $this->context->setRequest( $x );
18 return $old;
21 public function output( OutputPage $x = null ){
22 $old = $this->context->getOutput();
23 $this->context->setOutput( $x );
24 return $old;
27 public function __construct( RequestContext $context = null ) {
28 if ( !$context ) {
29 $context = RequestContext::getMain();
32 $this->context = $context;
33 $this->context->setTitle( $this->parseTitle() );
36 /**
37 * Parse $request to get the Title object
39 * @return Title object to be $wgTitle
41 private function parseTitle() {
42 global $wgContLang;
44 $request = $this->context->getRequest();
45 $curid = $request->getInt( 'curid' );
46 $title = $request->getVal( 'title' );
48 if ( $request->getCheck( 'search' ) ) {
49 // Compatibility with old search URLs which didn't use Special:Search
50 // Just check for presence here, so blank requests still
51 // show the search page when using ugly URLs (bug 8054).
52 $ret = SpecialPage::getTitleFor( 'Search' );
53 } elseif ( $curid ) {
54 // URLs like this are generated by RC, because rc_title isn't always accurate
55 $ret = Title::newFromID( $curid );
56 } elseif ( $title == '' && $this->getAction() != 'delete' ) {
57 $ret = Title::newMainPage();
58 } else {
59 $ret = Title::newFromURL( $title );
60 // check variant links so that interwiki links don't have to worry
61 // about the possible different language variants
62 if ( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 ){
63 $wgContLang->findVariantLink( $title, $ret );
66 // For non-special titles, check for implicit titles
67 if ( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
68 // We can have urls with just ?diff=,?oldid= or even just ?diff=
69 $oldid = $request->getInt( 'oldid' );
70 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
71 // Allow oldid to override a changed or missing title
72 if ( $oldid ) {
73 $rev = Revision::newFromId( $oldid );
74 $ret = $rev ? $rev->getTitle() : $ret;
78 if( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ){
79 $ret = new BadTitle;
81 return $ret;
84 /**
85 * Get the Title object that we'll be acting on, as specified in the WebRequest
86 * @return Title
88 public function getTitle(){
89 if( $this->context->getTitle() === null ){
90 $this->context->setTitle( $this->parseTitle() );
92 return $this->context->getTitle();
95 /**
96 * Performs the request.
97 * - bad titles
98 * - read restriction
99 * - local interwiki redirects
100 * - redirect loop
101 * - special pages
102 * - normal pages
104 * @return Article object
106 public function performRequest() {
107 global $wgServer, $wgUsePathInfo;
109 wfProfileIn( __METHOD__ );
111 $request = $this->context->getRequest();
112 $title = $this->context->getTitle();
113 $output = $this->context->getOutput();
114 $user = $this->context->getUser();
116 # Promote user to any groups they meet the criteria for
117 $user->addAutopromoteOnceGroups( 'onView' );
119 if ( $request->getVal( 'printable' ) === 'yes' ) {
120 $output->setPrintable();
123 wfRunHooks( 'BeforeInitialize', array(
124 &$title,
125 null,
126 &$output,
127 &$user,
128 $request,
129 $this
130 ) );
132 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
133 if ( $title instanceof BadTitle ) {
134 throw new ErrorPageError( 'badtitle', 'badtitletext' );
135 // If the user is not logged in, the Namespace:title of the article must be in
136 // the Read array in order for the user to see it. (We have to check here to
137 // catch special pages etc. We check again in Article::view())
138 } elseif ( !$title->userCanRead() ) {
139 $output->loginToUse();
140 // Interwiki redirects
141 } elseif ( $title->getInterwiki() != '' ) {
142 $rdfrom = $request->getVal( 'rdfrom' );
143 if ( $rdfrom ) {
144 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
145 } else {
146 $query = $request->getValues();
147 unset( $query['title'] );
148 $url = $title->getFullURL( $query );
150 // Check for a redirect loop
151 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url ) && $title->isLocal() ) {
152 // 301 so google et al report the target as the actual url.
153 $output->redirect( $url, 301 );
154 } else {
155 $this->context->setTitle( new BadTitle );
156 wfProfileOut( __METHOD__ );
157 throw new ErrorPageError( 'badtitle', 'badtitletext' );
159 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
160 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
161 && ( $request->getVal( 'title' ) === null || $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
162 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
164 if ( $title->getNamespace() == NS_SPECIAL ) {
165 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
166 if ( $name ) {
167 $title = SpecialPage::getTitleFor( $name, $subpage );
170 $targetUrl = $title->getFullURL();
171 // Redirect to canonical url, make it a 301 to allow caching
172 if ( $targetUrl == $request->getFullRequestURL() ) {
173 $message = "Redirect loop detected!\n\n" .
174 "This means the wiki got confused about what page was " .
175 "requested; this sometimes happens when moving a wiki " .
176 "to a new server or changing the server configuration.\n\n";
178 if ( $wgUsePathInfo ) {
179 $message .= "The wiki is trying to interpret the page " .
180 "title from the URL path portion (PATH_INFO), which " .
181 "sometimes fails depending on the web server. Try " .
182 "setting \"\$wgUsePathInfo = false;\" in your " .
183 "LocalSettings.php, or check that \$wgArticlePath " .
184 "is correct.";
185 } else {
186 $message .= "Your web server was detected as possibly not " .
187 "supporting URL path components (PATH_INFO) correctly; " .
188 "check your LocalSettings.php for a customized " .
189 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
190 "to true.";
192 wfHttpError( 500, "Internal error", $message );
193 } else {
194 $output->setSquidMaxage( 1200 );
195 $output->redirect( $targetUrl, '301' );
197 // Special pages
198 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
199 // actions that need to be made when we have a special pages
200 SpecialPageFactory::executePath( $title, $this->context );
201 } else {
202 // ...otherwise treat it as an article view. The article
203 // may be a redirect to another article or URL.
204 $article = $this->initializeArticle();
205 if ( is_object( $article ) ) {
207 * $wgArticle is deprecated, do not use it. This will possibly be removed
208 * entirely in 1.20 or 1.21
209 * @deprecated since 1.19
211 global $wgArticle;
212 $wgArticle = $article;
214 $this->performAction( $article );
215 wfProfileOut( __METHOD__ );
216 return $article;
217 } elseif ( is_string( $article ) ) {
218 $output->redirect( $article );
219 } else {
220 wfProfileOut( __METHOD__ );
221 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
224 wfProfileOut( __METHOD__ );
228 * Create an Article object of the appropriate class for the given page.
230 * @deprecated in 1.19; use Article::newFromTitle() instead
231 * @param $title Title
232 * @param $context RequestContext
233 * @return Article object
235 public static function articleFromTitle( $title, RequestContext $context ) {
236 return Article::newFromTitle( $title, $context );
240 * Returns the action that will be executed, not necesserly the one passed
241 * passed through the "action" parameter. Actions disabled in
242 * $wgDisabledActions will be replaced by "nosuchaction"
244 * @return String: action
246 public function getAction() {
247 global $wgDisabledActions;
249 $request = $this->context->getRequest();
250 $action = $request->getVal( 'action', 'view' );
252 // Check for disabled actions
253 if ( in_array( $action, $wgDisabledActions ) ) {
254 return 'nosuchaction';
257 // Workaround for bug #20966: inability of IE to provide an action dependent
258 // on which submit button is clicked.
259 if ( $action === 'historysubmit' ) {
260 if ( $request->getBool( 'revisiondelete' ) ) {
261 return 'revisiondelete';
262 } else {
263 return 'view';
265 } elseif ( $action == 'editredlink' ) {
266 return 'edit';
269 return $action;
273 * Initialize the main Article object for "standard" actions (view, etc)
274 * Create an Article object for the page, following redirects if needed.
276 * @return mixed an Article, or a string to redirect to another URL
278 private function initializeArticle() {
279 global $wgDisableHardRedirects;
281 wfProfileIn( __METHOD__ );
283 $request = $this->context->getRequest();
284 $title = $this->context->getTitle();
286 $action = $request->getVal( 'action', 'view' );
287 $article = Article::newFromTitle( $title, $this->context );
288 // NS_MEDIAWIKI has no redirects.
289 // It is also used for CSS/JS, so performance matters here...
290 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
291 wfProfileOut( __METHOD__ );
292 return $article;
294 // Namespace might change when using redirects
295 // Check for redirects ...
296 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
297 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
298 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
299 !$request->getVal( 'diff' ) && // ... and not when showing diff
300 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
301 // ... and the article is not a non-redirect image page with associated file
302 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
304 // Give extensions a change to ignore/handle redirects as needed
305 $ignoreRedirect = $target = false;
307 wfRunHooks( 'InitializeArticleMaybeRedirect',
308 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
310 // Follow redirects only for... redirects.
311 // If $target is set, then a hook wanted to redirect.
312 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
313 // Is the target already set by an extension?
314 $target = $target ? $target : $article->followRedirect();
315 if ( is_string( $target ) ) {
316 if ( !$wgDisableHardRedirects ) {
317 // we'll need to redirect
318 wfProfileOut( __METHOD__ );
319 return $target;
322 if ( is_object( $target ) ) {
323 // Rewrite environment to redirected article
324 $rarticle = Article::newFromTitle( $target, $this->context );
325 $rarticle->loadPageData();
326 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
327 $rarticle->setRedirectedFrom( $title );
328 $article = $rarticle;
329 $this->context->setTitle( $target );
332 } else {
333 $this->context->setTitle( $article->getTitle() );
336 wfProfileOut( __METHOD__ );
337 return $article;
341 * Cleaning up request by doing deferred updates, DB transaction, and the output
343 public function finalCleanup() {
344 wfProfileIn( __METHOD__ );
345 // Now commit any transactions, so that unreported errors after
346 // output() don't roll back the whole DB transaction
347 $factory = wfGetLBFactory();
348 $factory->commitMasterChanges();
349 // Output everything!
350 $this->context->getOutput()->output();
351 // Do any deferred jobs
352 wfDoUpdates( 'commit' );
353 $this->doJobs();
354 wfProfileOut( __METHOD__ );
358 * Do a job from the job queue
360 private function doJobs() {
361 global $wgJobRunRate;
363 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
364 return;
366 if ( $wgJobRunRate < 1 ) {
367 $max = mt_getrandmax();
368 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
369 return;
371 $n = 1;
372 } else {
373 $n = intval( $wgJobRunRate );
376 while ( $n-- && false != ( $job = Job::pop() ) ) {
377 $output = $job->toString() . "\n";
378 $t = -wfTime();
379 $success = $job->run();
380 $t += wfTime();
381 $t = round( $t * 1000 );
382 if ( !$success ) {
383 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
384 } else {
385 $output .= "Success, Time: $t ms\n";
387 wfDebugLog( 'jobqueue', $output );
392 * Ends this task peacefully
394 public function restInPeace() {
395 MessageCache::logMessages();
396 wfLogProfilingData();
397 // Commit and close up!
398 $factory = wfGetLBFactory();
399 $factory->commitMasterChanges();
400 $factory->shutdown();
401 wfDebug( "Request ended normally\n" );
405 * Perform one of the "standard" actions
407 * @param $article Article
409 private function performAction( $article ) {
410 global $wgSquidMaxage, $wgUseExternalEditor;
412 wfProfileIn( __METHOD__ );
414 $request = $this->context->getRequest();
415 $output = $this->context->getOutput();
416 $title = $this->context->getTitle();
417 $user = $this->context->getUser();
419 if ( !wfRunHooks( 'MediaWikiPerformAction', array(
420 $output, $article, $title,
421 $user, $request, $this ) ) )
423 wfProfileOut( __METHOD__ );
424 return;
427 $act = $this->getAction();
429 $action = Action::factory( $act, $article );
430 if( $action instanceof Action ){
431 $action->show();
432 wfProfileOut( __METHOD__ );
433 return;
436 switch( $act ) {
437 case 'view':
438 $output->setSquidMaxage( $wgSquidMaxage );
439 $article->view();
440 break;
441 case 'raw': // includes JS/CSS
442 wfProfileIn( __METHOD__ . '-raw' );
443 $raw = new RawPage( $article );
444 $raw->view();
445 wfProfileOut( __METHOD__ . '-raw' );
446 break;
447 case 'delete':
448 case 'revert':
449 case 'rollback':
450 case 'protect':
451 case 'unprotect':
452 case 'render':
453 $article->$act();
454 break;
455 case 'submit':
456 if ( session_id() == '' ) {
457 // Send a cookie so anons get talk message notifications
458 wfSetupSession();
460 // Continue...
461 case 'edit':
462 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
463 $internal = $request->getVal( 'internaledit' );
464 $external = $request->getVal( 'externaledit' );
465 $section = $request->getVal( 'section' );
466 $oldid = $request->getVal( 'oldid' );
467 if ( !$wgUseExternalEditor || $act == 'submit' || $internal ||
468 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
469 $editor = new EditPage( $article );
470 $editor->submit();
471 } elseif ( $wgUseExternalEditor && ( $external || $user->getOption( 'externaleditor' ) ) ) {
472 $mode = $request->getVal( 'mode' );
473 $extedit = new ExternalEdit( $article, $mode );
474 $extedit->edit();
477 break;
478 case 'history':
479 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
480 $output->setSquidMaxage( $wgSquidMaxage );
482 $history = new HistoryPage( $article );
483 $history->history();
484 break;
485 default:
486 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
487 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
490 wfProfileOut( __METHOD__ );
494 * Run the current MediaWiki instance
495 * index.php just calls this
497 function run() {
498 try {
499 $this->checkMaxLag( true );
500 $this->main();
501 $this->restInPeace();
502 } catch ( Exception $e ) {
503 MWExceptionHandler::handle( $e );
508 * Checks if the request should abort due to a lagged server,
509 * for given maxlag parameter.
511 * @param boolean $abort True if this class should abort the
512 * script execution. False to return the result as a boolean.
513 * @return boolean True if we passed the check, false if we surpass the maxlag
515 function checkMaxLag( $abort ) {
516 global $wgShowHostnames;
518 wfProfileIn( __METHOD__ );
519 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
520 if ( !is_null( $maxLag ) ) {
521 $lb = wfGetLB(); // foo()->bar() is not supported in PHP4
522 list( $host, $lag ) = $lb->getMaxLag();
523 if ( $lag > $maxLag ) {
524 if ( $abort ) {
525 header( 'HTTP/1.1 503 Service Unavailable' );
526 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
527 header( 'X-Database-Lag: ' . intval( $lag ) );
528 header( 'Content-Type: text/plain' );
529 if( $wgShowHostnames ) {
530 echo "Waiting for $host: $lag seconds lagged\n";
531 } else {
532 echo "Waiting for a database server: $lag seconds lagged\n";
536 wfProfileOut( __METHOD__ );
538 if ( !$abort )
539 return false;
540 exit;
543 wfProfileOut( __METHOD__ );
544 return true;
547 function main() {
548 global $wgUseFileCache, $wgTitle, $wgUseAjax;
550 wfProfileIn( __METHOD__ );
552 # Set title from request parameters
553 $wgTitle = $this->getTitle();
554 $action = $this->getAction();
556 # Send Ajax requests to the Ajax dispatcher.
557 if ( $wgUseAjax && $action == 'ajax' ) {
558 $dispatcher = new AjaxDispatcher();
559 $dispatcher->performAction();
560 wfProfileOut( __METHOD__ );
561 return;
564 if ( $wgUseFileCache && $wgTitle !== null ) {
565 wfProfileIn( 'main-try-filecache' );
566 // Raw pages should handle cache control on their own,
567 // even when using file cache. This reduces hits from clients.
568 if ( $action != 'raw' && HTMLFileCache::useFileCache() ) {
569 /* Try low-level file cache hit */
570 $cache = new HTMLFileCache( $wgTitle, $action );
571 if ( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
572 /* Check incoming headers to see if client has this cached */
573 if ( !$this->context->getOutput()->checkLastModified( $cache->fileCacheTime() ) ) {
574 $cache->loadFromFileCache();
576 # Do any stats increment/watchlist stuff
577 $article = Article::newFromTitle( $wgTitle, $this->context );
578 $article->viewUpdates();
579 # Tell OutputPage that output is taken care of
580 $this->context->getOutput()->disable();
581 wfProfileOut( 'main-try-filecache' );
582 wfProfileOut( __METHOD__ );
583 return;
586 wfProfileOut( 'main-try-filecache' );
589 $this->performRequest();
590 $this->finalCleanup();
592 wfProfileOut( __METHOD__ );