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