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