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