Reinstate r109223 per CR + fixes
[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 ErrorPageError( 'badtitle', 'badtitletext' );
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 ErrorPageError( 'badtitle', 'badtitletext' );
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 * This will be removed entirely in 1.20.
273 * @deprecated since 1.18
274 */
275 global $wgArticle;
276 $wgArticle = $article;
277
278 $this->performAction( $article );
279 } elseif ( is_string( $article ) ) {
280 $output->redirect( $article );
281 } else {
282 wfProfileOut( __METHOD__ );
283 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
284 }
285 }
286
287 if ( $pageView ) {
288 // Promote user to any groups they meet the criteria for
289 $user->addAutopromoteOnceGroups( 'onView' );
290 }
291
292 wfProfileOut( __METHOD__ );
293 }
294
295 /**
296 * Create an Article object of the appropriate class for the given page.
297 *
298 * @deprecated in 1.18; use Article::newFromTitle() instead
299 * @param $title Title
300 * @param $context IContextSource
301 * @return Article object
302 */
303 public static function articleFromTitle( $title, IContextSource $context ) {
304 wfDeprecated( __METHOD__, '1.18' );
305 return Article::newFromTitle( $title, $context );
306 }
307
308 /**
309 * Returns the name of the action that will be executed.
310 *
311 * @return string: action
312 */
313 public function getAction() {
314 static $action = null;
315
316 if ( $action === null ) {
317 $action = Action::getActionName( $this->context );
318 }
319
320 return $action;
321 }
322
323 /**
324 * Initialize the main Article object for "standard" actions (view, etc)
325 * Create an Article object for the page, following redirects if needed.
326 *
327 * @return mixed an Article, or a string to redirect to another URL
328 */
329 private function initializeArticle() {
330 global $wgDisableHardRedirects;
331
332 wfProfileIn( __METHOD__ );
333
334 $title = $this->context->getTitle();
335 $article = Article::newFromTitle( $title, $this->context );
336 $this->context->setWikiPage( $article->getPage() );
337 // NS_MEDIAWIKI has no redirects.
338 // It is also used for CSS/JS, so performance matters here...
339 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
340 wfProfileOut( __METHOD__ );
341 return $article;
342 }
343
344 $request = $this->context->getRequest();
345
346 // Namespace might change when using redirects
347 // Check for redirects ...
348 $action = $request->getVal( 'action', 'view' );
349 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
350 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
351 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
352 !$request->getVal( 'diff' ) && // ... and not when showing diff
353 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
354 // ... and the article is not a non-redirect image page with associated file
355 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
356 {
357 // Give extensions a change to ignore/handle redirects as needed
358 $ignoreRedirect = $target = false;
359
360 wfRunHooks( 'InitializeArticleMaybeRedirect',
361 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
362
363 // Follow redirects only for... redirects.
364 // If $target is set, then a hook wanted to redirect.
365 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
366 // Is the target already set by an extension?
367 $target = $target ? $target : $article->followRedirect();
368 if ( is_string( $target ) ) {
369 if ( !$wgDisableHardRedirects ) {
370 // we'll need to redirect
371 wfProfileOut( __METHOD__ );
372 return $target;
373 }
374 }
375 if ( is_object( $target ) ) {
376 // Rewrite environment to redirected article
377 $rarticle = Article::newFromTitle( $target, $this->context );
378 $rarticle->loadPageData();
379 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
380 $rarticle->setRedirectedFrom( $title );
381 $article = $rarticle;
382 $this->context->setTitle( $target );
383 $this->context->setWikiPage( $article->getPage() );
384 }
385 }
386 } else {
387 $this->context->setTitle( $article->getTitle() );
388 $this->context->setWikiPage( $article->getPage() );
389 }
390 }
391
392 wfProfileOut( __METHOD__ );
393 return $article;
394 }
395
396 /**
397 * Cleaning up request by doing deferred updates, DB transaction, and the output
398 */
399 public function finalCleanup() {
400 wfProfileIn( __METHOD__ );
401 // Now commit any transactions, so that unreported errors after
402 // output() don't roll back the whole DB transaction
403 $factory = wfGetLBFactory();
404 $factory->commitMasterChanges();
405 // Output everything!
406 $this->context->getOutput()->output();
407 // Do any deferred jobs
408 DeferredUpdates::doUpdates( 'commit' );
409 $this->doJobs();
410 wfProfileOut( __METHOD__ );
411 }
412
413 /**
414 * Do a job from the job queue
415 */
416 private function doJobs() {
417 global $wgJobRunRate;
418
419 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
420 return;
421 }
422 if ( $wgJobRunRate < 1 ) {
423 $max = mt_getrandmax();
424 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
425 return;
426 }
427 $n = 1;
428 } else {
429 $n = intval( $wgJobRunRate );
430 }
431
432 while ( $n-- && false != ( $job = Job::pop() ) ) {
433 $output = $job->toString() . "\n";
434 $t = -wfTime();
435 $success = $job->run();
436 $t += wfTime();
437 $t = round( $t * 1000 );
438 if ( !$success ) {
439 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
440 } else {
441 $output .= "Success, Time: $t ms\n";
442 }
443 wfDebugLog( 'jobqueue', $output );
444 }
445 }
446
447 /**
448 * Ends this task peacefully
449 */
450 public function restInPeace() {
451 MessageCache::logMessages();
452 wfLogProfilingData();
453 // Commit and close up!
454 $factory = wfGetLBFactory();
455 $factory->commitMasterChanges();
456 $factory->shutdown();
457 wfDebug( "Request ended normally\n" );
458 }
459
460 /**
461 * Perform one of the "standard" actions
462 *
463 * @param $article Article
464 */
465 private function performAction( Page $article ) {
466 global $wgSquidMaxage;
467
468 wfProfileIn( __METHOD__ );
469
470 $request = $this->context->getRequest();
471 $output = $this->context->getOutput();
472 $title = $this->context->getTitle();
473 $user = $this->context->getUser();
474
475 if ( !wfRunHooks( 'MediaWikiPerformAction',
476 array( $output, $article, $title, $user, $request, $this ) ) )
477 {
478 wfProfileOut( __METHOD__ );
479 return;
480 }
481
482 $act = $this->getAction();
483
484 $action = Action::factory( $act, $article );
485 if ( $action instanceof Action ) {
486 $action->show();
487 wfProfileOut( __METHOD__ );
488 return;
489 }
490
491 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
492 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
493 }
494
495 wfProfileOut( __METHOD__ );
496 }
497
498 /**
499 * Run the current MediaWiki instance
500 * index.php just calls this
501 */
502 public function run() {
503 try {
504 $this->checkMaxLag();
505 $this->main();
506 $this->restInPeace();
507 } catch ( Exception $e ) {
508 MWExceptionHandler::handle( $e );
509 }
510 }
511
512 /**
513 * Checks if the request should abort due to a lagged server,
514 * for given maxlag parameter.
515 * @return bool
516 */
517 private function checkMaxLag() {
518 global $wgShowHostnames;
519
520 wfProfileIn( __METHOD__ );
521 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
522 if ( !is_null( $maxLag ) ) {
523 list( $host, $lag ) = wfGetLB()->getMaxLag();
524 if ( $lag > $maxLag ) {
525 $resp = $this->context->getRequest()->response();
526 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
527 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
528 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
529 $resp->header( 'Content-Type: text/plain' );
530 if( $wgShowHostnames ) {
531 echo "Waiting for $host: $lag seconds lagged\n";
532 } else {
533 echo "Waiting for a database server: $lag seconds lagged\n";
534 }
535
536 wfProfileOut( __METHOD__ );
537
538 exit;
539 }
540 }
541 wfProfileOut( __METHOD__ );
542 return true;
543 }
544
545 private function main() {
546 global $wgUseFileCache, $wgTitle, $wgUseAjax;
547
548 wfProfileIn( __METHOD__ );
549
550 # Set title from request parameters
551 $wgTitle = $this->getTitle();
552 $action = $this->getAction();
553
554 # Send Ajax requests to the Ajax dispatcher.
555 if ( $wgUseAjax && $action == 'ajax' ) {
556 $dispatcher = new AjaxDispatcher();
557 $dispatcher->performAction();
558 wfProfileOut( __METHOD__ );
559 return;
560 }
561
562 if ( $wgUseFileCache && $this->getTitle()->getNamespace() >= 0 ) {
563 wfProfileIn( 'main-try-filecache' );
564 if ( HTMLFileCache::useFileCache( $this->context ) ) {
565 /* Try low-level file cache hit */
566 $cache = HTMLFileCache::newFromTitle( $this->getTitle(), $action );
567 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
568 /* Check incoming headers to see if client has this cached */
569 $timestamp = $cache->cacheTimestamp();
570 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
571 $cache->loadFromFileCache( $this->context );
572 }
573 # Do any stats increment/watchlist stuff
574 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
575 # Tell OutputPage that output is taken care of
576 $this->context->getOutput()->disable();
577 wfProfileOut( 'main-try-filecache' );
578 wfProfileOut( __METHOD__ );
579 return;
580 }
581 }
582 wfProfileOut( 'main-try-filecache' );
583 }
584
585 $this->performRequest();
586 $this->finalCleanup();
587
588 wfProfileOut( __METHOD__ );
589 }
590 }