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