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