reinsert some statements removed by r74745
[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, $request ) ) {
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 $ret = null;
112 $curid = $wgRequest->getInt( 'curid' );
113 if( $curid ) {
114 // URLs like this are generated by RC, because rc_title isn't always accurate
115 $ret = Title::newFromID( $curid );
116 } elseif( $title == '' && $action != 'delete' ) {
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 * @return boolean true if successful
146 */
147 function preliminaryChecks( &$title, &$output, $request ) {
148 if( $request->getCheck( 'search' ) ) {
149 // Compatibility with old search URLs which didn't use Special:Search
150 // Just check for presence here, so blank requests still
151 // show the search page when using ugly URLs (bug 8054).
152
153 // Do this above the read whitelist check for security...
154 $title = SpecialPage::getTitleFor( 'Search' );
155 }
156 // If the user is not logged in, the Namespace:title of the article must be in
157 // the Read array in order for the user to see it. (We have to check here to
158 // catch special pages etc. We check again in Article::view())
159 if( !is_null( $title ) && !$title->userCanRead() ) {
160 global $wgDeferredUpdateList;
161 $output->loginToUse();
162 $this->finalCleanup( $wgDeferredUpdateList, $output );
163 $output->disable();
164 return false;
165 }
166 return true;
167 }
168
169 /**
170 * Initialize some special cases:
171 * - bad titles
172 * - local interwiki redirects
173 * - redirect loop
174 * - special pages
175 *
176 * @param $title Title
177 * @param $output OutputPage
178 * @param $request WebRequest
179 * @return bool true if the request is already executed
180 */
181 function handleSpecialCases( &$title, &$output, $request ) {
182 wfProfileIn( __METHOD__ );
183
184 $action = $this->getVal( 'Action' );
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 $output->setTitle( $title ); // bug 21456
190 // Die now before we mess up $wgArticle and the skin stops working
191 throw new ErrorPageError( 'badtitle', 'badtitletext' );
192
193 // Interwiki redirects
194 } else if( $title->getInterwiki() != '' ) {
195 $rdfrom = $request->getVal( 'rdfrom' );
196 if( $rdfrom ) {
197 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
198 } else {
199 $query = $request->getValues();
200 unset( $query['title'] );
201 $url = $title->getFullURL( $query );
202 }
203 /* Check for a redirect loop */
204 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
205 $output->redirect( $url );
206 } else {
207 $title = SpecialPage::getTitleFor( 'Badtitle' );
208 $output->setTitle( $title ); // bug 21456
209 wfProfileOut( __METHOD__ );
210 throw new ErrorPageError( 'badtitle', 'badtitletext' );
211 }
212 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
213 } else if ( $action == 'view' && !$request->wasPosted()
214 && ( !$request->getVal( 'title' ) || $title->getPrefixedDBKey() != $request->getText( 'title' ) )
215 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
216 {
217 $targetUrl = $title->getFullURL();
218 // Redirect to canonical url, make it a 301 to allow caching
219 if( $targetUrl == $request->getFullRequestURL() ) {
220 $message = "Redirect loop detected!\n\n" .
221 "This means the wiki got confused about what page was " .
222 "requested; this sometimes happens when moving a wiki " .
223 "to a new server or changing the server configuration.\n\n";
224
225 if( $this->getVal( 'UsePathInfo' ) ) {
226 $message .= "The wiki is trying to interpret the page " .
227 "title from the URL path portion (PATH_INFO), which " .
228 "sometimes fails depending on the web server. Try " .
229 "setting \"\$wgUsePathInfo = false;\" in your " .
230 "LocalSettings.php, or check that \$wgArticlePath " .
231 "is correct.";
232 } else {
233 $message .= "Your web server was detected as possibly not " .
234 "supporting URL path components (PATH_INFO) correctly; " .
235 "check your LocalSettings.php for a customized " .
236 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
237 "to true.";
238 }
239 wfHttpError( 500, "Internal error", $message );
240 wfProfileOut( __METHOD__ );
241 return false;
242 } else {
243 $output->setSquidMaxage( 1200 );
244 $output->redirect( $targetUrl, '301' );
245 }
246 // Special pages
247 } else if( NS_SPECIAL == $title->getNamespace() ) {
248 /* actions that need to be made when we have a special pages */
249 SpecialPage::executePath( $title );
250 } else {
251 /* No match to special cases */
252 wfProfileOut( __METHOD__ );
253 return false;
254 }
255 /* Did match a special case */
256 wfProfileOut( __METHOD__ );
257 return true;
258 }
259
260 /**
261 * Create an Article object of the appropriate class for the given page.
262 *
263 * @param $title Title
264 * @return Article object
265 */
266 static function articleFromTitle( &$title ) {
267 if( NS_MEDIA == $title->getNamespace() ) {
268 // FIXME: where should this go?
269 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
270 }
271
272 $article = null;
273 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
274 if( $article ) {
275 return $article;
276 }
277
278 switch( $title->getNamespace() ) {
279 case NS_FILE:
280 return new ImagePage( $title );
281 case NS_CATEGORY:
282 return new CategoryPage( $title );
283 default:
284 return new Article( $title );
285 }
286 }
287
288 /**
289 * Initialize the object to be known as $wgArticle for "standard" actions
290 * Create an Article object for the page, following redirects if needed.
291 *
292 * @param $title Title ($wgTitle)
293 * @param $output OutputPage ($wgOut)
294 * @param $request WebRequest ($wgRequest)
295 * @return mixed an Article, or a string to redirect to another URL
296 */
297 function initializeArticle( &$title, &$output, $request ) {
298 wfProfileIn( __METHOD__ );
299
300 $action = $this->getVal( 'action', 'view' );
301 $article = self::articleFromTitle( $title );
302 // NS_MEDIAWIKI has no redirects.
303 // It is also used for CSS/JS, so performance matters here...
304 if( $title->getNamespace() == NS_MEDIAWIKI ) {
305 wfProfileOut( __METHOD__ );
306 return $article;
307 }
308 // Namespace might change when using redirects
309 // Check for redirects ...
310 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
311 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
312 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
313 !$request->getVal( 'diff' ) && // ... and not when showing diff
314 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
315 // ... and the article is not a non-redirect image page with associated file
316 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
317 {
318 // Give extensions a change to ignore/handle redirects as needed
319 $ignoreRedirect = $target = false;
320
321 $dbr = wfGetDB( DB_SLAVE );
322 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
323
324 wfRunHooks( 'InitializeArticleMaybeRedirect',
325 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
326
327 // Follow redirects only for... redirects.
328 // If $target is set, then a hook wanted to redirect.
329 if( !$ignoreRedirect && ($target || $article->isRedirect()) ) {
330 // Is the target already set by an extension?
331 $target = $target ? $target : $article->followRedirect();
332 if( is_string( $target ) ) {
333 if( !$this->getVal( 'DisableHardRedirects' ) ) {
334 // we'll need to redirect
335 wfProfileOut( __METHOD__ );
336 return $target;
337 }
338 }
339 if( is_object($target) ) {
340 // Rewrite environment to redirected article
341 $rarticle = self::articleFromTitle( $target );
342 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
343 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
344 $rarticle->setRedirectedFrom( $title );
345 $article = $rarticle;
346 $title = $target;
347 $output->setTitle( $title );
348 }
349 }
350 } else {
351 $title = $article->getTitle();
352 }
353 }
354 wfProfileOut( __METHOD__ );
355 return $article;
356 }
357
358 /**
359 * Cleaning up request by doing:
360 ** deferred updates, DB transaction, and the output
361 *
362 * @param $deferredUpdates array of updates to do
363 * @param $output OutputPage
364 */
365 function finalCleanup( &$deferredUpdates, &$output ) {
366 wfProfileIn( __METHOD__ );
367 // Now commit any transactions, so that unreported errors after
368 // output() don't roll back the whole DB transaction
369 $factory = wfGetLBFactory();
370 $factory->commitMasterChanges();
371 // Output everything!
372 $output->output();
373 // Do any deferred jobs
374 $this->doUpdates( $deferredUpdates );
375 // Close the session so that jobs don't access the current session
376 session_write_close();
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 MessageCache::logMessages();
448 wfLogProfilingData();
449 // Commit and close up!
450 $factory = wfGetLBFactory();
451 $factory->commitMasterChanges();
452 $factory->shutdown();
453 wfDebug( "Request ended normally\n" );
454 }
455
456 /**
457 * Perform one of the "standard" actions
458 *
459 * @param $output OutputPage
460 * @param $article Article
461 * @param $title Title
462 * @param $user User
463 * @param $request WebRequest
464 */
465 function performAction( &$output, &$article, &$title, &$user, &$request ) {
466 wfProfileIn( __METHOD__ );
467
468 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
469 wfProfileOut( __METHOD__ );
470 return;
471 }
472
473 $action = $this->getVal( 'Action' );
474 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
475 /* No such action; this will switch to the default case */
476 $action = 'nosuchaction';
477 }
478
479 // Workaround for bug #20966: inability of IE to provide an action dependent
480 // on which submit button is clicked.
481 if ( $action === 'historysubmit' ) {
482 if ( $request->getBool( 'revisiondelete' ) ) {
483 $action = 'revisiondelete';
484 } elseif ( $request->getBool( 'revisionmove' ) ) {
485 $action = 'revisionmove';
486 } else {
487 $action = 'view';
488 }
489 }
490
491 switch( $action ) {
492 case 'view':
493 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
494 $article->view();
495 break;
496 case 'raw': // includes JS/CSS
497 wfProfileIn( __METHOD__.'-raw' );
498 $raw = new RawPage( $article );
499 $raw->view();
500 wfProfileOut( __METHOD__.'-raw' );
501 break;
502 case 'watch':
503 case 'unwatch':
504 case 'delete':
505 case 'revert':
506 case 'rollback':
507 case 'protect':
508 case 'unprotect':
509 case 'info':
510 case 'markpatrolled':
511 case 'render':
512 case 'deletetrackback':
513 case 'purge':
514 $article->$action();
515 break;
516 case 'print':
517 $article->view();
518 break;
519 case 'dublincore':
520 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
521 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
522 } else {
523 $rdf = new DublinCoreRdf( $article );
524 $rdf->show();
525 }
526 break;
527 case 'creativecommons':
528 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
529 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
530 } else {
531 $rdf = new CreativeCommonsRdf( $article );
532 $rdf->show();
533 }
534 break;
535 case 'credits':
536 Credits::showPage( $article );
537 break;
538 case 'submit':
539 if( session_id() == '' ) {
540 /* Send a cookie so anons get talk message notifications */
541 wfSetupSession();
542 }
543 /* Continue... */
544 case 'edit':
545 case 'editredlink':
546 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
547 $internal = $request->getVal( 'internaledit' );
548 $external = $request->getVal( 'externaledit' );
549 $section = $request->getVal( 'section' );
550 $oldid = $request->getVal( 'oldid' );
551 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
552 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
553 $editor = new EditPage( $article );
554 $editor->submit();
555 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
556 $mode = $request->getVal( 'mode' );
557 $extedit = new ExternalEdit( $article, $mode );
558 $extedit->edit();
559 }
560 }
561 break;
562 case 'history':
563 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
564 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
565 }
566 $history = new HistoryPage( $article );
567 $history->history();
568 break;
569 case 'revisiondelete':
570 // For show/hide submission from history page
571 $special = SpecialPage::getPage( 'Revisiondelete' );
572 $special->execute( '' );
573 break;
574 case 'revisionmove':
575 // For revision move submission from history page
576 $special = SpecialPage::getPage( 'RevisionMove' );
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 }