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