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