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