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