Reverted r108743 per CR comment. This should at least be discussed first.
[lhc/web/wiklou.git] / includes / Wiki.php
1 <?php
2 /**
3 * Helper class for the index.php entry point.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * The MediaWiki class is the helper class for the index.php entry point.
25 *
26 * @internal documentation reviewed 15 Mar 2010
27 */
28 class MediaWiki {
29
30 /**
31 * TODO: fold $output, etc, into this
32 * @var IContextSource
33 */
34 private $context;
35
36 /**
37 * @var string
38 */
39 private $performedAction = 'nosuchaction';
40
41 /**
42 * @param $x null|WebRequest
43 * @return WebRequest
44 */
45 public function request( WebRequest $x = null ) {
46 $old = $this->context->getRequest();
47 $this->context->setRequest( $x );
48 return $old;
49 }
50
51 /**
52 * @param $x null|OutputPage
53 * @return OutputPage
54 */
55 public function output( OutputPage $x = null ) {
56 $old = $this->context->getOutput();
57 $this->context->setOutput( $x );
58 return $old;
59 }
60
61 /**
62 * @param IContextSource|null $context
63 */
64 public function __construct( IContextSource $context = null ) {
65 if ( !$context ) {
66 $context = RequestContext::getMain();
67 }
68
69 $this->context = $context;
70 $this->context->setTitle( $this->parseTitle() );
71 }
72
73 /**
74 * Parse the request to get the Title object
75 *
76 * @return Title object to be $wgTitle
77 */
78 private function parseTitle() {
79 global $wgContLang;
80
81 $request = $this->context->getRequest();
82 $curid = $request->getInt( 'curid' );
83 $title = $request->getVal( 'title' );
84
85 if ( $request->getCheck( 'search' ) ) {
86 // Compatibility with old search URLs which didn't use Special:Search
87 // Just check for presence here, so blank requests still
88 // show the search page when using ugly URLs (bug 8054).
89 $ret = SpecialPage::getTitleFor( 'Search' );
90 } elseif ( $curid ) {
91 // URLs like this are generated by RC, because rc_title isn't always accurate
92 $ret = Title::newFromID( $curid );
93 } elseif ( $title == '' && $this->getAction() != 'delete' ) {
94 $ret = Title::newMainPage();
95 } else {
96 $ret = Title::newFromURL( $title );
97 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
98 // in wikitext links to tell Parser to make a direct file link
99 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) {
100 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
101 }
102 // Check variant links so that interwiki links don't have to worry
103 // about the possible different language variants
104 if ( count( $wgContLang->getVariants() ) > 1
105 && !is_null( $ret ) && $ret->getArticleID() == 0 )
106 {
107 $wgContLang->findVariantLink( $title, $ret );
108 }
109 }
110 // For non-special titles, check for implicit titles
111 if ( is_null( $ret ) || !$ret->isSpecialPage() ) {
112 // We can have urls with just ?diff=,?oldid= or even just ?diff=
113 $oldid = $request->getInt( 'oldid' );
114 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
115 // Allow oldid to override a changed or missing title
116 if ( $oldid ) {
117 $rev = Revision::newFromId( $oldid );
118 $ret = $rev ? $rev->getTitle() : $ret;
119 }
120 }
121
122 if ( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
123 $ret = SpecialPage::getTitleFor( 'Badtitle' );
124 }
125
126 return $ret;
127 }
128
129 /**
130 * Get the Title object that we'll be acting on, as specified in the WebRequest
131 * @return Title
132 */
133 public function getTitle() {
134 if( $this->context->getTitle() === null ){
135 $this->context->setTitle( $this->parseTitle() );
136 }
137 return $this->context->getTitle();
138 }
139
140 /**
141 * Performs the request.
142 * - bad titles
143 * - read restriction
144 * - local interwiki redirects
145 * - redirect loop
146 * - special pages
147 * - normal pages
148 *
149 * @return void
150 */
151 private function performRequest() {
152 global $wgServer, $wgUsePathInfo, $wgTitle;
153
154 wfProfileIn( __METHOD__ );
155
156 $request = $this->context->getRequest();
157 $title = $this->context->getTitle();
158 $output = $this->context->getOutput();
159 $user = $this->context->getUser();
160
161 if ( $request->getVal( 'printable' ) === 'yes' ) {
162 $output->setPrintable();
163 }
164
165 $unused = null; // To pass it by reference
166 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
167
168 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
169 if ( is_null( $title ) || ( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
170 $title->isSpecial( 'Badtitle' ) )
171 {
172 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
173 wfProfileOut( __METHOD__ );
174 throw new ErrorPageError( 'badtitle', 'badtitletext' );
175 }
176
177 // Check user's permissions to read this page.
178 // We have to check here to catch special pages etc.
179 // We will check again in Article::view().
180 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
181 if ( count( $permErrors ) ) {
182 // Bug 32276: allowing the skin to generate output with $wgTitle or
183 // $this->context->title set to the input title would allow anonymous users to
184 // determine whether a page exists, potentially leaking private data. In fact, the
185 // curid and oldid request parameters would allow page titles to be enumerated even
186 // when they are not guessable. So we reset the title to Special:Badtitle before the
187 // permissions error is displayed.
188 //
189 // The skin mostly uses $this->context->getTitle() these days, but some extensions
190 // still use $wgTitle.
191
192 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
193 $this->context->setTitle( $badTitle );
194 $wgTitle = $badTitle;
195
196 wfProfileOut( __METHOD__ );
197 throw new PermissionsError( 'read', $permErrors );
198 }
199
200 $pageView = false; // was an article or special page viewed?
201
202 // Interwiki redirects
203 if ( $title->getInterwiki() != '' ) {
204 $rdfrom = $request->getVal( 'rdfrom' );
205 if ( $rdfrom ) {
206 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
207 } else {
208 $query = $request->getValues();
209 unset( $query['title'] );
210 $url = $title->getFullURL( $query );
211 }
212 // Check for a redirect loop
213 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
214 && $title->isLocal() )
215 {
216 // 301 so google et al report the target as the actual url.
217 $output->redirect( $url, 301 );
218 } else {
219 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
220 wfProfileOut( __METHOD__ );
221 throw new ErrorPageError( 'badtitle', 'badtitletext' );
222 }
223 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
224 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
225 && ( $request->getVal( 'title' ) === null ||
226 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
227 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
228 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
229 {
230 if ( $title->isSpecialPage() ) {
231 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
232 if ( $name ) {
233 $title = SpecialPage::getTitleFor( $name, $subpage );
234 }
235 }
236 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
237 // Redirect to canonical url, make it a 301 to allow caching
238 if ( $targetUrl == $request->getFullRequestURL() ) {
239 $message = "Redirect loop detected!\n\n" .
240 "This means the wiki got confused about what page was " .
241 "requested; this sometimes happens when moving a wiki " .
242 "to a new server or changing the server configuration.\n\n";
243
244 if ( $wgUsePathInfo ) {
245 $message .= "The wiki is trying to interpret the page " .
246 "title from the URL path portion (PATH_INFO), which " .
247 "sometimes fails depending on the web server. Try " .
248 "setting \"\$wgUsePathInfo = false;\" in your " .
249 "LocalSettings.php, or check that \$wgArticlePath " .
250 "is correct.";
251 } else {
252 $message .= "Your web server was detected as possibly not " .
253 "supporting URL path components (PATH_INFO) correctly; " .
254 "check your LocalSettings.php for a customized " .
255 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
256 "to true.";
257 }
258 throw new HttpError( 500, $message );
259 } else {
260 $output->setSquidMaxage( 1200 );
261 $output->redirect( $targetUrl, '301' );
262 }
263 // Special pages
264 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
265 $pageView = true;
266 // Actions that need to be made when we have a special pages
267 SpecialPageFactory::executePath( $title, $this->context );
268 } else {
269 // ...otherwise treat it as an article view. The article
270 // may be a redirect to another article or URL.
271 $article = $this->initializeArticle();
272 if ( is_object( $article ) ) {
273 $pageView = true;
274 /**
275 * $wgArticle is deprecated, do not use it.
276 * This will be removed entirely in 1.20.
277 * @deprecated since 1.18
278 */
279 global $wgArticle;
280 $wgArticle = $article;
281
282 $this->performAction( $article );
283 } elseif ( is_string( $article ) ) {
284 $output->redirect( $article );
285 } else {
286 wfProfileOut( __METHOD__ );
287 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
288 }
289 }
290
291 if ( $pageView ) {
292 // Promote user to any groups they meet the criteria for
293 $user->addAutopromoteOnceGroups( 'onView' );
294 }
295
296 wfProfileOut( __METHOD__ );
297 }
298
299 /**
300 * Create an Article object of the appropriate class for the given page.
301 *
302 * @deprecated in 1.18; use Article::newFromTitle() instead
303 * @param $title Title
304 * @param $context IContextSource
305 * @return Article object
306 */
307 public static function articleFromTitle( $title, IContextSource $context ) {
308 wfDeprecated( __METHOD__, '1.18' );
309 return Article::newFromTitle( $title, $context );
310 }
311
312 /**
313 * Returns the action that will be executed, not necessarily the one passed
314 * passed through the "action" parameter. Actions disabled in
315 * $wgDisabledActions will be replaced by "nosuchaction".
316 *
317 * The return value is merely a suggestion, not the actually performed action,
318 * which may be different. The actually performed action is determined by performAction().
319 * Requests like action=nonsense will make this function return "nonsense".
320 * Use getPerformedAction() to get the performed action.
321 *
322 * @return string: action
323 */
324 public function getAction() {
325 global $wgDisabledActions;
326
327 $request = $this->context->getRequest();
328 $action = $request->getVal( 'action', 'view' );
329
330 // Check for disabled actions
331 if ( in_array( $action, $wgDisabledActions ) ) {
332 return 'nosuchaction';
333 }
334
335 // Workaround for bug #20966: inability of IE to provide an action dependent
336 // on which submit button is clicked.
337 if ( $action === 'historysubmit' ) {
338 if ( $request->getBool( 'revisiondelete' ) ) {
339 return 'revisiondelete';
340 } else {
341 return 'view';
342 }
343 } elseif ( $action == 'editredlink' ) {
344 return 'edit';
345 }
346
347 return $action;
348 }
349
350 /**
351 * Initialize the main Article object for "standard" actions (view, etc)
352 * Create an Article object for the page, following redirects if needed.
353 *
354 * @return mixed an Article, or a string to redirect to another URL
355 */
356 private function initializeArticle() {
357 global $wgDisableHardRedirects;
358
359 wfProfileIn( __METHOD__ );
360
361 $title = $this->context->getTitle();
362 $article = Article::newFromTitle( $title, $this->context );
363 $this->context->setWikiPage( $article->getPage() );
364 // NS_MEDIAWIKI has no redirects.
365 // It is also used for CSS/JS, so performance matters here...
366 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
367 wfProfileOut( __METHOD__ );
368 return $article;
369 }
370
371 $request = $this->context->getRequest();
372
373 // Namespace might change when using redirects
374 // Check for redirects ...
375 $action = $request->getVal( 'action', 'view' );
376 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
377 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
378 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
379 !$request->getVal( 'diff' ) && // ... and not when showing diff
380 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
381 // ... and the article is not a non-redirect image page with associated file
382 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
383 {
384 // Give extensions a change to ignore/handle redirects as needed
385 $ignoreRedirect = $target = false;
386
387 wfRunHooks( 'InitializeArticleMaybeRedirect',
388 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
389
390 // Follow redirects only for... redirects.
391 // If $target is set, then a hook wanted to redirect.
392 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
393 // Is the target already set by an extension?
394 $target = $target ? $target : $article->followRedirect();
395 if ( is_string( $target ) ) {
396 if ( !$wgDisableHardRedirects ) {
397 // we'll need to redirect
398 wfProfileOut( __METHOD__ );
399 return $target;
400 }
401 }
402 if ( is_object( $target ) ) {
403 // Rewrite environment to redirected article
404 $rarticle = Article::newFromTitle( $target, $this->context );
405 $rarticle->loadPageData();
406 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
407 $rarticle->setRedirectedFrom( $title );
408 $article = $rarticle;
409 $this->context->setTitle( $target );
410 $this->context->setWikiPage( $article->getPage() );
411 }
412 }
413 } else {
414 $this->context->setTitle( $article->getTitle() );
415 $this->context->setWikiPage( $article->getPage() );
416 }
417 }
418
419 wfProfileOut( __METHOD__ );
420 return $article;
421 }
422
423 /**
424 * Cleaning up request by doing deferred updates, DB transaction, and the output
425 */
426 public function finalCleanup() {
427 wfProfileIn( __METHOD__ );
428 // Now commit any transactions, so that unreported errors after
429 // output() don't roll back the whole DB transaction
430 $factory = wfGetLBFactory();
431 $factory->commitMasterChanges();
432 // Output everything!
433 $this->context->getOutput()->output();
434 // Do any deferred jobs
435 DeferredUpdates::doUpdates( 'commit' );
436 $this->doJobs();
437 wfProfileOut( __METHOD__ );
438 }
439
440 /**
441 * Do a job from the job queue
442 */
443 private function doJobs() {
444 global $wgJobRunRate;
445
446 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
447 return;
448 }
449 if ( $wgJobRunRate < 1 ) {
450 $max = mt_getrandmax();
451 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
452 return;
453 }
454 $n = 1;
455 } else {
456 $n = intval( $wgJobRunRate );
457 }
458
459 while ( $n-- && false != ( $job = Job::pop() ) ) {
460 $output = $job->toString() . "\n";
461 $t = -wfTime();
462 $success = $job->run();
463 $t += wfTime();
464 $t = round( $t * 1000 );
465 if ( !$success ) {
466 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
467 } else {
468 $output .= "Success, Time: $t ms\n";
469 }
470 wfDebugLog( 'jobqueue', $output );
471 }
472 }
473
474 /**
475 * Ends this task peacefully
476 */
477 public function restInPeace() {
478 MessageCache::logMessages();
479 wfLogProfilingData();
480 // Commit and close up!
481 $factory = wfGetLBFactory();
482 $factory->commitMasterChanges();
483 $factory->shutdown();
484 wfDebug( "Request ended normally\n" );
485 }
486
487 /**
488 * Perform one of the "standard" actions
489 *
490 * @param $article Article
491 */
492 private function performAction( Page $article ) {
493 global $wgSquidMaxage;
494
495 wfProfileIn( __METHOD__ );
496
497 $request = $this->context->getRequest();
498 $output = $this->context->getOutput();
499 $title = $this->context->getTitle();
500 $user = $this->context->getUser();
501
502 if ( !wfRunHooks( 'MediaWikiPerformAction',
503 array( $output, $article, $title, $user, $request, $this ) ) )
504 {
505 wfProfileOut( __METHOD__ );
506 return;
507 }
508
509 $act = $this->getAction();
510
511 $action = Action::factory( $act, $article );
512 if ( $action instanceof Action ) {
513 $this->performedAction = $act;
514 $action->show();
515 wfProfileOut( __METHOD__ );
516 return;
517 }
518
519 switch( $act ) {
520 case 'view':
521 $output->setSquidMaxage( $wgSquidMaxage );
522 $this->performedAction = $act;
523 $article->view();
524 break;
525 case 'delete':
526 case 'protect':
527 case 'unprotect':
528 case 'render':
529 $this->performedAction = $act;
530 $article->$act();
531 break;
532 case 'submit':
533 if ( session_id() == '' ) {
534 // Send a cookie so anons get talk message notifications
535 wfSetupSession();
536 }
537 // Continue...
538 case 'edit':
539 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
540 $this->performedAction = 'edit';
541 if ( ExternalEdit::useExternalEngine( $this->context, 'edit' )
542 && $act == 'edit' && !$request->getVal( 'section' )
543 && !$request->getVal( 'oldid' ) )
544 {
545 $extedit = new ExternalEdit( $this->context );
546 $extedit->execute();
547 } else {
548 $editor = new EditPage( $article );
549 $editor->edit();
550 }
551 }
552 break;
553 default:
554 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
555 $this->performedAction = 'nosuchaction';
556 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
557 }
558 }
559 wfProfileOut( __METHOD__ );
560 }
561
562 /**
563 * Returns the real action as determined by performAction.
564 * Do not use internally in this class as it depends on the actions by this class.
565 *
566 * @since 1.19
567 *
568 * @return string: action
569 */
570 public function getPerformedAction() {
571 return $this->performedAction;
572 }
573
574 /**
575 * Run the current MediaWiki instance
576 * index.php just calls this
577 */
578 public function run() {
579 try {
580 $this->checkMaxLag();
581 $this->main();
582 $this->restInPeace();
583 } catch ( Exception $e ) {
584 MWExceptionHandler::handle( $e );
585 }
586 }
587
588 /**
589 * Checks if the request should abort due to a lagged server,
590 * for given maxlag parameter.
591 * @return bool
592 */
593 private function checkMaxLag() {
594 global $wgShowHostnames;
595
596 wfProfileIn( __METHOD__ );
597 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
598 if ( !is_null( $maxLag ) ) {
599 list( $host, $lag ) = wfGetLB()->getMaxLag();
600 if ( $lag > $maxLag ) {
601 $resp = $this->context->getRequest()->response();
602 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
603 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
604 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
605 $resp->header( 'Content-Type: text/plain' );
606 if( $wgShowHostnames ) {
607 echo "Waiting for $host: $lag seconds lagged\n";
608 } else {
609 echo "Waiting for a database server: $lag seconds lagged\n";
610 }
611
612 wfProfileOut( __METHOD__ );
613
614 exit;
615 }
616 }
617 wfProfileOut( __METHOD__ );
618 return true;
619 }
620
621 private function main() {
622 global $wgUseFileCache, $wgTitle, $wgUseAjax;
623
624 wfProfileIn( __METHOD__ );
625
626 # Set title from request parameters
627 $wgTitle = $this->getTitle();
628 $action = $this->getAction();
629
630 # Send Ajax requests to the Ajax dispatcher.
631 if ( $wgUseAjax && $action == 'ajax' ) {
632 $dispatcher = new AjaxDispatcher();
633 $dispatcher->performAction();
634 wfProfileOut( __METHOD__ );
635 return;
636 }
637
638 if ( $wgUseFileCache && $this->getTitle()->getNamespace() >= 0 ) {
639 wfProfileIn( 'main-try-filecache' );
640 if ( HTMLFileCache::useFileCache( $this->context ) ) {
641 /* Try low-level file cache hit */
642 $cache = HTMLFileCache::newFromTitle( $this->getTitle(), $action );
643 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
644 /* Check incoming headers to see if client has this cached */
645 $timestamp = $cache->cacheTimestamp();
646 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
647 $cache->loadFromFileCache( $this->context );
648 }
649 # Do any stats increment/watchlist stuff
650 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
651 # Tell OutputPage that output is taken care of
652 $this->context->getOutput()->disable();
653 wfProfileOut( 'main-try-filecache' );
654 wfProfileOut( __METHOD__ );
655 return;
656 }
657 }
658 wfProfileOut( 'main-try-filecache' );
659 }
660
661 $this->performRequest();
662 $this->finalCleanup();
663
664 wfProfileOut( __METHOD__ );
665 }
666 }