Revert r44970 "Add FileCache exit back from r44801"
[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 return true;
243 }
244 }
245 /* No match to special cases */
246 wfProfileOut( __METHOD__ );
247 return false;
248 }
249 /* Did match a special case */
250 wfProfileOut( __METHOD__ );
251 return true;
252 }
253
254 /**
255 * Create an Article object of the appropriate class for the given page.
256 *
257 * @param $title Title
258 * @return Article object
259 */
260 static function articleFromTitle( &$title ) {
261 if( NS_MEDIA == $title->getNamespace() ) {
262 // FIXME: where should this go?
263 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
264 }
265
266 $article = null;
267 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
268 if( $article ) {
269 return $article;
270 }
271
272 switch( $title->getNamespace() ) {
273 case NS_FILE:
274 return new ImagePage( $title );
275 case NS_CATEGORY:
276 return new CategoryPage( $title );
277 default:
278 return new Article( $title );
279 }
280 }
281
282 /**
283 * Initialize the object to be known as $wgArticle for "standard" actions
284 * Create an Article object for the page, following redirects if needed.
285 *
286 * @param $title Title ($wgTitle)
287 * @param $request WebRequest
288 * @return mixed an Article, or a string to redirect to another URL
289 */
290 function initializeArticle( &$title, $request ) {
291 wfProfileIn( __METHOD__ );
292
293 $action = $this->getVal( 'action' );
294 $article = self::articleFromTitle( $title );
295
296 // Namespace might change when using redirects
297 // Check for redirects ...
298 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
299 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
300 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
301 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
302 // ... and the article is not a non-redirect image page with associated file
303 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
304 {
305 # Give extensions a change to ignore/handle redirects as needed
306 $ignoreRedirect = $target = false;
307
308 $dbr = wfGetDB( DB_SLAVE );
309 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
310
311 wfRunHooks( 'InitializeArticleMaybeRedirect',
312 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
313
314 // Follow redirects only for... redirects
315 if( !$ignoreRedirect && $article->isRedirect() ) {
316 # Is the target already set by an extension?
317 $target = $target ? $target : $article->followRedirect();
318 if( is_string( $target ) ) {
319 if( !$this->getVal( 'DisableHardRedirects' ) ) {
320 // we'll need to redirect
321 return $target;
322 }
323 }
324
325 if( is_object( $target ) ) {
326 // Rewrite environment to redirected article
327 $rarticle = self::articleFromTitle( $target );
328 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
329 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
330 $rarticle->setRedirectedFrom( $title );
331 $article = $rarticle;
332 $title = $target;
333 }
334 }
335 } else {
336 $title = $article->getTitle();
337 }
338 }
339 wfProfileOut( __METHOD__ );
340 return $article;
341 }
342
343 /**
344 * Cleaning up by doing deferred updates, calling LBFactory and doing the output
345 *
346 * @param $deferredUpdates array of updates to do
347 * @param $output OutputPage
348 */
349 function finalCleanup( &$deferredUpdates, &$output ) {
350 wfProfileIn( __METHOD__ );
351 # Now commit any transactions, so that unreported errors after output() don't roll back the whole thing
352 $factory = wfGetLBFactory();
353 $factory->commitMasterChanges();
354 # Output everything!
355 $output->output();
356 # Do any deferred jobs
357 $this->doUpdates( $deferredUpdates );
358 $this->doJobs();
359 # Commit and close up!
360 $factory->shutdown();
361 wfProfileOut( __METHOD__ );
362 }
363
364 /**
365 * Deferred updates aren't really deferred anymore. It's important to report
366 * errors to the user, and that means doing this before OutputPage::output().
367 * Note that for page saves, the client will wait until the script exits
368 * anyway before following the redirect.
369 *
370 * @param $updates array of objects that hold an update to do
371 */
372 function doUpdates( &$updates ) {
373 wfProfileIn( __METHOD__ );
374 /* No need to get master connections in case of empty updates array */
375 if (!$updates) {
376 wfProfileOut( __METHOD__ );
377 return;
378 }
379
380 $dbw = wfGetDB( DB_MASTER );
381 foreach( $updates as $up ) {
382 $up->doUpdate();
383
384 # Commit after every update to prevent lock contention
385 if( $dbw->trxLevel() ) {
386 $dbw->commit();
387 }
388 }
389 wfProfileOut( __METHOD__ );
390 }
391
392 /**
393 * Do a job from the job queue
394 */
395 function doJobs() {
396 $jobRunRate = $this->getVal( 'JobRunRate' );
397
398 if( $jobRunRate <= 0 || wfReadOnly() ) {
399 return;
400 }
401 if( $jobRunRate < 1 ) {
402 $max = mt_getrandmax();
403 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
404 return;
405 }
406 $n = 1;
407 } else {
408 $n = intval( $jobRunRate );
409 }
410
411 while ( $n-- && false != ( $job = Job::pop() ) ) {
412 $output = $job->toString() . "\n";
413 $t = -wfTime();
414 $success = $job->run();
415 $t += wfTime();
416 $t = round( $t*1000 );
417 if( !$success ) {
418 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
419 } else {
420 $output .= "Success, Time: $t ms\n";
421 }
422 wfDebugLog( 'jobqueue', $output );
423 }
424 }
425
426 /**
427 * Ends this task peacefully
428 */
429 function restInPeace() {
430 wfLogProfilingData();
431 wfDebug( "Request ended normally\n" );
432 }
433
434 /**
435 * Perform one of the "standard" actions
436 *
437 * @param $output OutputPage
438 * @param $article Article
439 * @param $title Title
440 * @param $user User
441 * @param $request WebRequest
442 */
443 function performAction( &$output, &$article, &$title, &$user, &$request ) {
444 wfProfileIn( __METHOD__ );
445
446 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
447 wfProfileOut( __METHOD__ );
448 return;
449 }
450
451 $action = $this->getVal( 'Action' );
452 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
453 /* No such action; this will switch to the default case */
454 $action = 'nosuchaction';
455 }
456
457 switch( $action ) {
458 case 'view':
459 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
460 $article->view();
461 break;
462 case 'raw': // includes JS/CSS
463 $raw = new RawPage( $article );
464 $raw->view();
465 break;
466 case 'watch':
467 case 'unwatch':
468 case 'delete':
469 case 'revert':
470 case 'rollback':
471 case 'protect':
472 case 'unprotect':
473 case 'info':
474 case 'markpatrolled':
475 case 'render':
476 case 'deletetrackback':
477 case 'purge':
478 $article->$action();
479 break;
480 case 'print':
481 $article->view();
482 break;
483 case 'dublincore':
484 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
485 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
486 } else {
487 $rdf = new DublinCoreRdf( $article );
488 $rdf->show();
489 }
490 break;
491 case 'creativecommons':
492 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
493 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
494 } else {
495 $rdf = new CreativeCommonsRdf( $article );
496 $rdf->show();
497 }
498 break;
499 case 'credits':
500 Credits::showPage( $article );
501 break;
502 case 'submit':
503 if( session_id() == '' ) {
504 /* Send a cookie so anons get talk message notifications */
505 wfSetupSession();
506 }
507 /* Continue... */
508 case 'edit':
509 case 'editredlink':
510 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
511 $internal = $request->getVal( 'internaledit' );
512 $external = $request->getVal( 'externaledit' );
513 $section = $request->getVal( 'section' );
514 $oldid = $request->getVal( 'oldid' );
515 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
516 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
517 $editor = new EditPage( $article );
518 $editor->submit();
519 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
520 $mode = $request->getVal( 'mode' );
521 $extedit = new ExternalEdit( $article, $mode );
522 $extedit->edit();
523 }
524 }
525 break;
526 case 'history':
527 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
528 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
529 }
530 $history = new PageHistory( $article );
531 $history->history();
532 break;
533 default:
534 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
535 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
536 }
537 }
538 wfProfileOut( __METHOD__ );
539
540 }
541
542 }; /* End of class MediaWiki */