follow-up r59522 and r59541. To make the condition when we'll use Accept-Language...
[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 $pref = $wgContLang->getPreferredVariant( $fromUser = false, $fromHeader = true );
216 $targetUrl = $title->getFullURL( $variant = $pref );
217 // Redirect to canonical url, make it a 301 to allow caching
218 if( $targetUrl == $request->getFullRequestURL() ) {
219 $message = "Redirect loop detected!\n\n" .
220 "This means the wiki got confused about what page was " .
221 "requested; this sometimes happens when moving a wiki " .
222 "to a new server or changing the server configuration.\n\n";
223
224 if( $this->getVal( 'UsePathInfo' ) ) {
225 $message .= "The wiki is trying to interpret the page " .
226 "title from the URL path portion (PATH_INFO), which " .
227 "sometimes fails depending on the web server. Try " .
228 "setting \"\$wgUsePathInfo = false;\" in your " .
229 "LocalSettings.php, or check that \$wgArticlePath " .
230 "is correct.";
231 } else {
232 $message .= "Your web server was detected as possibly not " .
233 "supporting URL path components (PATH_INFO) correctly; " .
234 "check your LocalSettings.php for a customized " .
235 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
236 "to true.";
237 }
238 wfHttpError( 500, "Internal error", $message );
239 wfProfileOut( __METHOD__ );
240 return false;
241 } else {
242 $output->setSquidMaxage( 1200 );
243 $output->redirect( $targetUrl, '301' );
244 }
245 // Special pages
246 } else if( NS_SPECIAL == $title->getNamespace() ) {
247 /* actions that need to be made when we have a special pages */
248 SpecialPage::executePath( $title );
249 } else {
250 /* No match to special cases */
251 wfProfileOut( __METHOD__ );
252 return false;
253 }
254 /* Did match a special case */
255 wfProfileOut( __METHOD__ );
256 return true;
257 }
258
259 /**
260 * Create an Article object of the appropriate class for the given page.
261 *
262 * @param $title Title
263 * @return Article object
264 */
265 static function articleFromTitle( &$title ) {
266 if( NS_MEDIA == $title->getNamespace() ) {
267 // FIXME: where should this go?
268 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
269 }
270
271 $article = null;
272 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
273 if( $article ) {
274 return $article;
275 }
276
277 switch( $title->getNamespace() ) {
278 case NS_FILE:
279 return new ImagePage( $title );
280 case NS_CATEGORY:
281 return new CategoryPage( $title );
282 default:
283 return new Article( $title );
284 }
285 }
286
287 /**
288 * Initialize the object to be known as $wgArticle for "standard" actions
289 * Create an Article object for the page, following redirects if needed.
290 *
291 * @param $title Title ($wgTitle)
292 * @param $output OutputPage ($wgOut)
293 * @param $request WebRequest ($wgRequest)
294 * @return mixed an Article, or a string to redirect to another URL
295 */
296 function initializeArticle( &$title, &$output, $request ) {
297 wfProfileIn( __METHOD__ );
298
299 $action = $this->getVal( 'action', 'view' );
300 $article = self::articleFromTitle( $title );
301 # NS_MEDIAWIKI has no redirects.
302 # It is also used for CSS/JS, so performance matters here...
303 if( $title->getNamespace() == NS_MEDIAWIKI ) {
304 wfProfileOut( __METHOD__ );
305 return $article;
306 }
307 // Namespace might change when using redirects
308 // Check for redirects ...
309 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
310 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
311 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
312 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
313 // ... and the article is not a non-redirect image page with associated file
314 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
315 {
316 # Give extensions a change to ignore/handle redirects as needed
317 $ignoreRedirect = $target = false;
318
319 $dbr = wfGetDB( DB_SLAVE );
320 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
321
322 wfRunHooks( 'InitializeArticleMaybeRedirect',
323 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
324
325 // Follow redirects only for... redirects.
326 // If $target is set, then a hook wanted to redirect.
327 if( !$ignoreRedirect && ($target || $article->isRedirect()) ) {
328 # Is the target already set by an extension?
329 $target = $target ? $target : $article->followRedirect();
330 if( is_string( $target ) ) {
331 if( !$this->getVal( 'DisableHardRedirects' ) ) {
332 // we'll need to redirect
333 wfProfileOut( __METHOD__ );
334 return $target;
335 }
336 }
337 if( is_object($target) ) {
338 // Rewrite environment to redirected article
339 $rarticle = self::articleFromTitle( $target );
340 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
341 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
342 $rarticle->setRedirectedFrom( $title );
343 $article = $rarticle;
344 $title = $target;
345 $output->setTitle( $title );
346 }
347 }
348 } else {
349 $title = $article->getTitle();
350 }
351 }
352 wfProfileOut( __METHOD__ );
353 return $article;
354 }
355
356 /**
357 * Cleaning up request by doing:
358 ** deferred updates, DB transaction, and the output
359 *
360 * @param $deferredUpdates array of updates to do
361 * @param $output OutputPage
362 */
363 function finalCleanup( &$deferredUpdates, &$output ) {
364 wfProfileIn( __METHOD__ );
365 # Now commit any transactions, so that unreported errors after
366 # output() don't roll back the whole DB transaction
367 $factory = wfGetLBFactory();
368 $factory->commitMasterChanges();
369 # Output everything!
370 $output->output();
371 # Do any deferred jobs
372 $this->doUpdates( $deferredUpdates );
373 $this->doJobs();
374 wfProfileOut( __METHOD__ );
375 }
376
377 /**
378 * Deferred updates aren't really deferred anymore. It's important to report
379 * errors to the user, and that means doing this before OutputPage::output().
380 * Note that for page saves, the client will wait until the script exits
381 * anyway before following the redirect.
382 *
383 * @param $updates array of objects that hold an update to do
384 */
385 function doUpdates( &$updates ) {
386 wfProfileIn( __METHOD__ );
387 /* No need to get master connections in case of empty updates array */
388 if (!$updates) {
389 wfProfileOut( __METHOD__ );
390 return;
391 }
392
393 $dbw = wfGetDB( DB_MASTER );
394 foreach( $updates as $up ) {
395 $up->doUpdate();
396
397 # Commit after every update to prevent lock contention
398 if( $dbw->trxLevel() ) {
399 $dbw->commit();
400 }
401 }
402 wfProfileOut( __METHOD__ );
403 }
404
405 /**
406 * Do a job from the job queue
407 */
408 function doJobs() {
409 $jobRunRate = $this->getVal( 'JobRunRate' );
410
411 if( $jobRunRate <= 0 || wfReadOnly() ) {
412 return;
413 }
414 if( $jobRunRate < 1 ) {
415 $max = mt_getrandmax();
416 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
417 return;
418 }
419 $n = 1;
420 } else {
421 $n = intval( $jobRunRate );
422 }
423
424 while ( $n-- && false != ( $job = Job::pop() ) ) {
425 $output = $job->toString() . "\n";
426 $t = -wfTime();
427 $success = $job->run();
428 $t += wfTime();
429 $t = round( $t*1000 );
430 if( !$success ) {
431 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
432 } else {
433 $output .= "Success, Time: $t ms\n";
434 }
435 wfDebugLog( 'jobqueue', $output );
436 }
437 }
438
439 /**
440 * Ends this task peacefully
441 */
442 function restInPeace() {
443 wfLogProfilingData();
444 # Commit and close up!
445 $factory = wfGetLBFactory();
446 $factory->commitMasterChanges();
447 $factory->shutdown();
448 wfDebug( "Request ended normally\n" );
449 }
450
451 /**
452 * Perform one of the "standard" actions
453 *
454 * @param $output OutputPage
455 * @param $article Article
456 * @param $title Title
457 * @param $user User
458 * @param $request WebRequest
459 */
460 function performAction( &$output, &$article, &$title, &$user, &$request ) {
461 wfProfileIn( __METHOD__ );
462
463 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
464 wfProfileOut( __METHOD__ );
465 return;
466 }
467
468 $action = $this->getVal( 'Action' );
469 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
470 /* No such action; this will switch to the default case */
471 $action = 'nosuchaction';
472 }
473
474 # Workaround for bug #20966: inability of IE to provide an action dependent
475 # on which submit button is clicked.
476 if ( $action === 'historysubmit' ) {
477 if ( $request->getBool( 'revisiondelete' ) ) {
478 $action = 'revisiondelete';
479 } else {
480 $action = 'view';
481 }
482 }
483
484 switch( $action ) {
485 case 'view':
486 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
487 $article->view();
488 break;
489 case 'raw': // includes JS/CSS
490 wfProfileIn( __METHOD__.'-raw' );
491 $raw = new RawPage( $article );
492 $raw->view();
493 wfProfileOut( __METHOD__.'-raw' );
494 break;
495 case 'watch':
496 case 'unwatch':
497 case 'delete':
498 case 'revert':
499 case 'rollback':
500 case 'protect':
501 case 'unprotect':
502 case 'info':
503 case 'markpatrolled':
504 case 'render':
505 case 'deletetrackback':
506 case 'purge':
507 $article->$action();
508 break;
509 case 'print':
510 $article->view();
511 break;
512 case 'dublincore':
513 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
514 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
515 } else {
516 $rdf = new DublinCoreRdf( $article );
517 $rdf->show();
518 }
519 break;
520 case 'creativecommons':
521 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
522 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
523 } else {
524 $rdf = new CreativeCommonsRdf( $article );
525 $rdf->show();
526 }
527 break;
528 case 'credits':
529 Credits::showPage( $article );
530 break;
531 case 'submit':
532 if( session_id() == '' ) {
533 /* Send a cookie so anons get talk message notifications */
534 wfSetupSession();
535 }
536 /* Continue... */
537 case 'edit':
538 case 'editredlink':
539 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
540 $internal = $request->getVal( 'internaledit' );
541 $external = $request->getVal( 'externaledit' );
542 $section = $request->getVal( 'section' );
543 $oldid = $request->getVal( 'oldid' );
544 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
545 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
546 $editor = new EditPage( $article );
547 $editor->submit();
548 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
549 $mode = $request->getVal( 'mode' );
550 $extedit = new ExternalEdit( $article, $mode );
551 $extedit->edit();
552 }
553 }
554 break;
555 case 'history':
556 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
557 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
558 }
559 $history = new HistoryPage( $article );
560 $history->history();
561 break;
562 case 'revisiondelete':
563 # For show/hide submission from history page
564 $special = SpecialPage::getPage( 'Revisiondelete' );
565 $special->execute( '' );
566 break;
567 default:
568 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
569 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
570 }
571 }
572 wfProfileOut( __METHOD__ );
573
574 }
575
576 }; /* End of class MediaWiki */