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