Moved action=info to an Action subclass; also changed display to use a table (a bit...
[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 /**
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 wfProfileOut( __METHOD__ );
211 return $article;
212 } elseif ( is_string( $article ) ) {
213 $output->redirect( $article );
214 } else {
215 wfProfileOut( __METHOD__ );
216 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
217 }
218 }
219 wfProfileOut( __METHOD__ );
220 }
221
222 /**
223 * Create an Article object of the appropriate class for the given page.
224 *
225 * @deprecated in 1.19; use Article::newFromTitle() instead
226 * @param $title Title
227 * @param $context RequestContext
228 * @return Article object
229 */
230 public static function articleFromTitle( $title, RequestContext $context ) {
231 return Article::newFromTitle( $title, $context );
232 }
233
234 /**
235 * Returns the action that will be executed, not necesserly the one passed
236 * passed through the "action" parameter. Actions disabled in
237 * $wgDisabledActions will be replaced by "nosuchaction"
238 *
239 * @return String: action
240 */
241 public function getAction() {
242 global $wgDisabledActions;
243
244 $request = $this->context->getRequest();
245 $action = $request->getVal( 'action', 'view' );
246
247 // Check for disabled actions
248 if ( in_array( $action, $wgDisabledActions ) ) {
249 return 'nosuchaction';
250 }
251
252 // Workaround for bug #20966: inability of IE to provide an action dependent
253 // on which submit button is clicked.
254 if ( $action === 'historysubmit' ) {
255 if ( $request->getBool( 'revisiondelete' ) ) {
256 return 'revisiondelete';
257 } else {
258 return 'view';
259 }
260 } elseif ( $action == 'editredlink' ) {
261 return 'edit';
262 }
263
264 return $action;
265 }
266
267 /**
268 * Initialize the main Article object for "standard" actions (view, etc)
269 * Create an Article object for the page, following redirects if needed.
270 *
271 * @return mixed an Article, or a string to redirect to another URL
272 */
273 private function initializeArticle() {
274 global $wgDisableHardRedirects;
275
276 wfProfileIn( __METHOD__ );
277
278 $request = $this->context->getRequest();
279 $title = $this->context->getTitle();
280
281 $action = $request->getVal( 'action', 'view' );
282 $article = Article::newFromTitle( $title, $this->context );
283 // NS_MEDIAWIKI has no redirects.
284 // It is also used for CSS/JS, so performance matters here...
285 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
286 wfProfileOut( __METHOD__ );
287 return $article;
288 }
289 // Namespace might change when using redirects
290 // Check for redirects ...
291 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
292 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
293 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
294 !$request->getVal( 'diff' ) && // ... and not when showing diff
295 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
296 // ... and the article is not a non-redirect image page with associated file
297 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
298 {
299 // Give extensions a change to ignore/handle redirects as needed
300 $ignoreRedirect = $target = false;
301
302 wfRunHooks( 'InitializeArticleMaybeRedirect',
303 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
304
305 // Follow redirects only for... redirects.
306 // If $target is set, then a hook wanted to redirect.
307 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
308 // Is the target already set by an extension?
309 $target = $target ? $target : $article->followRedirect();
310 if ( is_string( $target ) ) {
311 if ( !$wgDisableHardRedirects ) {
312 // we'll need to redirect
313 wfProfileOut( __METHOD__ );
314 return $target;
315 }
316 }
317 if ( is_object( $target ) ) {
318 // Rewrite environment to redirected article
319 $rarticle = Article::newFromTitle( $target, $this->context );
320 $rarticle->loadPageData();
321 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
322 $rarticle->setRedirectedFrom( $title );
323 $article = $rarticle;
324 $this->context->setTitle( $target );
325 }
326 }
327 } else {
328 $this->context->setTitle( $article->getTitle() );
329 }
330 }
331 wfProfileOut( __METHOD__ );
332 return $article;
333 }
334
335 /**
336 * Cleaning up request by doing deferred updates, DB transaction, and the output
337 */
338 public function finalCleanup() {
339 wfProfileIn( __METHOD__ );
340 // Now commit any transactions, so that unreported errors after
341 // output() don't roll back the whole DB transaction
342 $factory = wfGetLBFactory();
343 $factory->commitMasterChanges();
344 // Output everything!
345 $this->context->getOutput()->output();
346 // Do any deferred jobs
347 wfDoUpdates( 'commit' );
348 $this->doJobs();
349 wfProfileOut( __METHOD__ );
350 }
351
352 /**
353 * Do a job from the job queue
354 */
355 private function doJobs() {
356 global $wgJobRunRate;
357
358 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
359 return;
360 }
361 if ( $wgJobRunRate < 1 ) {
362 $max = mt_getrandmax();
363 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
364 return;
365 }
366 $n = 1;
367 } else {
368 $n = intval( $wgJobRunRate );
369 }
370
371 while ( $n-- && false != ( $job = Job::pop() ) ) {
372 $output = $job->toString() . "\n";
373 $t = -wfTime();
374 $success = $job->run();
375 $t += wfTime();
376 $t = round( $t * 1000 );
377 if ( !$success ) {
378 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
379 } else {
380 $output .= "Success, Time: $t ms\n";
381 }
382 wfDebugLog( 'jobqueue', $output );
383 }
384 }
385
386 /**
387 * Ends this task peacefully
388 */
389 public function restInPeace() {
390 MessageCache::logMessages();
391 wfLogProfilingData();
392 // Commit and close up!
393 $factory = wfGetLBFactory();
394 $factory->commitMasterChanges();
395 $factory->shutdown();
396 wfDebug( "Request ended normally\n" );
397 }
398
399 /**
400 * Perform one of the "standard" actions
401 *
402 * @param $article Article
403 */
404 private function performAction( $article ) {
405 global $wgSquidMaxage, $wgUseExternalEditor;
406
407 wfProfileIn( __METHOD__ );
408
409 $request = $this->context->getRequest();
410 $output = $this->context->getOutput();
411 $title = $this->context->getTitle();
412 $user = $this->context->getUser();
413
414 if ( !wfRunHooks( 'MediaWikiPerformAction', array(
415 $output, $article, $title,
416 $user, $request, $this ) ) )
417 {
418 wfProfileOut( __METHOD__ );
419 return;
420 }
421
422 $act = $this->getAction();
423
424 $action = Action::factory( $act, $article );
425 if( $action instanceof Action ){
426 $action->show();
427 wfProfileOut( __METHOD__ );
428 return;
429 }
430
431 switch( $act ) {
432 case 'view':
433 $output->setSquidMaxage( $wgSquidMaxage );
434 $article->view();
435 break;
436 case 'raw': // includes JS/CSS
437 wfProfileIn( __METHOD__ . '-raw' );
438 $raw = new RawPage( $article );
439 $raw->view();
440 wfProfileOut( __METHOD__ . '-raw' );
441 break;
442 case 'delete':
443 case 'revert':
444 case 'rollback':
445 case 'protect':
446 case 'unprotect':
447 case 'render':
448 $article->$act();
449 break;
450 case 'submit':
451 if ( session_id() == '' ) {
452 // Send a cookie so anons get talk message notifications
453 wfSetupSession();
454 }
455 // Continue...
456 case 'edit':
457 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
458 $internal = $request->getVal( 'internaledit' );
459 $external = $request->getVal( 'externaledit' );
460 $section = $request->getVal( 'section' );
461 $oldid = $request->getVal( 'oldid' );
462 if ( !$wgUseExternalEditor || $act == 'submit' || $internal ||
463 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
464 $editor = new EditPage( $article );
465 $editor->submit();
466 } elseif ( $wgUseExternalEditor && ( $external || $user->getOption( 'externaleditor' ) ) ) {
467 $mode = $request->getVal( 'mode' );
468 $extedit = new ExternalEdit( $article, $mode );
469 $extedit->edit();
470 }
471 }
472 break;
473 case 'history':
474 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
475 $output->setSquidMaxage( $wgSquidMaxage );
476 }
477 $history = new HistoryPage( $article );
478 $history->history();
479 break;
480 default:
481 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
482 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
483 }
484 }
485 wfProfileOut( __METHOD__ );
486 }
487
488 /**
489 * Run the current MediaWiki instance
490 * index.php just calls this
491 */
492 function run() {
493 try {
494 $this->checkMaxLag( true );
495 $this->main();
496 $this->restInPeace();
497 } catch ( Exception $e ) {
498 MWExceptionHandler::handle( $e );
499 }
500 }
501
502 /**
503 * Checks if the request should abort due to a lagged server,
504 * for given maxlag parameter.
505 *
506 * @param boolean $abort True if this class should abort the
507 * script execution. False to return the result as a boolean.
508 * @return boolean True if we passed the check, false if we surpass the maxlag
509 */
510 function checkMaxLag( $abort ) {
511 global $wgShowHostnames;
512
513 wfProfileIn( __METHOD__ );
514 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
515 if ( !is_null( $maxLag ) ) {
516 $lb = wfGetLB(); // foo()->bar() is not supported in PHP4
517 list( $host, $lag ) = $lb->getMaxLag();
518 if ( $lag > $maxLag ) {
519 if ( $abort ) {
520 header( 'HTTP/1.1 503 Service Unavailable' );
521 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
522 header( 'X-Database-Lag: ' . intval( $lag ) );
523 header( 'Content-Type: text/plain' );
524 if( $wgShowHostnames ) {
525 echo "Waiting for $host: $lag seconds lagged\n";
526 } else {
527 echo "Waiting for a database server: $lag seconds lagged\n";
528 }
529 }
530
531 wfProfileOut( __METHOD__ );
532
533 if ( !$abort )
534 return false;
535 exit;
536 }
537 }
538 wfProfileOut( __METHOD__ );
539 return true;
540 }
541
542 function main() {
543 global $wgUseFileCache, $wgTitle, $wgUseAjax;
544
545 wfProfileIn( __METHOD__ );
546
547 # Set title from request parameters
548 $wgTitle = $this->getTitle();
549 $action = $this->getAction();
550
551 # Send Ajax requests to the Ajax dispatcher.
552 if ( $wgUseAjax && $action == 'ajax' ) {
553 $dispatcher = new AjaxDispatcher();
554 $dispatcher->performAction();
555 wfProfileOut( __METHOD__ );
556 return;
557 }
558
559 if ( $wgUseFileCache && $wgTitle !== null ) {
560 wfProfileIn( 'main-try-filecache' );
561 // Raw pages should handle cache control on their own,
562 // even when using file cache. This reduces hits from clients.
563 if ( $action != 'raw' && HTMLFileCache::useFileCache() ) {
564 /* Try low-level file cache hit */
565 $cache = new HTMLFileCache( $wgTitle, $action );
566 if ( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
567 /* Check incoming headers to see if client has this cached */
568 if ( !$this->context->getOutput()->checkLastModified( $cache->fileCacheTime() ) ) {
569 $cache->loadFromFileCache();
570 }
571 # Do any stats increment/watchlist stuff
572 $article = Article::newFromTitle( $wgTitle, $this->context );
573 $article->viewUpdates();
574 # Tell OutputPage that output is taken care of
575 $this->context->getOutput()->disable();
576 wfProfileOut( 'main-try-filecache' );
577 wfProfileOut( __METHOD__ );
578 return;
579 }
580 }
581 wfProfileOut( 'main-try-filecache' );
582 }
583
584 $this->performRequest();
585 $this->finalCleanup();
586
587 wfProfileOut( __METHOD__ );
588 }
589 }