Follow-up r85226, r85227: add @since annotations
[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 if( $request->getVal( 'printable' ) === 'yes' ) {
53 $output->setPrintable();
54 }
55
56 wfRunHooks( 'BeforeInitialize', array( &$title, &$article, &$output, &$user, $request, $this ) );
57
58 if( !$this->preliminaryChecks( $title, $output ) ) {
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 *
101 * @param $request WebRequest
102 * @return Title object to be $wgTitle
103 */
104 function checkInitialQueries( WebRequest $request ) {
105 global $wgContLang;
106
107 $curid = $request->getInt( 'curid' );
108 $title = $request->getVal( 'title' );
109
110 if( $request->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 == '' && $this->getAction( $request ) != '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 = $request->getInt( 'oldid' );
131 $oldid = $oldid ? $oldid : $request->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 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
177 if( is_null($title) || ( ( $title->getDBkey() == '' ) && ( $title->getInterwiki() == '' ) ) ) {
178 $title = SpecialPage::getTitleFor( 'Badtitle' );
179 $output->setTitle( $title ); // bug 21456
180 // Die now before we mess up $wgArticle and the skin stops working
181 throw new ErrorPageError( 'badtitle', 'badtitletext' );
182
183 // Interwiki redirects
184 } else if( $title->getInterwiki() != '' ) {
185 $rdfrom = $request->getVal( 'rdfrom' );
186 if( $rdfrom ) {
187 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
188 } else {
189 $query = $request->getValues();
190 unset( $query['title'] );
191 $url = $title->getFullURL( $query );
192 }
193 /* Check for a redirect loop */
194 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
195 // 301 so google et al report the target as the actual url.
196 $output->redirect( $url, 301 );
197 } else {
198 $title = SpecialPage::getTitleFor( 'Badtitle' );
199 $output->setTitle( $title ); // bug 21456
200 wfProfileOut( __METHOD__ );
201 throw new ErrorPageError( 'badtitle', 'badtitletext' );
202 }
203 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
204 } else if ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
205 && ( $request->getVal( 'title' ) === null || $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
206 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
207 {
208 if ( $title->getNamespace() == NS_SPECIAL ) {
209 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
210 if ( $name ) {
211 $title = SpecialPage::getTitleFor( $name, $subpage );
212 }
213 }
214 $targetUrl = $title->getFullURL();
215 // Redirect to canonical url, make it a 301 to allow caching
216 if( $targetUrl == $request->getFullRequestURL() ) {
217 $message = "Redirect loop detected!\n\n" .
218 "This means the wiki got confused about what page was " .
219 "requested; this sometimes happens when moving a wiki " .
220 "to a new server or changing the server configuration.\n\n";
221
222 if( $this->getVal( 'UsePathInfo' ) ) {
223 $message .= "The wiki is trying to interpret the page " .
224 "title from the URL path portion (PATH_INFO), which " .
225 "sometimes fails depending on the web server. Try " .
226 "setting \"\$wgUsePathInfo = false;\" in your " .
227 "LocalSettings.php, or check that \$wgArticlePath " .
228 "is correct.";
229 } else {
230 $message .= "Your web server was detected as possibly not " .
231 "supporting URL path components (PATH_INFO) correctly; " .
232 "check your LocalSettings.php for a customized " .
233 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
234 "to true.";
235 }
236 wfHttpError( 500, "Internal error", $message );
237 wfProfileOut( __METHOD__ );
238 return false;
239 } else {
240 $output->setSquidMaxage( 1200 );
241 $output->redirect( $targetUrl, '301' );
242 }
243 // Special pages
244 } else if( NS_SPECIAL == $title->getNamespace() ) {
245 /* actions that need to be made when we have a special pages */
246 SpecialPage::executePath( $title );
247 } else {
248 /* No match to special cases */
249 wfProfileOut( __METHOD__ );
250 return false;
251 }
252 /* Did match a special case */
253 wfProfileOut( __METHOD__ );
254 return true;
255 }
256
257 /**
258 * Create an Article object of the appropriate class for the given page.
259 *
260 * @param $title Title
261 * @return Article object
262 */
263 static function articleFromTitle( &$title ) {
264 if( NS_MEDIA == $title->getNamespace() ) {
265 // FIXME: where should this go?
266 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
267 }
268
269 $article = null;
270 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
271 if( $article ) {
272 return $article;
273 }
274
275 switch( $title->getNamespace() ) {
276 case NS_FILE:
277 return new ImagePage( $title );
278 case NS_CATEGORY:
279 return new CategoryPage( $title );
280 default:
281 return new Article( $title );
282 }
283 }
284
285 /**
286 * Returns the action that will be executed, not necesserly the one passed
287 * passed through the "action" parameter. Actions disabled in
288 * $wgDisabledActions will be replaced by "nosuchaction"
289 *
290 * @param $request WebRequest
291 * @return String: action
292 */
293 public function getAction( WebRequest $request ) {
294 global $wgDisabledActions;
295
296 $action = $request->getVal( 'action', 'view' );
297
298 // Check for disabled actions
299 if( in_array( $action, $wgDisabledActions ) ) {
300 return 'nosuchaction';
301 }
302
303 // Workaround for bug #20966: inability of IE to provide an action dependent
304 // on which submit button is clicked.
305 if ( $action === 'historysubmit' ) {
306 if ( $request->getBool( 'revisiondelete' ) ) {
307 return 'revisiondelete';
308 } elseif ( $request->getBool( 'revisionmove' ) ) {
309 return 'revisionmove';
310 } else {
311 return 'view';
312 }
313 } elseif ( $action == 'editredlink' ) {
314 return 'edit';
315 }
316
317 return $action;
318 }
319
320 /**
321 * Initialize the object to be known as $wgArticle for "standard" actions
322 * Create an Article object for the page, following redirects if needed.
323 *
324 * @param $title Title ($wgTitle)
325 * @param $output OutputPage ($wgOut)
326 * @param $request WebRequest ($wgRequest)
327 * @return mixed an Article, or a string to redirect to another URL
328 */
329 function initializeArticle( &$title, &$output, $request ) {
330 wfProfileIn( __METHOD__ );
331
332 $action = $request->getVal( 'action', 'view' );
333 $article = self::articleFromTitle( $title );
334 // NS_MEDIAWIKI has no redirects.
335 // It is also used for CSS/JS, so performance matters here...
336 if( $title->getNamespace() == NS_MEDIAWIKI ) {
337 wfProfileOut( __METHOD__ );
338 return $article;
339 }
340 // Namespace might change when using redirects
341 // Check for redirects ...
342 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
343 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
344 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
345 !$request->getVal( 'diff' ) && // ... and not when showing diff
346 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
347 // ... and the article is not a non-redirect image page with associated file
348 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
349 {
350 // Give extensions a change to ignore/handle redirects as needed
351 $ignoreRedirect = $target = false;
352
353 wfRunHooks( 'InitializeArticleMaybeRedirect',
354 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
355
356 // Follow redirects only for... redirects.
357 // If $target is set, then a hook wanted to redirect.
358 if( !$ignoreRedirect && ($target || $article->isRedirect()) ) {
359 // Is the target already set by an extension?
360 $target = $target ? $target : $article->followRedirect();
361 if( is_string( $target ) ) {
362 if( !$this->getVal( 'DisableHardRedirects' ) ) {
363 // we'll need to redirect
364 wfProfileOut( __METHOD__ );
365 return $target;
366 }
367 }
368 if( is_object($target) ) {
369 // Rewrite environment to redirected article
370 $rarticle = self::articleFromTitle( $target );
371 $rarticle->loadPageData();
372 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
373 $rarticle->setRedirectedFrom( $title );
374 $article = $rarticle;
375 $title = $target;
376 $output->setTitle( $title );
377 }
378 }
379 } else {
380 $title = $article->getTitle();
381 }
382 }
383 wfProfileOut( __METHOD__ );
384 return $article;
385 }
386
387 /**
388 * Cleaning up request by doing:
389 ** deferred updates, DB transaction, and the output
390 *
391 * @param $output OutputPage
392 */
393 function finalCleanup( &$output ) {
394 wfProfileIn( __METHOD__ );
395 // Now commit any transactions, so that unreported errors after
396 // output() don't roll back the whole DB transaction
397 $factory = wfGetLBFactory();
398 $factory->commitMasterChanges();
399 // Output everything!
400 $output->output();
401 // Do any deferred jobs
402 wfDoUpdates( 'commit' );
403 // Close the session so that jobs don't access the current session
404 session_write_close();
405 $this->doJobs();
406 wfProfileOut( __METHOD__ );
407 }
408
409 /**
410 * Do a job from the job queue
411 */
412 function doJobs() {
413 global $wgJobRunRate;
414
415 if( $wgJobRunRate <= 0 || wfReadOnly() ) {
416 return;
417 }
418 if( $wgJobRunRate < 1 ) {
419 $max = mt_getrandmax();
420 if( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
421 return;
422 }
423 $n = 1;
424 } else {
425 $n = intval( $wgJobRunRate );
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->getAction( $request );
474
475 switch( $action ) {
476 case 'view':
477 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
478 $article->view();
479 break;
480 case 'raw': // includes JS/CSS
481 wfProfileIn( __METHOD__.'-raw' );
482 $raw = new RawPage( $article );
483 $raw->view();
484 wfProfileOut( __METHOD__.'-raw' );
485 break;
486 case 'watch':
487 case 'unwatch':
488 case 'delete':
489 case 'revert':
490 case 'rollback':
491 case 'protect':
492 case 'unprotect':
493 case 'info':
494 case 'markpatrolled':
495 case 'render':
496 case 'deletetrackback':
497 case 'purge':
498 $article->$action();
499 break;
500 case 'print':
501 $article->view();
502 break;
503 case 'dublincore':
504 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
505 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
506 } else {
507 $rdf = new DublinCoreRdf( $article );
508 $rdf->show();
509 }
510 break;
511 case 'creativecommons':
512 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
513 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
514 } else {
515 $rdf = new CreativeCommonsRdf( $article );
516 $rdf->show();
517 }
518 break;
519 case 'credits':
520 Credits::showPage( $article );
521 break;
522 case 'submit':
523 if( session_id() == '' ) {
524 /* Send a cookie so anons get talk message notifications */
525 wfSetupSession();
526 }
527 /* Continue... */
528 case 'edit':
529 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
530 $internal = $request->getVal( 'internaledit' );
531 $external = $request->getVal( 'externaledit' );
532 $section = $request->getVal( 'section' );
533 $oldid = $request->getVal( 'oldid' );
534 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
535 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
536 $editor = new EditPage( $article );
537 $editor->submit();
538 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
539 $mode = $request->getVal( 'mode' );
540 $extedit = new ExternalEdit( $article, $mode );
541 $extedit->edit();
542 }
543 }
544 break;
545 case 'history':
546 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
547 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
548 }
549 $history = new HistoryPage( $article );
550 $history->history();
551 break;
552 case 'revisiondelete':
553 // For show/hide submission from history page
554 $special = SpecialPage::getPage( 'Revisiondelete' );
555 $special->execute( '' );
556 break;
557 case 'revisionmove':
558 // For revision move submission from history page
559 $special = SpecialPage::getPage( 'RevisionMove' );
560 $special->execute( '' );
561 break;
562 default:
563 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
564 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
565 }
566 }
567 wfProfileOut( __METHOD__ );
568
569 }
570
571 }