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