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