Merge "Fixed dependencies for jquery.collapsibleTabs"
[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 }
66
67 /**
68 * Parse the request to get the Title object
69 *
70 * @return Title object to be $wgTitle
71 */
72 private function parseTitle() {
73 global $wgContLang;
74
75 $request = $this->context->getRequest();
76 $curid = $request->getInt( 'curid' );
77 $title = $request->getVal( 'title' );
78 $action = $request->getVal( 'action', 'view' );
79
80 if ( $request->getCheck( 'search' ) ) {
81 // Compatibility with old search URLs which didn't use Special:Search
82 // Just check for presence here, so blank requests still
83 // show the search page when using ugly URLs (bug 8054).
84 $ret = SpecialPage::getTitleFor( 'Search' );
85 } elseif ( $curid ) {
86 // URLs like this are generated by RC, because rc_title isn't always accurate
87 $ret = Title::newFromID( $curid );
88 } elseif ( $title == '' && $action != 'delete' ) {
89 $ret = Title::newMainPage();
90 } else {
91 $ret = Title::newFromURL( $title );
92 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
93 // in wikitext links to tell Parser to make a direct file link
94 if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) {
95 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
96 }
97 // Check variant links so that interwiki links don't have to worry
98 // about the possible different language variants
99 if ( count( $wgContLang->getVariants() ) > 1
100 && !is_null( $ret ) && $ret->getArticleID() == 0 )
101 {
102 $wgContLang->findVariantLink( $title, $ret );
103 }
104 }
105 // For non-special titles, check for implicit titles
106 if ( is_null( $ret ) || !$ret->isSpecialPage() ) {
107 // We can have urls with just ?diff=,?oldid= or even just ?diff=
108 $oldid = $request->getInt( 'oldid' );
109 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
110 // Allow oldid to override a changed or missing title
111 if ( $oldid ) {
112 $rev = Revision::newFromId( $oldid );
113 $ret = $rev ? $rev->getTitle() : $ret;
114 }
115 }
116
117 if ( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ) {
118 $ret = SpecialPage::getTitleFor( 'Badtitle' );
119 }
120
121 return $ret;
122 }
123
124 /**
125 * Get the Title object that we'll be acting on, as specified in the WebRequest
126 * @return Title
127 */
128 public function getTitle() {
129 if( $this->context->getTitle() === null ){
130 $this->context->setTitle( $this->parseTitle() );
131 }
132 return $this->context->getTitle();
133 }
134
135 /**
136 * Returns the name of the action that will be executed.
137 *
138 * @return string: action
139 */
140 public function getAction() {
141 static $action = null;
142
143 if ( $action === null ) {
144 $action = Action::getActionName( $this->context );
145 }
146
147 return $action;
148 }
149
150 /**
151 * Create an Article object of the appropriate class for the given page.
152 *
153 * @deprecated in 1.18; use Article::newFromTitle() instead
154 * @param $title Title
155 * @param $context IContextSource
156 * @return Article object
157 */
158 public static function articleFromTitle( $title, IContextSource $context ) {
159 wfDeprecated( __METHOD__, '1.18' );
160 return Article::newFromTitle( $title, $context );
161 }
162
163 /**
164 * Performs the request.
165 * - bad titles
166 * - read restriction
167 * - local interwiki redirects
168 * - redirect loop
169 * - special pages
170 * - normal pages
171 *
172 * @throws MWException|PermissionsError|BadTitleError|HttpError
173 * @return void
174 */
175 private function performRequest() {
176 global $wgServer, $wgUsePathInfo, $wgTitle;
177
178 wfProfileIn( __METHOD__ );
179
180 $request = $this->context->getRequest();
181 $requestTitle = $title = $this->context->getTitle();
182 $output = $this->context->getOutput();
183 $user = $this->context->getUser();
184
185 if ( $request->getVal( 'printable' ) === 'yes' ) {
186 $output->setPrintable();
187 }
188
189 $unused = null; // To pass it by reference
190 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
191
192 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
193 if ( is_null( $title ) || ( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
194 $title->isSpecial( 'Badtitle' ) )
195 {
196 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
197 wfProfileOut( __METHOD__ );
198 throw new BadTitleError();
199 }
200
201 // Check user's permissions to read this page.
202 // We have to check here to catch special pages etc.
203 // We will check again in Article::view().
204 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
205 if ( count( $permErrors ) ) {
206 // Bug 32276: allowing the skin to generate output with $wgTitle or
207 // $this->context->title set to the input title would allow anonymous users to
208 // determine whether a page exists, potentially leaking private data. In fact, the
209 // curid and oldid request parameters would allow page titles to be enumerated even
210 // when they are not guessable. So we reset the title to Special:Badtitle before the
211 // permissions error is displayed.
212 //
213 // The skin mostly uses $this->context->getTitle() these days, but some extensions
214 // still use $wgTitle.
215
216 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
217 $this->context->setTitle( $badTitle );
218 $wgTitle = $badTitle;
219
220 wfProfileOut( __METHOD__ );
221 throw new PermissionsError( 'read', $permErrors );
222 }
223
224 $pageView = false; // was an article or special page viewed?
225
226 // Interwiki redirects
227 if ( $title->getInterwiki() != '' ) {
228 $rdfrom = $request->getVal( 'rdfrom' );
229 if ( $rdfrom ) {
230 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
231 } else {
232 $query = $request->getValues();
233 unset( $query['title'] );
234 $url = $title->getFullURL( $query );
235 }
236 // Check for a redirect loop
237 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
238 && $title->isLocal() )
239 {
240 // 301 so google et al report the target as the actual url.
241 $output->redirect( $url, 301 );
242 } else {
243 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
244 wfProfileOut( __METHOD__ );
245 throw new BadTitleError();
246 }
247 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
248 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
249 && ( $request->getVal( 'title' ) === null ||
250 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
251 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
252 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
253 {
254 if ( $title->isSpecialPage() ) {
255 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
256 if ( $name ) {
257 $title = SpecialPage::getTitleFor( $name, $subpage );
258 }
259 }
260 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
261 // Redirect to canonical url, make it a 301 to allow caching
262 if ( $targetUrl == $request->getFullRequestURL() ) {
263 $message = "Redirect loop detected!\n\n" .
264 "This means the wiki got confused about what page was " .
265 "requested; this sometimes happens when moving a wiki " .
266 "to a new server or changing the server configuration.\n\n";
267
268 if ( $wgUsePathInfo ) {
269 $message .= "The wiki is trying to interpret the page " .
270 "title from the URL path portion (PATH_INFO), which " .
271 "sometimes fails depending on the web server. Try " .
272 "setting \"\$wgUsePathInfo = false;\" in your " .
273 "LocalSettings.php, or check that \$wgArticlePath " .
274 "is correct.";
275 } else {
276 $message .= "Your web server was detected as possibly not " .
277 "supporting URL path components (PATH_INFO) correctly; " .
278 "check your LocalSettings.php for a customized " .
279 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
280 "to true.";
281 }
282 throw new HttpError( 500, $message );
283 } else {
284 $output->setSquidMaxage( 1200 );
285 $output->redirect( $targetUrl, '301' );
286 }
287 // Special pages
288 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
289 $pageView = true;
290 // Actions that need to be made when we have a special pages
291 SpecialPageFactory::executePath( $title, $this->context );
292 } else {
293 // ...otherwise treat it as an article view. The article
294 // may be a redirect to another article or URL.
295 $article = $this->initializeArticle();
296 if ( is_object( $article ) ) {
297 $pageView = true;
298 /**
299 * $wgArticle is deprecated, do not use it.
300 * @deprecated since 1.18
301 */
302 global $wgArticle;
303 $wgArticle = new DeprecatedGlobal( 'wgArticle', $article, '1.18' );
304
305 $this->performAction( $article, $requestTitle );
306 } elseif ( is_string( $article ) ) {
307 $output->redirect( $article );
308 } else {
309 wfProfileOut( __METHOD__ );
310 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
311 }
312 }
313
314 if ( $pageView ) {
315 // Promote user to any groups they meet the criteria for
316 $user->addAutopromoteOnceGroups( 'onView' );
317 }
318
319 wfProfileOut( __METHOD__ );
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 * Perform one of the "standard" actions
397 *
398 * @param $page Page
399 * @param $requestTitle The original title, before any redirects were applied
400 */
401 private function performAction( Page $page, Title $requestTitle ) {
402 global $wgUseSquid, $wgSquidMaxage;
403
404 wfProfileIn( __METHOD__ );
405
406 $request = $this->context->getRequest();
407 $output = $this->context->getOutput();
408 $title = $this->context->getTitle();
409 $user = $this->context->getUser();
410
411 if ( !wfRunHooks( 'MediaWikiPerformAction',
412 array( $output, $page, $title, $user, $request, $this ) ) )
413 {
414 wfProfileOut( __METHOD__ );
415 return;
416 }
417
418 $act = $this->getAction();
419
420 $action = Action::factory( $act, $page );
421 if ( $action instanceof Action ) {
422 # Let Squid cache things if we can purge them.
423 if ( $wgUseSquid &&
424 in_array( $request->getFullRequestURL(), $requestTitle->getSquidURLs() )
425 ) {
426 $output->setSquidMaxage( $wgSquidMaxage );
427 }
428
429 $action->show();
430 wfProfileOut( __METHOD__ );
431 return;
432 }
433
434 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
435 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
436 }
437
438 wfProfileOut( __METHOD__ );
439 }
440
441 /**
442 * Run the current MediaWiki instance
443 * index.php just calls this
444 */
445 public function run() {
446 try {
447 $this->checkMaxLag();
448 $this->main();
449 $this->restInPeace();
450 } catch ( Exception $e ) {
451 MWExceptionHandler::handle( $e );
452 }
453 }
454
455 /**
456 * Checks if the request should abort due to a lagged server,
457 * for given maxlag parameter.
458 * @return bool
459 */
460 private function checkMaxLag() {
461 global $wgShowHostnames;
462
463 wfProfileIn( __METHOD__ );
464 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
465 if ( !is_null( $maxLag ) ) {
466 list( $host, $lag ) = wfGetLB()->getMaxLag();
467 if ( $lag > $maxLag ) {
468 $resp = $this->context->getRequest()->response();
469 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
470 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
471 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
472 $resp->header( 'Content-Type: text/plain' );
473 if( $wgShowHostnames ) {
474 echo "Waiting for $host: $lag seconds lagged\n";
475 } else {
476 echo "Waiting for a database server: $lag seconds lagged\n";
477 }
478
479 wfProfileOut( __METHOD__ );
480
481 exit;
482 }
483 }
484 wfProfileOut( __METHOD__ );
485 return true;
486 }
487
488 private function main() {
489 global $wgUseFileCache, $wgTitle, $wgUseAjax;
490
491 wfProfileIn( __METHOD__ );
492
493 $request = $this->context->getRequest();
494
495 if ( $request->getCookie( 'forceHTTPS' )
496 && $request->detectProtocol() == 'http'
497 && $request->getMethod() == 'GET'
498 ) {
499 $redirUrl = $request->getFullRequestURL();
500 $redirUrl = str_replace( 'http://' , 'https://' , $redirUrl );
501
502 // Setup dummy Title, otherwise OutputPage::redirect will fail
503 $title = Title::newFromText( NS_MAIN, 'REDIR' );
504 $this->context->setTitle( $title );
505 $output = $this->context->getOutput();
506 $output->redirect( $redirUrl );
507 $output->output();
508 wfProfileOut( __METHOD__ );
509 return;
510 }
511
512 // Send Ajax requests to the Ajax dispatcher.
513 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
514
515 // Set a dummy title, because $wgTitle == null might break things
516 $title = Title::makeTitle( NS_MAIN, 'AJAX' );
517 $this->context->setTitle( $title );
518 $wgTitle = $title;
519
520 $dispatcher = new AjaxDispatcher();
521 $dispatcher->performAction();
522 wfProfileOut( __METHOD__ );
523 return;
524 }
525
526 // Get title from request parameters,
527 // is set on the fly by parseTitle the first time.
528 $title = $this->getTitle();
529 $action = $this->getAction();
530 $wgTitle = $title;
531
532 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
533 wfProfileIn( 'main-try-filecache' );
534 if ( HTMLFileCache::useFileCache( $this->context ) ) {
535 // Try low-level file cache hit
536 $cache = HTMLFileCache::newFromTitle( $title, $action );
537 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
538 // Check incoming headers to see if client has this cached
539 $timestamp = $cache->cacheTimestamp();
540 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
541 $cache->loadFromFileCache( $this->context );
542 }
543 // Do any stats increment/watchlist stuff
544 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
545 // Tell OutputPage that output is taken care of
546 $this->context->getOutput()->disable();
547 wfProfileOut( 'main-try-filecache' );
548 wfProfileOut( __METHOD__ );
549 return;
550 }
551 }
552 wfProfileOut( 'main-try-filecache' );
553 }
554
555 $this->performRequest();
556
557 // Now commit any transactions, so that unreported errors after
558 // output() don't roll back the whole DB transaction
559 wfGetLBFactory()->commitMasterChanges();
560
561 // Output everything!
562 $this->context->getOutput()->output();
563
564 wfProfileOut( __METHOD__ );
565 }
566
567 /**
568 * Ends this task peacefully
569 */
570 public function restInPeace() {
571 // Do any deferred jobs
572 DeferredUpdates::doUpdates( 'commit' );
573
574 // Execute a job from the queue
575 $this->doJobs();
576
577 // Log message usage, if $wgAdaptiveMessageCache is set to true
578 MessageCache::logMessages();
579
580 // Log profiling data, e.g. in the database or UDP
581 wfLogProfilingData();
582
583 // Commit and close up!
584 $factory = wfGetLBFactory();
585 $factory->commitMasterChanges();
586 $factory->shutdown();
587
588 wfDebug( "Request ended normally\n" );
589 }
590
591 /**
592 * Do a job from the job queue
593 */
594 private function doJobs() {
595 global $wgJobRunRate;
596
597 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
598 return;
599 }
600
601 if ( $wgJobRunRate < 1 ) {
602 $max = mt_getrandmax();
603 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
604 return; // the higher $wgJobRunRate, the less likely we return here
605 }
606 $n = 1;
607 } else {
608 $n = intval( $wgJobRunRate );
609 }
610
611 $group = JobQueueGroup::singleton();
612 $types = $group->getDefaultQueueTypes();
613 shuffle( $types ); // avoid starvation
614
615 // Scan the queues for a job N times...
616 do {
617 $jobFound = false; // found a job in any queue?
618 // Find a queue with a job on it and run it...
619 foreach ( $types as $i => $type ) {
620 $queue = $group->get( $type );
621 if ( $queue->isEmpty() ) {
622 unset( $types[$i] ); // don't keep checking this queue
623 continue;
624 }
625 $job = $queue->pop();
626 if ( $job ) {
627 $jobFound = true;
628 $output = $job->toString() . "\n";
629 $t = - microtime( true );
630 $success = $job->run();
631 $queue->ack( $job ); // done
632 $t += microtime( true );
633 $t = round( $t * 1000 );
634 if ( !$success ) {
635 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
636 } else {
637 $output .= "Success, Time: $t ms\n";
638 }
639 wfDebugLog( 'jobqueue', $output );
640 break;
641 } else {
642 unset( $types[$i] ); // don't keep checking this queue
643 }
644 }
645 } while ( --$n && $jobFound );
646 }
647 }