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