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