(bug 19226) First line renders differently on many UI messages
[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
186 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
187 if( is_null($title) || ( ($title->getDBkey() == '') && ($title->getInterwiki() == '') ) ) {
188 $title = SpecialPage::getTitleFor( 'Badtitle' );
189 # Die now before we mess up $wgArticle and the skin stops working
190 throw new ErrorPageError( 'badtitle', 'badtitletext' );
191
192 // Interwiki redirects
193 } else if( $title->getInterwiki() != '' ) {
194 if( $rdfrom = $request->getVal( 'rdfrom' ) ) {
195 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
196 } else {
197 $query = $request->getValues();
198 unset( $query['title'] );
199 $url = $title->getFullURL( $query );
200 }
201 /* Check for a redirect loop */
202 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
203 $output->redirect( $url );
204 } else {
205 $title = SpecialPage::getTitleFor( 'Badtitle' );
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( $action == 'view' && !$request->wasPosted() &&
211 ( ( !isset($this->GET['title']) || $title->getPrefixedDBKey() != $this->GET['title'] ) ||
212 // No valid variant in URL (if the main-language has multi-variants), to ensure
213 // anonymous access would always be redirect to a URL with 'variant' parameter
214 ( !isset($this->GET['variant']) && $wgContLang->hasVariants() && !$wgUser->isLoggedIn() ) ) &&
215 !count( array_diff( array_keys( $this->GET ), array( 'action', 'title' ) ) ) )
216 {
217 if( !$wgUser->isLoggedIn() ) {
218 $pref = $wgContLang->getPreferredVariant( false, $fromHeader = true );
219 $targetUrl = $title->getFullURL( '', $variant = $pref );
220 }
221 else
222 $targetUrl = $title->getFullURL();
223 // Redirect to canonical url, make it a 301 to allow caching
224 if( $targetUrl == $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 $output->setSquidMaxage( 1200 );
249 $output->redirect( $targetUrl, '301' );
250 }
251 // Special pages
252 } else if( NS_SPECIAL == $title->getNamespace() ) {
253 /* actions that need to be made when we have a special pages */
254 SpecialPage::executePath( $title );
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 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 * Initialize the object to be known as $wgArticle for "standard" actions
295 * Create an Article object for the page, following redirects if needed.
296 *
297 * @param $title Title ($wgTitle)
298 * @param $output OutputPage ($wgOut)
299 * @param $request WebRequest ($wgRequest)
300 * @return mixed an Article, or a string to redirect to another URL
301 */
302 function initializeArticle( &$title, &$output, $request ) {
303 wfProfileIn( __METHOD__ );
304
305 $action = $this->getVal( 'action', 'view' );
306 $article = self::articleFromTitle( $title );
307 # NS_MEDIAWIKI has no redirects.
308 # It is also used for CSS/JS, so performance matters here...
309 if( $title->getNamespace() == NS_MEDIAWIKI ) {
310 wfProfileOut( __METHOD__ );
311 return $article;
312 }
313 // Namespace might change when using redirects
314 // Check for redirects ...
315 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
316 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
317 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
318 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
319 // ... and the article is not a non-redirect image page with associated file
320 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
321 {
322 # Give extensions a change to ignore/handle redirects as needed
323 $ignoreRedirect = $target = false;
324
325 $dbr = wfGetDB( DB_SLAVE );
326 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
327
328 wfRunHooks( 'InitializeArticleMaybeRedirect',
329 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
330
331 // Follow redirects only for... redirects.
332 // If $target is set, then a hook wanted to redirect.
333 if( !$ignoreRedirect && ($target || $article->isRedirect()) ) {
334 # Is the target already set by an extension?
335 $target = $target ? $target : $article->followRedirect();
336 if( is_string( $target ) ) {
337 if( !$this->getVal( 'DisableHardRedirects' ) ) {
338 // we'll need to redirect
339 wfProfileOut( __METHOD__ );
340 return $target;
341 }
342 }
343 if( is_object($target) ) {
344 // Rewrite environment to redirected article
345 $rarticle = self::articleFromTitle( $target );
346 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
347 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
348 $rarticle->setRedirectedFrom( $title );
349 $article = $rarticle;
350 $title = $target;
351 $output->setTitle( $title );
352 }
353 }
354 } else {
355 $title = $article->getTitle();
356 }
357 }
358 wfProfileOut( __METHOD__ );
359 return $article;
360 }
361
362 /**
363 * Cleaning up request by doing:
364 ** deferred updates, DB transaction, and the output
365 *
366 * @param $deferredUpdates array of updates to do
367 * @param $output OutputPage
368 */
369 function finalCleanup( &$deferredUpdates, &$output ) {
370 wfProfileIn( __METHOD__ );
371 # Now commit any transactions, so that unreported errors after
372 # output() don't roll back the whole DB transaction
373 $factory = wfGetLBFactory();
374 $factory->commitMasterChanges();
375 # Output everything!
376 $output->output();
377 # Do any deferred jobs
378 $this->doUpdates( $deferredUpdates );
379 $this->doJobs();
380 wfProfileOut( __METHOD__ );
381 }
382
383 /**
384 * Deferred updates aren't really deferred anymore. It's important to report
385 * errors to the user, and that means doing this before OutputPage::output().
386 * Note that for page saves, the client will wait until the script exits
387 * anyway before following the redirect.
388 *
389 * @param $updates array of objects that hold an update to do
390 */
391 function doUpdates( &$updates ) {
392 wfProfileIn( __METHOD__ );
393 /* No need to get master connections in case of empty updates array */
394 if (!$updates) {
395 wfProfileOut( __METHOD__ );
396 return;
397 }
398
399 $dbw = wfGetDB( DB_MASTER );
400 foreach( $updates as $up ) {
401 $up->doUpdate();
402
403 # Commit after every update to prevent lock contention
404 if( $dbw->trxLevel() ) {
405 $dbw->commit();
406 }
407 }
408 wfProfileOut( __METHOD__ );
409 }
410
411 /**
412 * Do a job from the job queue
413 */
414 function doJobs() {
415 $jobRunRate = $this->getVal( 'JobRunRate' );
416
417 if( $jobRunRate <= 0 || wfReadOnly() ) {
418 return;
419 }
420 if( $jobRunRate < 1 ) {
421 $max = mt_getrandmax();
422 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
423 return;
424 }
425 $n = 1;
426 } else {
427 $n = intval( $jobRunRate );
428 }
429
430 while ( $n-- && false != ( $job = Job::pop() ) ) {
431 $output = $job->toString() . "\n";
432 $t = -wfTime();
433 $success = $job->run();
434 $t += wfTime();
435 $t = round( $t*1000 );
436 if( !$success ) {
437 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
438 } else {
439 $output .= "Success, Time: $t ms\n";
440 }
441 wfDebugLog( 'jobqueue', $output );
442 }
443 }
444
445 /**
446 * Ends this task peacefully
447 */
448 function restInPeace() {
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 $output OutputPage
461 * @param $article Article
462 * @param $title Title
463 * @param $user User
464 * @param $request WebRequest
465 */
466 function performAction( &$output, &$article, &$title, &$user, &$request ) {
467 wfProfileIn( __METHOD__ );
468
469 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
470 wfProfileOut( __METHOD__ );
471 return;
472 }
473
474 $action = $this->getVal( 'Action' );
475 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
476 /* No such action; this will switch to the default case */
477 $action = 'nosuchaction';
478 }
479
480 # Workaround for bug #20966: inability of IE to provide an action dependent
481 # on which submit button is clicked.
482 if ( $action === 'historysubmit' ) {
483 if ( $request->getBool( 'revisiondelete' ) ) {
484 $action = 'revisiondelete';
485 } else {
486 $action = 'view';
487 }
488 }
489
490 switch( $action ) {
491 case 'view':
492 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
493 $article->view();
494 break;
495 case 'raw': // includes JS/CSS
496 wfProfileIn( __METHOD__.'-raw' );
497 $raw = new RawPage( $article );
498 $raw->view();
499 wfProfileOut( __METHOD__.'-raw' );
500 break;
501 case 'watch':
502 case 'unwatch':
503 case 'delete':
504 case 'revert':
505 case 'rollback':
506 case 'protect':
507 case 'unprotect':
508 case 'info':
509 case 'markpatrolled':
510 case 'render':
511 case 'deletetrackback':
512 case 'purge':
513 $article->$action();
514 break;
515 case 'print':
516 $article->view();
517 break;
518 case 'dublincore':
519 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
520 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
521 } else {
522 $rdf = new DublinCoreRdf( $article );
523 $rdf->show();
524 }
525 break;
526 case 'creativecommons':
527 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
528 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
529 } else {
530 $rdf = new CreativeCommonsRdf( $article );
531 $rdf->show();
532 }
533 break;
534 case 'credits':
535 Credits::showPage( $article );
536 break;
537 case 'submit':
538 if( session_id() == '' ) {
539 /* Send a cookie so anons get talk message notifications */
540 wfSetupSession();
541 }
542 /* Continue... */
543 case 'edit':
544 case 'editredlink':
545 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
546 $internal = $request->getVal( 'internaledit' );
547 $external = $request->getVal( 'externaledit' );
548 $section = $request->getVal( 'section' );
549 $oldid = $request->getVal( 'oldid' );
550 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
551 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
552 $editor = new EditPage( $article );
553 $editor->submit();
554 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
555 $mode = $request->getVal( 'mode' );
556 $extedit = new ExternalEdit( $article, $mode );
557 $extedit->edit();
558 }
559 }
560 break;
561 case 'history':
562 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
563 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
564 }
565 $history = new HistoryPage( $article );
566 $history->history();
567 break;
568 case 'revisiondelete':
569 # For show/hide submission from history page
570 $special = SpecialPage::getPage( 'Revisiondelete' );
571 $special->execute( '' );
572 break;
573 default:
574 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
575 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
576 }
577 }
578 wfProfileOut( __METHOD__ );
579
580 }
581
582 }; /* End of class MediaWiki */