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