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