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