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