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