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