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