(bug 26130) Revert changes to WebStart.php in r72349, which turn out to have been...
[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 var $params = array();
9
10 /** Constructor */
11 function __construct() {}
12
13 /**
14 * Stores key/value pairs to circumvent global variables
15 * Note that keys are case-insensitive!
16 *
17 * @param $key String: key to store
18 * @param $value Mixed: value to put for the key
19 */
20 function setVal( $key, &$value ) {
21 $key = strtolower( $key );
22 $this->params[$key] =& $value;
23 }
24
25 /**
26 * Retrieves key/value pairs to circumvent global variables
27 * Note that keys are case-insensitive!
28 *
29 * @param $key String: key to get
30 * @param $default string default value, defaults to empty string
31 * @return $default Mixed: default value if if the key doesn't exist
32 */
33 function getVal( $key, $default = '' ) {
34 $key = strtolower( $key );
35 if( isset( $this->params[$key] ) ) {
36 return $this->params[$key];
37 }
38 return $default;
39 }
40
41 /**
42 * Initialization of ... everything
43 * Performs the request too
44 *
45 * @param $title Title ($wgTitle)
46 * @param $article Article
47 * @param $output OutputPage
48 * @param $user User
49 * @param $request WebRequest
50 */
51 function performRequestForTitle( &$title, &$article, &$output, &$user, $request ) {
52 wfProfileIn( __METHOD__ );
53
54 $output->setTitle( $title );
55
56 wfRunHooks( 'BeforeInitialize', array( &$title, &$article, &$output, &$user, $request, $this ) );
57
58 if( !$this->preliminaryChecks( $title, $output ) ) {
59 wfProfileOut( __METHOD__ );
60 return;
61 }
62 // Call handleSpecialCases() to deal with all special requests...
63 if( !$this->handleSpecialCases( $title, $output, $request ) ) {
64 // ...otherwise treat it as an article view. The article
65 // may be a redirect to another article or URL.
66 $new_article = $this->initializeArticle( $title, $output, $request );
67 if( is_object( $new_article ) ) {
68 $article = $new_article;
69 $this->performAction( $output, $article, $title, $user, $request );
70 } elseif( is_string( $new_article ) ) {
71 $output->redirect( $new_article );
72 } else {
73 wfProfileOut( __METHOD__ );
74 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
75 }
76 }
77 wfProfileOut( __METHOD__ );
78 }
79
80 /**
81 * Check if the maximum lag of database slaves is higher that $maxLag, and
82 * if it's the case, output an error message
83 *
84 * @param $maxLag int: maximum lag allowed for the request, as supplied by
85 * the client
86 * @return bool true if the request can continue
87 */
88 function checkMaxLag( $maxLag ) {
89 list( $host, $lag ) = wfGetLB()->getMaxLag();
90 if( $lag > $maxLag ) {
91 wfMaxlagError( $host, $lag, $maxLag );
92 return false;
93 } else {
94 return true;
95 }
96 }
97
98 /**
99 * Checks some initial queries
100 * Note that $title here is *not* a Title object, but a string!
101 *
102 * @param $title String
103 * @param $action String
104 * @return Title object to be $wgTitle
105 */
106 function checkInitialQueries( $title, $action ) {
107 global $wgOut, $wgRequest, $wgContLang;
108 if( $wgRequest->getVal( 'printable' ) === 'yes' ) {
109 $wgOut->setPrintable();
110 }
111
112 $curid = $wgRequest->getInt( 'curid' );
113 if( $wgRequest->getCheck( 'search' ) ) {
114 // Compatibility with old search URLs which didn't use Special:Search
115 // Just check for presence here, so blank requests still
116 // show the search page when using ugly URLs (bug 8054).
117 $ret = SpecialPage::getTitleFor( 'Search' );
118 } elseif( $curid ) {
119 // URLs like this are generated by RC, because rc_title isn't always accurate
120 $ret = Title::newFromID( $curid );
121 } elseif( $title == '' && $action != 'delete' ) {
122 $ret = Title::newMainPage();
123 } else {
124 $ret = Title::newFromURL( $title );
125 // check variant links so that interwiki links don't have to worry
126 // about the possible different language variants
127 if( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 )
128 $wgContLang->findVariantLink( $title, $ret );
129 }
130 // For non-special titles, check for implicit titles
131 if( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
132 // We can have urls with just ?diff=,?oldid= or even just ?diff=
133 $oldid = $wgRequest->getInt( 'oldid' );
134 $oldid = $oldid ? $oldid : $wgRequest->getInt( 'diff' );
135 // Allow oldid to override a changed or missing title
136 if( $oldid ) {
137 $rev = Revision::newFromId( $oldid );
138 $ret = $rev ? $rev->getTitle() : $ret;
139 }
140 }
141 return $ret;
142 }
143
144 /**
145 * Checks for anon-cannot-read case
146 *
147 * @param $title Title
148 * @param $output OutputPage
149 * @return boolean true if successful
150 */
151 function preliminaryChecks( &$title, &$output ) {
152 // If the user is not logged in, the Namespace:title of the article must be in
153 // the Read array in order for the user to see it. (We have to check here to
154 // catch special pages etc. We check again in Article::view())
155 if( !is_null( $title ) && !$title->userCanRead() ) {
156 global $wgDeferredUpdateList;
157 $output->loginToUse();
158 $this->finalCleanup( $wgDeferredUpdateList, $output );
159 $output->disable();
160 return false;
161 }
162 return true;
163 }
164
165 /**
166 * Initialize some special cases:
167 * - bad titles
168 * - local interwiki redirects
169 * - redirect loop
170 * - special pages
171 *
172 * @param $title Title
173 * @param $output OutputPage
174 * @param $request WebRequest
175 * @return bool true if the request is already executed
176 */
177 function handleSpecialCases( &$title, &$output, $request ) {
178 wfProfileIn( __METHOD__ );
179
180 $action = $this->getVal( 'Action' );
181
182 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
183 if( is_null($title) || ( ( $title->getDBkey() == '' ) && ( $title->getInterwiki() == '' ) ) ) {
184 $title = SpecialPage::getTitleFor( 'Badtitle' );
185 $output->setTitle( $title ); // bug 21456
186 // Die now before we mess up $wgArticle and the skin stops working
187 throw new ErrorPageError( 'badtitle', 'badtitletext' );
188
189 // Interwiki redirects
190 } else if( $title->getInterwiki() != '' ) {
191 $rdfrom = $request->getVal( 'rdfrom' );
192 if( $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 $output->setTitle( $title ); // bug 21456
205 wfProfileOut( __METHOD__ );
206 throw new ErrorPageError( 'badtitle', 'badtitletext' );
207 }
208 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
209 } else if ( $action == 'view' && !$request->wasPosted()
210 && ( $request->getVal( 'title' ) === null || $title->getPrefixedDBKey() != $request->getText( 'title' ) )
211 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
212 {
213 if ( $title->getNamespace() == NS_SPECIAL ) {
214 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
215 if ( $name ) {
216 $title = SpecialPage::getTitleFor( $name, $subpage );
217 }
218 }
219 $targetUrl = $title->getFullURL();
220 // Redirect to canonical url, make it a 301 to allow caching
221 if( $targetUrl == $request->getFullRequestURL() ) {
222 $message = "Redirect loop detected!\n\n" .
223 "This means the wiki got confused about what page was " .
224 "requested; this sometimes happens when moving a wiki " .
225 "to a new server or changing the server configuration.\n\n";
226
227 if( $this->getVal( 'UsePathInfo' ) ) {
228 $message .= "The wiki is trying to interpret the page " .
229 "title from the URL path portion (PATH_INFO), which " .
230 "sometimes fails depending on the web server. Try " .
231 "setting \"\$wgUsePathInfo = false;\" in your " .
232 "LocalSettings.php, or check that \$wgArticlePath " .
233 "is correct.";
234 } else {
235 $message .= "Your web server was detected as possibly not " .
236 "supporting URL path components (PATH_INFO) correctly; " .
237 "check your LocalSettings.php for a customized " .
238 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
239 "to true.";
240 }
241 wfHttpError( 500, "Internal error", $message );
242 wfProfileOut( __METHOD__ );
243 return false;
244 } else {
245 $output->setSquidMaxage( 1200 );
246 $output->redirect( $targetUrl, '301' );
247 }
248 // Special pages
249 } else if( NS_SPECIAL == $title->getNamespace() ) {
250 /* actions that need to be made when we have a special pages */
251 SpecialPage::executePath( $title );
252 } else {
253 /* No match to special cases */
254 wfProfileOut( __METHOD__ );
255 return false;
256 }
257 /* Did match a special case */
258 wfProfileOut( __METHOD__ );
259 return true;
260 }
261
262 /**
263 * Create an Article object of the appropriate class for the given page.
264 *
265 * @param $title Title
266 * @return Article object
267 */
268 static function articleFromTitle( &$title ) {
269 if( NS_MEDIA == $title->getNamespace() ) {
270 // FIXME: where should this go?
271 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
272 }
273
274 $article = null;
275 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
276 if( $article ) {
277 return $article;
278 }
279
280 switch( $title->getNamespace() ) {
281 case NS_FILE:
282 return new ImagePage( $title );
283 case NS_CATEGORY:
284 return new CategoryPage( $title );
285 default:
286 return new Article( $title );
287 }
288 }
289
290 /**
291 * Initialize the object to be known as $wgArticle for "standard" actions
292 * Create an Article object for the page, following redirects if needed.
293 *
294 * @param $title Title ($wgTitle)
295 * @param $output OutputPage ($wgOut)
296 * @param $request WebRequest ($wgRequest)
297 * @return mixed an Article, or a string to redirect to another URL
298 */
299 function initializeArticle( &$title, &$output, $request ) {
300 wfProfileIn( __METHOD__ );
301
302 $action = $this->getVal( 'action', 'view' );
303 $article = self::articleFromTitle( $title );
304 // NS_MEDIAWIKI has no redirects.
305 // It is also used for CSS/JS, so performance matters here...
306 if( $title->getNamespace() == NS_MEDIAWIKI ) {
307 wfProfileOut( __METHOD__ );
308 return $article;
309 }
310 // Namespace might change when using redirects
311 // Check for redirects ...
312 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
313 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
314 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
315 !$request->getVal( 'diff' ) && // ... and not when showing diff
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 // Close the session so that jobs don't access the current session
378 session_write_close();
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 MessageCache::logMessages();
450 wfLogProfilingData();
451 // Commit and close up!
452 $factory = wfGetLBFactory();
453 $factory->commitMasterChanges();
454 $factory->shutdown();
455 wfDebug( "Request ended normally\n" );
456 }
457
458 /**
459 * Perform one of the "standard" actions
460 *
461 * @param $output OutputPage
462 * @param $article Article
463 * @param $title Title
464 * @param $user User
465 * @param $request WebRequest
466 */
467 function performAction( &$output, &$article, &$title, &$user, &$request ) {
468 wfProfileIn( __METHOD__ );
469
470 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
471 wfProfileOut( __METHOD__ );
472 return;
473 }
474
475 $action = $this->getVal( 'Action' );
476 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
477 /* No such action; this will switch to the default case */
478 $action = 'nosuchaction';
479 }
480
481 // Workaround for bug #20966: inability of IE to provide an action dependent
482 // on which submit button is clicked.
483 if ( $action === 'historysubmit' ) {
484 if ( $request->getBool( 'revisiondelete' ) ) {
485 $action = 'revisiondelete';
486 } elseif ( $request->getBool( 'revisionmove' ) ) {
487 $action = 'revisionmove';
488 } else {
489 $action = 'view';
490 }
491 }
492
493 switch( $action ) {
494 case 'view':
495 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
496 $article->view();
497 break;
498 case 'raw': // includes JS/CSS
499 wfProfileIn( __METHOD__.'-raw' );
500 $raw = new RawPage( $article );
501 $raw->view();
502 wfProfileOut( __METHOD__.'-raw' );
503 break;
504 case 'watch':
505 case 'unwatch':
506 case 'delete':
507 case 'revert':
508 case 'rollback':
509 case 'protect':
510 case 'unprotect':
511 case 'info':
512 case 'markpatrolled':
513 case 'render':
514 case 'deletetrackback':
515 case 'purge':
516 $article->$action();
517 break;
518 case 'print':
519 $article->view();
520 break;
521 case 'dublincore':
522 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
523 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
524 } else {
525 $rdf = new DublinCoreRdf( $article );
526 $rdf->show();
527 }
528 break;
529 case 'creativecommons':
530 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
531 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
532 } else {
533 $rdf = new CreativeCommonsRdf( $article );
534 $rdf->show();
535 }
536 break;
537 case 'credits':
538 Credits::showPage( $article );
539 break;
540 case 'submit':
541 if( session_id() == '' ) {
542 /* Send a cookie so anons get talk message notifications */
543 wfSetupSession();
544 }
545 /* Continue... */
546 case 'edit':
547 case 'editredlink':
548 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
549 $internal = $request->getVal( 'internaledit' );
550 $external = $request->getVal( 'externaledit' );
551 $section = $request->getVal( 'section' );
552 $oldid = $request->getVal( 'oldid' );
553 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
554 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
555 $editor = new EditPage( $article );
556 $editor->submit();
557 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
558 $mode = $request->getVal( 'mode' );
559 $extedit = new ExternalEdit( $article, $mode );
560 $extedit->edit();
561 }
562 }
563 break;
564 case 'history':
565 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
566 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
567 }
568 $history = new HistoryPage( $article );
569 $history->history();
570 break;
571 case 'revisiondelete':
572 // For show/hide submission from history page
573 $special = SpecialPage::getPage( 'Revisiondelete' );
574 $special->execute( '' );
575 break;
576 case 'revisionmove':
577 // For revision move submission from history page
578 $special = SpecialPage::getPage( 'RevisionMove' );
579 $special->execute( '' );
580 break;
581 default:
582 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
583 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
584 }
585 }
586 wfProfileOut( __METHOD__ );
587
588 }
589
590 }