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