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 * @return void
173 */
174 private function performRequest() {
175 global $wgServer, $wgUsePathInfo, $wgTitle;
176
177 wfProfileIn( __METHOD__ );
178
179 $request = $this->context->getRequest();
180 $title = $this->context->getTitle();
181 $output = $this->context->getOutput();
182 $user = $this->context->getUser();
183
184 if ( $request->getVal( 'printable' ) === 'yes' ) {
185 $output->setPrintable();
186 }
187
188 $unused = null; // To pass it by reference
189 wfRunHooks( 'BeforeInitialize', array( &$title, &$unused, &$output, &$user, $request, $this ) );
190
191 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
192 if ( is_null( $title ) || ( $title->getDBkey() == '' && $title->getInterwiki() == '' ) ||
193 $title->isSpecial( 'Badtitle' ) )
194 {
195 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
196 wfProfileOut( __METHOD__ );
197 throw new BadTitleError();
198 }
199
200 // Check user's permissions to read this page.
201 // We have to check here to catch special pages etc.
202 // We will check again in Article::view().
203 $permErrors = $title->getUserPermissionsErrors( 'read', $user );
204 if ( count( $permErrors ) ) {
205 // Bug 32276: allowing the skin to generate output with $wgTitle or
206 // $this->context->title set to the input title would allow anonymous users to
207 // determine whether a page exists, potentially leaking private data. In fact, the
208 // curid and oldid request parameters would allow page titles to be enumerated even
209 // when they are not guessable. So we reset the title to Special:Badtitle before the
210 // permissions error is displayed.
211 //
212 // The skin mostly uses $this->context->getTitle() these days, but some extensions
213 // still use $wgTitle.
214
215 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
216 $this->context->setTitle( $badTitle );
217 $wgTitle = $badTitle;
218
219 wfProfileOut( __METHOD__ );
220 throw new PermissionsError( 'read', $permErrors );
221 }
222
223 $pageView = false; // was an article or special page viewed?
224
225 // Interwiki redirects
226 if ( $title->getInterwiki() != '' ) {
227 $rdfrom = $request->getVal( 'rdfrom' );
228 if ( $rdfrom ) {
229 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
230 } else {
231 $query = $request->getValues();
232 unset( $query['title'] );
233 $url = $title->getFullURL( $query );
234 }
235 // Check for a redirect loop
236 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
237 && $title->isLocal() )
238 {
239 // 301 so google et al report the target as the actual url.
240 $output->redirect( $url, 301 );
241 } else {
242 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
243 wfProfileOut( __METHOD__ );
244 throw new BadTitleError();
245 }
246 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
247 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
248 && ( $request->getVal( 'title' ) === null ||
249 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
250 && !count( $request->getValueNames( array( 'action', 'title' ) ) )
251 && wfRunHooks( 'TestCanonicalRedirect', array( $request, $title, $output ) ) )
252 {
253 if ( $title->isSpecialPage() ) {
254 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
255 if ( $name ) {
256 $title = SpecialPage::getTitleFor( $name, $subpage );
257 }
258 }
259 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
260 // Redirect to canonical url, make it a 301 to allow caching
261 if ( $targetUrl == $request->getFullRequestURL() ) {
262 $message = "Redirect loop detected!\n\n" .
263 "This means the wiki got confused about what page was " .
264 "requested; this sometimes happens when moving a wiki " .
265 "to a new server or changing the server configuration.\n\n";
266
267 if ( $wgUsePathInfo ) {
268 $message .= "The wiki is trying to interpret the page " .
269 "title from the URL path portion (PATH_INFO), which " .
270 "sometimes fails depending on the web server. Try " .
271 "setting \"\$wgUsePathInfo = false;\" in your " .
272 "LocalSettings.php, or check that \$wgArticlePath " .
273 "is correct.";
274 } else {
275 $message .= "Your web server was detected as possibly not " .
276 "supporting URL path components (PATH_INFO) correctly; " .
277 "check your LocalSettings.php for a customized " .
278 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
279 "to true.";
280 }
281 throw new HttpError( 500, $message );
282 } else {
283 $output->setSquidMaxage( 1200 );
284 $output->redirect( $targetUrl, '301' );
285 }
286 // Special pages
287 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
288 $pageView = true;
289 // Actions that need to be made when we have a special pages
290 SpecialPageFactory::executePath( $title, $this->context );
291 } else {
292 // ...otherwise treat it as an article view. The article
293 // may be a redirect to another article or URL.
294 $article = $this->initializeArticle();
295 if ( is_object( $article ) ) {
296 $pageView = true;
297 /**
298 * $wgArticle is deprecated, do not use it.
299 * @deprecated since 1.18
300 */
301 global $wgArticle;
302 $wgArticle = new DeprecatedGlobal( 'wgArticle', $article, '1.18' );
303
304 $this->performAction( $article );
305 } elseif ( is_string( $article ) ) {
306 $output->redirect( $article );
307 } else {
308 wfProfileOut( __METHOD__ );
309 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
310 }
311 }
312
313 if ( $pageView ) {
314 // Promote user to any groups they meet the criteria for
315 $user->addAutopromoteOnceGroups( 'onView' );
316 }
317
318 wfProfileOut( __METHOD__ );
319 }
320
321 /**
322 * Initialize the main Article object for "standard" actions (view, etc)
323 * Create an Article object for the page, following redirects if needed.
324 *
325 * @return mixed an Article, or a string to redirect to another URL
326 */
327 private function initializeArticle() {
328 global $wgDisableHardRedirects;
329
330 wfProfileIn( __METHOD__ );
331
332 $title = $this->context->getTitle();
333 $article = Article::newFromTitle( $title, $this->context );
334 $this->context->setWikiPage( $article->getPage() );
335 // NS_MEDIAWIKI has no redirects.
336 // It is also used for CSS/JS, so performance matters here...
337 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
338 wfProfileOut( __METHOD__ );
339 return $article;
340 }
341
342 $request = $this->context->getRequest();
343
344 // Namespace might change when using redirects
345 // Check for redirects ...
346 $action = $request->getVal( 'action', 'view' );
347 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
348 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
349 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
350 !$request->getVal( 'diff' ) && // ... and not when showing diff
351 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
352 // ... and the article is not a non-redirect image page with associated file
353 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
354 {
355 // Give extensions a change to ignore/handle redirects as needed
356 $ignoreRedirect = $target = false;
357
358 wfRunHooks( 'InitializeArticleMaybeRedirect',
359 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
360
361 // Follow redirects only for... redirects.
362 // If $target is set, then a hook wanted to redirect.
363 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
364 // Is the target already set by an extension?
365 $target = $target ? $target : $article->followRedirect();
366 if ( is_string( $target ) ) {
367 if ( !$wgDisableHardRedirects ) {
368 // we'll need to redirect
369 wfProfileOut( __METHOD__ );
370 return $target;
371 }
372 }
373 if ( is_object( $target ) ) {
374 // Rewrite environment to redirected article
375 $rarticle = Article::newFromTitle( $target, $this->context );
376 $rarticle->loadPageData();
377 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
378 $rarticle->setRedirectedFrom( $title );
379 $article = $rarticle;
380 $this->context->setTitle( $target );
381 $this->context->setWikiPage( $article->getPage() );
382 }
383 }
384 } else {
385 $this->context->setTitle( $article->getTitle() );
386 $this->context->setWikiPage( $article->getPage() );
387 }
388 }
389
390 wfProfileOut( __METHOD__ );
391 return $article;
392 }
393
394 /**
395 * Perform one of the "standard" actions
396 *
397 * @param $page Page
398 */
399 private function performAction( Page $page ) {
400 global $wgUseSquid, $wgSquidMaxage;
401
402 wfProfileIn( __METHOD__ );
403
404 $request = $this->context->getRequest();
405 $output = $this->context->getOutput();
406 $title = $this->context->getTitle();
407 $user = $this->context->getUser();
408
409 if ( !wfRunHooks( 'MediaWikiPerformAction',
410 array( $output, $page, $title, $user, $request, $this ) ) )
411 {
412 wfProfileOut( __METHOD__ );
413 return;
414 }
415
416 $act = $this->getAction();
417
418 $action = Action::factory( $act, $page );
419 if ( $action instanceof Action ) {
420 # Let Squid cache things if we can purge them.
421 if ( $wgUseSquid &&
422 in_array( $request->getFullRequestURL(), $title->getSquidURLs() )
423 ) {
424 $output->setSquidMaxage( $wgSquidMaxage );
425 }
426
427 $action->show();
428 wfProfileOut( __METHOD__ );
429 return;
430 }
431
432 if ( wfRunHooks( 'UnknownAction', array( $request->getVal( 'action', 'view' ), $page ) ) ) {
433 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
434 }
435
436 wfProfileOut( __METHOD__ );
437 }
438
439 /**
440 * Run the current MediaWiki instance
441 * index.php just calls this
442 */
443 public function run() {
444 try {
445 $this->checkMaxLag();
446 $this->main();
447 $this->restInPeace();
448 } catch ( Exception $e ) {
449 MWExceptionHandler::handle( $e );
450 }
451 }
452
453 /**
454 * Checks if the request should abort due to a lagged server,
455 * for given maxlag parameter.
456 * @return bool
457 */
458 private function checkMaxLag() {
459 global $wgShowHostnames;
460
461 wfProfileIn( __METHOD__ );
462 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
463 if ( !is_null( $maxLag ) ) {
464 list( $host, $lag ) = wfGetLB()->getMaxLag();
465 if ( $lag > $maxLag ) {
466 $resp = $this->context->getRequest()->response();
467 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
468 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
469 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
470 $resp->header( 'Content-Type: text/plain' );
471 if( $wgShowHostnames ) {
472 echo "Waiting for $host: $lag seconds lagged\n";
473 } else {
474 echo "Waiting for a database server: $lag seconds lagged\n";
475 }
476
477 wfProfileOut( __METHOD__ );
478
479 exit;
480 }
481 }
482 wfProfileOut( __METHOD__ );
483 return true;
484 }
485
486 private function main() {
487 global $wgUseFileCache, $wgTitle, $wgUseAjax;
488
489 wfProfileIn( __METHOD__ );
490
491 $request = $this->context->getRequest();
492
493 if ( $request->getCookie( 'forceHTTPS' )
494 && $request->detectProtocol() == 'http'
495 && $request->getMethod() == 'GET'
496 ) {
497 $redirUrl = $request->getFullRequestURL();
498 $redirUrl = str_replace( 'http://' , 'https://' , $redirUrl );
499
500 // Setup dummy Title, otherwise OutputPage::redirect will fail
501 $title = Title::newFromText( NS_MAIN, 'REDIR' );
502 $this->context->setTitle( $title );
503 $output = $this->context->getOutput();
504 $output->redirect( $redirUrl );
505 $output->output();
506 wfProfileOut( __METHOD__ );
507 return;
508 }
509
510 // Send Ajax requests to the Ajax dispatcher.
511 if ( $wgUseAjax && $request->getVal( 'action', 'view' ) == 'ajax' ) {
512
513 // Set a dummy title, because $wgTitle == null might break things
514 $title = Title::makeTitle( NS_MAIN, 'AJAX' );
515 $this->context->setTitle( $title );
516 $wgTitle = $title;
517
518 $dispatcher = new AjaxDispatcher();
519 $dispatcher->performAction();
520 wfProfileOut( __METHOD__ );
521 return;
522 }
523
524 // Get title from request parameters,
525 // is set on the fly by parseTitle the first time.
526 $title = $this->getTitle();
527 $action = $this->getAction();
528 $wgTitle = $title;
529
530 if ( $wgUseFileCache && $title->getNamespace() >= 0 ) {
531 wfProfileIn( 'main-try-filecache' );
532 if ( HTMLFileCache::useFileCache( $this->context ) ) {
533 // Try low-level file cache hit
534 $cache = HTMLFileCache::newFromTitle( $title, $action );
535 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
536 // Check incoming headers to see if client has this cached
537 $timestamp = $cache->cacheTimestamp();
538 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
539 $cache->loadFromFileCache( $this->context );
540 }
541 // Do any stats increment/watchlist stuff
542 $this->context->getWikiPage()->doViewUpdates( $this->context->getUser() );
543 // Tell OutputPage that output is taken care of
544 $this->context->getOutput()->disable();
545 wfProfileOut( 'main-try-filecache' );
546 wfProfileOut( __METHOD__ );
547 return;
548 }
549 }
550 wfProfileOut( 'main-try-filecache' );
551 }
552
553 $this->performRequest();
554
555 // Now commit any transactions, so that unreported errors after
556 // output() don't roll back the whole DB transaction
557 wfGetLBFactory()->commitMasterChanges();
558
559 // Output everything!
560 $this->context->getOutput()->output();
561
562 wfProfileOut( __METHOD__ );
563 }
564
565 /**
566 * Ends this task peacefully
567 */
568 public function restInPeace() {
569 // Do any deferred jobs
570 DeferredUpdates::doUpdates( 'commit' );
571
572 // Execute a job from the queue
573 $this->doJobs();
574
575 // Log message usage, if $wgAdaptiveMessageCache is set to true
576 MessageCache::logMessages();
577
578 // Log profiling data, e.g. in the database or UDP
579 wfLogProfilingData();
580
581 // Commit and close up!
582 $factory = wfGetLBFactory();
583 $factory->commitMasterChanges();
584 $factory->shutdown();
585
586 wfDebug( "Request ended normally\n" );
587 }
588
589 /**
590 * Do a job from the job queue
591 */
592 private function doJobs() {
593 global $wgJobRunRate;
594
595 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
596 return;
597 }
598 if ( $wgJobRunRate < 1 ) {
599 $max = mt_getrandmax();
600 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
601 return;
602 }
603 $n = 1;
604 } else {
605 $n = intval( $wgJobRunRate );
606 }
607
608 while ( $n-- && false != ( $job = Job::pop() ) ) {
609 $output = $job->toString() . "\n";
610 $t = - microtime( true );
611 $success = $job->run();
612 $t += microtime( true );
613 $t = round( $t * 1000 );
614 if ( !$success ) {
615 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
616 } else {
617 $output .= "Success, Time: $t ms\n";
618 }
619 wfDebugLog( 'jobqueue', $output );
620 }
621 }
622 }