Refactor the retrieval of the cache timestamp into getCachedTimestamp() so the future...
[lhc/web/wiklou.git] / includes / Wiki.php
1 <?php
2 /**
3 * MediaWiki is the to-be base class for this whole project
4 *
5 * @internal documentation reviewed 15 Mar 2010
6 */
7 class MediaWiki {
8 var $params = array();
9
10 /**
11 * Stores key/value pairs to circumvent global variables
12 * Note that keys are case-insensitive!
13 *
14 * @param $key String: key to store
15 * @param $value Mixed: value to put for the key
16 */
17 function setVal( $key, &$value ) {
18 $key = strtolower( $key );
19 $this->params[$key] =& $value;
20 }
21
22 /**
23 * Retrieves key/value pairs to circumvent global variables
24 * Note that keys are case-insensitive!
25 *
26 * @param $key String: key to get
27 * @param $default string default value, defaults to empty string
28 * @return $default Mixed: default value if if the key doesn't exist
29 */
30 function getVal( $key, $default = '' ) {
31 $key = strtolower( $key );
32 if( isset( $this->params[$key] ) ) {
33 return $this->params[$key];
34 }
35 return $default;
36 }
37
38 /**
39 * Initialization of ... everything
40 * Performs the request too
41 *
42 * @param $title Title ($wgTitle)
43 * @param $article Article
44 * @param $output OutputPage
45 * @param $user User
46 * @param $request WebRequest
47 */
48 function performRequestForTitle( &$title, &$article, &$output, &$user, $request ) {
49 wfProfileIn( __METHOD__ );
50
51 $output->setTitle( $title );
52 if( $request->getVal( 'printable' ) === 'yes' ) {
53 $output->setPrintable();
54 }
55
56 wfRunHooks( 'BeforeInitialize', array( &$title, &$article, &$output, &$user, $request, $this ) );
57
58 if( !$this->preliminaryChecks( $title, $output ) ) {
59 wfProfileOut( __METHOD__ );
60 return;
61 }
62 // Call handleSpecialCases() to deal with all special requests...
63 if( !$this->handleSpecialCases( $title, $output, $request ) ) {
64 // ...otherwise treat it as an article view. The article
65 // may be a redirect to another article or URL.
66 $new_article = $this->initializeArticle( $title, $output, $request );
67 if( is_object( $new_article ) ) {
68 $article = $new_article;
69 $this->performAction( $output, $article, $title, $user, $request );
70 } elseif( is_string( $new_article ) ) {
71 $output->redirect( $new_article );
72 } else {
73 wfProfileOut( __METHOD__ );
74 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
75 }
76 }
77 wfProfileOut( __METHOD__ );
78 }
79
80 /**
81 * Check if the maximum lag of database slaves is higher that $maxLag, and
82 * if it's the case, output an error message
83 *
84 * @param $maxLag int: maximum lag allowed for the request, as supplied by
85 * the client
86 * @return bool true if the request can continue
87 */
88 function checkMaxLag( $maxLag ) {
89 list( $host, $lag ) = wfGetLB()->getMaxLag();
90 if( $lag > $maxLag ) {
91 wfMaxlagError( $host, $lag, $maxLag );
92 return false;
93 } else {
94 return true;
95 }
96 }
97
98 /**
99 * Checks some initial queries
100 *
101 * @param $request WebRequest
102 * @return Title object to be $wgTitle
103 */
104 function checkInitialQueries( WebRequest $request ) {
105 global $wgContLang;
106
107 $curid = $request->getInt( 'curid' );
108 $title = $request->getVal( 'title' );
109
110 if( $request->getCheck( 'search' ) ) {
111 // Compatibility with old search URLs which didn't use Special:Search
112 // Just check for presence here, so blank requests still
113 // show the search page when using ugly URLs (bug 8054).
114 $ret = SpecialPage::getTitleFor( 'Search' );
115 } elseif( $curid ) {
116 // URLs like this are generated by RC, because rc_title isn't always accurate
117 $ret = Title::newFromID( $curid );
118 } elseif( $title == '' && $this->getAction( $request ) != 'delete' ) {
119 $ret = Title::newMainPage();
120 } else {
121 $ret = Title::newFromURL( $title );
122 // check variant links so that interwiki links don't have to worry
123 // about the possible different language variants
124 if( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 )
125 $wgContLang->findVariantLink( $title, $ret );
126 }
127 // For non-special titles, check for implicit titles
128 if( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
129 // We can have urls with just ?diff=,?oldid= or even just ?diff=
130 $oldid = $request->getInt( 'oldid' );
131 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
132 // Allow oldid to override a changed or missing title
133 if( $oldid ) {
134 $rev = Revision::newFromId( $oldid );
135 $ret = $rev ? $rev->getTitle() : $ret;
136 }
137 }
138 return $ret;
139 }
140
141 /**
142 * Checks for anon-cannot-read case
143 *
144 * @param $title Title
145 * @param $output OutputPage
146 * @return boolean true if successful
147 */
148 function preliminaryChecks( &$title, &$output ) {
149 // If the user is not logged in, the Namespace:title of the article must be in
150 // the Read array in order for the user to see it. (We have to check here to
151 // catch special pages etc. We check again in Article::view())
152 if( !is_null( $title ) && !$title->userCanRead() ) {
153 $output->loginToUse();
154 $this->finalCleanup( $output );
155 $output->disable();
156 return false;
157 }
158 return true;
159 }
160
161 /**
162 * Initialize some special cases:
163 * - bad titles
164 * - local interwiki redirects
165 * - redirect loop
166 * - special pages
167 *
168 * @param $title Title
169 * @param $output OutputPage
170 * @param $request WebRequest
171 * @return bool true if the request is already executed
172 */
173 function handleSpecialCases( &$title, &$output, $request ) {
174 wfProfileIn( __METHOD__ );
175
176 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
177 if( is_null($title) || ( ( $title->getDBkey() == '' ) && ( $title->getInterwiki() == '' ) ) ) {
178 $title = SpecialPage::getTitleFor( 'Badtitle' );
179 $output->setTitle( $title ); // bug 21456
180 // Die now before we mess up $wgArticle and the skin stops working
181 throw new ErrorPageError( 'badtitle', 'badtitletext' );
182
183 // Interwiki redirects
184 } else if( $title->getInterwiki() != '' ) {
185 $rdfrom = $request->getVal( 'rdfrom' );
186 if( $rdfrom ) {
187 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
188 } else {
189 $query = $request->getValues();
190 unset( $query['title'] );
191 $url = $title->getFullURL( $query );
192 }
193 /* Check for a redirect loop */
194 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
195 $output->redirect( $url );
196 } else {
197 $title = SpecialPage::getTitleFor( 'Badtitle' );
198 $output->setTitle( $title ); // bug 21456
199 wfProfileOut( __METHOD__ );
200 throw new ErrorPageError( 'badtitle', 'badtitletext' );
201 }
202 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
203 } else if ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
204 && ( $request->getVal( 'title' ) === null || $title->getPrefixedDBKey() != $request->getText( 'title' ) )
205 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
206 {
207 if ( $title->getNamespace() == NS_SPECIAL ) {
208 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
209 if ( $name ) {
210 $title = SpecialPage::getTitleFor( $name, $subpage );
211 }
212 }
213 $targetUrl = $title->getFullURL();
214 // Redirect to canonical url, make it a 301 to allow caching
215 if( $targetUrl == $request->getFullRequestURL() ) {
216 $message = "Redirect loop detected!\n\n" .
217 "This means the wiki got confused about what page was " .
218 "requested; this sometimes happens when moving a wiki " .
219 "to a new server or changing the server configuration.\n\n";
220
221 if( $this->getVal( 'UsePathInfo' ) ) {
222 $message .= "The wiki is trying to interpret the page " .
223 "title from the URL path portion (PATH_INFO), which " .
224 "sometimes fails depending on the web server. Try " .
225 "setting \"\$wgUsePathInfo = false;\" in your " .
226 "LocalSettings.php, or check that \$wgArticlePath " .
227 "is correct.";
228 } else {
229 $message .= "Your web server was detected as possibly not " .
230 "supporting URL path components (PATH_INFO) correctly; " .
231 "check your LocalSettings.php for a customized " .
232 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
233 "to true.";
234 }
235 wfHttpError( 500, "Internal error", $message );
236 wfProfileOut( __METHOD__ );
237 return false;
238 } else {
239 $output->setSquidMaxage( 1200 );
240 $output->redirect( $targetUrl, '301' );
241 }
242 // Special pages
243 } else if( NS_SPECIAL == $title->getNamespace() ) {
244 /* actions that need to be made when we have a special pages */
245 SpecialPage::executePath( $title );
246 } else {
247 /* No match to special cases */
248 wfProfileOut( __METHOD__ );
249 return false;
250 }
251 /* Did match a special case */
252 wfProfileOut( __METHOD__ );
253 return true;
254 }
255
256 /**
257 * Create an Article object of the appropriate class for the given page.
258 *
259 * @param $title Title
260 * @return Article object
261 */
262 static function articleFromTitle( &$title ) {
263 if( NS_MEDIA == $title->getNamespace() ) {
264 // FIXME: where should this go?
265 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
266 }
267
268 $article = null;
269 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
270 if( $article ) {
271 return $article;
272 }
273
274 switch( $title->getNamespace() ) {
275 case NS_FILE:
276 return new ImagePage( $title );
277 case NS_CATEGORY:
278 return new CategoryPage( $title );
279 default:
280 return new Article( $title );
281 }
282 }
283
284 /**
285 * Returns the action that will be executed, not necesserly the one passed
286 * passed through the "action" parameter. Actions disabled in
287 * $wgDisabledActions will be replaced by "nosuchaction"
288 *
289 * @param $request WebRequest
290 * @return String: action
291 */
292 public function getAction( WebRequest $request ) {
293 global $wgDisabledActions;
294
295 $action = $request->getVal( 'action', 'view' );
296
297 // Check for disabled actions
298 if( in_array( $action, $wgDisabledActions ) ) {
299 return 'nosuchaction';
300 }
301
302 // Workaround for bug #20966: inability of IE to provide an action dependent
303 // on which submit button is clicked.
304 if ( $action === 'historysubmit' ) {
305 if ( $request->getBool( 'revisiondelete' ) ) {
306 return 'revisiondelete';
307 } elseif ( $request->getBool( 'revisionmove' ) ) {
308 return 'revisionmove';
309 } else {
310 return 'view';
311 }
312 } elseif ( $action == 'editredlink' ) {
313 return 'edit';
314 }
315
316 return $action;
317 }
318
319 /**
320 * Initialize the object to be known as $wgArticle for "standard" actions
321 * Create an Article object for the page, following redirects if needed.
322 *
323 * @param $title Title ($wgTitle)
324 * @param $output OutputPage ($wgOut)
325 * @param $request WebRequest ($wgRequest)
326 * @return mixed an Article, or a string to redirect to another URL
327 */
328 function initializeArticle( &$title, &$output, $request ) {
329 wfProfileIn( __METHOD__ );
330
331 $action = $request->getVal( 'action', 'view' );
332 $article = self::articleFromTitle( $title );
333 // NS_MEDIAWIKI has no redirects.
334 // It is also used for CSS/JS, so performance matters here...
335 if( $title->getNamespace() == NS_MEDIAWIKI ) {
336 wfProfileOut( __METHOD__ );
337 return $article;
338 }
339 // Namespace might change when using redirects
340 // Check for redirects ...
341 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
342 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
343 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
344 !$request->getVal( 'diff' ) && // ... and not when showing diff
345 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
346 // ... and the article is not a non-redirect image page with associated file
347 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
348 {
349 // Give extensions a change to ignore/handle redirects as needed
350 $ignoreRedirect = $target = false;
351
352 $dbr = wfGetDB( DB_SLAVE );
353 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
354
355 wfRunHooks( 'InitializeArticleMaybeRedirect',
356 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
357
358 // Follow redirects only for... redirects.
359 // If $target is set, then a hook wanted to redirect.
360 if( !$ignoreRedirect && ($target || $article->isRedirect()) ) {
361 // Is the target already set by an extension?
362 $target = $target ? $target : $article->followRedirect();
363 if( is_string( $target ) ) {
364 if( !$this->getVal( 'DisableHardRedirects' ) ) {
365 // we'll need to redirect
366 wfProfileOut( __METHOD__ );
367 return $target;
368 }
369 }
370 if( is_object($target) ) {
371 // Rewrite environment to redirected article
372 $rarticle = self::articleFromTitle( $target );
373 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
374 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
375 $rarticle->setRedirectedFrom( $title );
376 $article = $rarticle;
377 $title = $target;
378 $output->setTitle( $title );
379 }
380 }
381 } else {
382 $title = $article->getTitle();
383 }
384 }
385 wfProfileOut( __METHOD__ );
386 return $article;
387 }
388
389 /**
390 * Cleaning up request by doing:
391 ** deferred updates, DB transaction, and the output
392 *
393 * @param $output OutputPage
394 */
395 function finalCleanup( &$output ) {
396 wfProfileIn( __METHOD__ );
397 // Now commit any transactions, so that unreported errors after
398 // output() don't roll back the whole DB transaction
399 $factory = wfGetLBFactory();
400 $factory->commitMasterChanges();
401 // Output everything!
402 $output->output();
403 // Do any deferred jobs
404 wfDoUpdates( 'commit' );
405 // Close the session so that jobs don't access the current session
406 session_write_close();
407 $this->doJobs();
408 wfProfileOut( __METHOD__ );
409 }
410
411 /**
412 * Do a job from the job queue
413 */
414 function doJobs() {
415 global $wgJobRunRate;
416
417 if( $wgJobRunRate <= 0 || wfReadOnly() ) {
418 return;
419 }
420 if( $wgJobRunRate < 1 ) {
421 $max = mt_getrandmax();
422 if( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
423 return;
424 }
425 $n = 1;
426 } else {
427 $n = intval( $wgJobRunRate );
428 }
429
430 while ( $n-- && false != ( $job = Job::pop() ) ) {
431 $output = $job->toString() . "\n";
432 $t = -wfTime();
433 $success = $job->run();
434 $t += wfTime();
435 $t = round( $t*1000 );
436 if( !$success ) {
437 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
438 } else {
439 $output .= "Success, Time: $t ms\n";
440 }
441 wfDebugLog( 'jobqueue', $output );
442 }
443 }
444
445 /**
446 * Ends this task peacefully
447 */
448 function restInPeace() {
449 MessageCache::logMessages();
450 wfLogProfilingData();
451 // Commit and close up!
452 $factory = wfGetLBFactory();
453 $factory->commitMasterChanges();
454 $factory->shutdown();
455 wfDebug( "Request ended normally\n" );
456 }
457
458 /**
459 * Perform one of the "standard" actions
460 *
461 * @param $output OutputPage
462 * @param $article Article
463 * @param $title Title
464 * @param $user User
465 * @param $request WebRequest
466 */
467 function performAction( &$output, &$article, &$title, &$user, &$request ) {
468 wfProfileIn( __METHOD__ );
469
470 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
471 wfProfileOut( __METHOD__ );
472 return;
473 }
474
475 $action = $this->getAction( $request );
476
477 switch( $action ) {
478 case 'view':
479 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
480 $article->view();
481 break;
482 case 'raw': // includes JS/CSS
483 wfProfileIn( __METHOD__.'-raw' );
484 $raw = new RawPage( $article );
485 $raw->view();
486 wfProfileOut( __METHOD__.'-raw' );
487 break;
488 case 'watch':
489 case 'unwatch':
490 case 'delete':
491 case 'revert':
492 case 'rollback':
493 case 'protect':
494 case 'unprotect':
495 case 'info':
496 case 'markpatrolled':
497 case 'render':
498 case 'deletetrackback':
499 case 'purge':
500 $article->$action();
501 break;
502 case 'print':
503 $article->view();
504 break;
505 case 'dublincore':
506 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
507 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
508 } else {
509 $rdf = new DublinCoreRdf( $article );
510 $rdf->show();
511 }
512 break;
513 case 'creativecommons':
514 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
515 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
516 } else {
517 $rdf = new CreativeCommonsRdf( $article );
518 $rdf->show();
519 }
520 break;
521 case 'credits':
522 Credits::showPage( $article );
523 break;
524 case 'submit':
525 if( session_id() == '' ) {
526 /* Send a cookie so anons get talk message notifications */
527 wfSetupSession();
528 }
529 /* Continue... */
530 case 'edit':
531 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
532 $internal = $request->getVal( 'internaledit' );
533 $external = $request->getVal( 'externaledit' );
534 $section = $request->getVal( 'section' );
535 $oldid = $request->getVal( 'oldid' );
536 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
537 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
538 $editor = new EditPage( $article );
539 $editor->submit();
540 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
541 $mode = $request->getVal( 'mode' );
542 $extedit = new ExternalEdit( $article, $mode );
543 $extedit->edit();
544 }
545 }
546 break;
547 case 'history':
548 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
549 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
550 }
551 $history = new HistoryPage( $article );
552 $history->history();
553 break;
554 case 'revisiondelete':
555 // For show/hide submission from history page
556 $special = SpecialPage::getPage( 'Revisiondelete' );
557 $special->execute( '' );
558 break;
559 case 'revisionmove':
560 // For revision move submission from history page
561 $special = SpecialPage::getPage( 'RevisionMove' );
562 $special->execute( '' );
563 break;
564 default:
565 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
566 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
567 }
568 }
569 wfProfileOut( __METHOD__ );
570
571 }
572
573 }