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