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