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