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