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