d385f92311b16fed60aee08ded40d3c6060b5528
[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 $url = $title->getFullURL();
192 }
193 /* Check for a redirect loop */
194 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
195 $output->redirect( $url );
196 } else {
197 $title = SpecialPage::getTitleFor( 'Badtitle' );
198 throw new ErrorPageError( 'badtitle', 'badtitletext' );
199 }
200 } else if( $action == 'view' && !$request->wasPosted() &&
201 ( !isset($this->GET['title']) || $title->getPrefixedDBKey() != $this->GET['title'] ) &&
202 !count( array_diff( array_keys( $this->GET ), array( 'action', 'title' ) ) ) )
203 {
204 $targetUrl = $title->getFullURL();
205 // Redirect to canonical url, make it a 301 to allow caching
206 if( $targetUrl == $request->getFullRequestURL() ) {
207 $message = "Redirect loop detected!\n\n" .
208 "This means the wiki got confused about what page was " .
209 "requested; this sometimes happens when moving a wiki " .
210 "to a new server or changing the server configuration.\n\n";
211
212 if( $this->getVal( 'UsePathInfo' ) ) {
213 $message .= "The wiki is trying to interpret the page " .
214 "title from the URL path portion (PATH_INFO), which " .
215 "sometimes fails depending on the web server. Try " .
216 "setting \"\$wgUsePathInfo = false;\" in your " .
217 "LocalSettings.php, or check that \$wgArticlePath " .
218 "is correct.";
219 } else {
220 $message .= "Your web server was detected as possibly not " .
221 "supporting URL path components (PATH_INFO) correctly; " .
222 "check your LocalSettings.php for a customized " .
223 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
224 "to true.";
225 }
226 wfHttpError( 500, "Internal error", $message );
227 return false;
228 } else {
229 $output->setSquidMaxage( 1200 );
230 $output->redirect( $targetUrl, '301' );
231 }
232 } else if( NS_SPECIAL == $title->getNamespace() ) {
233 /* actions that need to be made when we have a special pages */
234 SpecialPage::executePath( $title );
235 } else {
236 /* No match to special cases */
237 wfProfileOut( __METHOD__ );
238 return false;
239 }
240 /* Did match a special case */
241 wfProfileOut( __METHOD__ );
242 return true;
243 }
244
245 /**
246 * Create an Article object of the appropriate class for the given page.
247 *
248 * @param $title Title
249 * @return Article object
250 */
251 static function articleFromTitle( &$title ) {
252 if( NS_MEDIA == $title->getNamespace() ) {
253 // FIXME: where should this go?
254 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
255 }
256
257 $article = null;
258 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
259 if( $article ) {
260 return $article;
261 }
262
263 switch( $title->getNamespace() ) {
264 case NS_FILE:
265 return new ImagePage( $title );
266 case NS_CATEGORY:
267 return new CategoryPage( $title );
268 default:
269 return new Article( $title );
270 }
271 }
272
273 /**
274 * Initialize the object to be known as $wgArticle for "standard" actions
275 * Create an Article object for the page, following redirects if needed.
276 *
277 * @param $title Title ($wgTitle)
278 * @param $output OutputPage ($wgOut)
279 * @param $request WebRequest ($wgRequest)
280 * @return mixed an Article, or a string to redirect to another URL
281 */
282 function initializeArticle( &$title, &$output, $request ) {
283 wfProfileIn( __METHOD__ );
284
285 $action = $this->getVal( 'action', 'view' );
286 $article = self::articleFromTitle( $title );
287 # NS_MEDIAWIKI has no redirects.
288 # It is also used for CSS/JS, so performance matters here...
289 if( $title->getNamespace() == NS_MEDIAWIKI ) {
290 wfProfileOut( __METHOD__ );
291 return $article;
292 }
293 // Namespace might change when using redirects
294 // Check for redirects ...
295 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
296 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
297 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
298 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
299 // ... and the article is not a non-redirect image page with associated file
300 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
301 {
302 # Give extensions a change to ignore/handle redirects as needed
303 $ignoreRedirect = $target = false;
304
305 $dbr = wfGetDB( DB_SLAVE );
306 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
307
308 wfRunHooks( 'InitializeArticleMaybeRedirect',
309 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
310
311 // Follow redirects only for... redirects
312 if( !$ignoreRedirect && $article->isRedirect() ) {
313 # Is the target already set by an extension?
314 $target = $target ? $target : $article->followRedirect();
315 if( is_string( $target ) ) {
316 if( !$this->getVal( 'DisableHardRedirects' ) ) {
317 // we'll need to redirect
318 return $target;
319 }
320 }
321 if( is_object($target) ) {
322 // Rewrite environment to redirected article
323 $rarticle = self::articleFromTitle( $target );
324 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
325 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
326 $rarticle->setRedirectedFrom( $title );
327 $article = $rarticle;
328 $title = $target;
329 $output->setTitle( $title );
330 }
331 }
332 } else {
333 $title = $article->getTitle();
334 }
335 }
336 wfProfileOut( __METHOD__ );
337 return $article;
338 }
339
340 /**
341 * Cleaning up request by doing:
342 ** deferred updates, DB transaction, and the output
343 *
344 * @param $deferredUpdates array of updates to do
345 * @param $output OutputPage
346 */
347 function finalCleanup( &$deferredUpdates, &$output ) {
348 wfProfileIn( __METHOD__ );
349 # Now commit any transactions, so that unreported errors after
350 # output() don't roll back the whole DB transaction
351 $factory = wfGetLBFactory();
352 $factory->commitMasterChanges();
353 # Output everything!
354 $output->output();
355 # Do any deferred jobs
356 $this->doUpdates( $deferredUpdates );
357 $this->doJobs();
358 wfProfileOut( __METHOD__ );
359 }
360
361 /**
362 * Deferred updates aren't really deferred anymore. It's important to report
363 * errors to the user, and that means doing this before OutputPage::output().
364 * Note that for page saves, the client will wait until the script exits
365 * anyway before following the redirect.
366 *
367 * @param $updates array of objects that hold an update to do
368 */
369 function doUpdates( &$updates ) {
370 wfProfileIn( __METHOD__ );
371 /* No need to get master connections in case of empty updates array */
372 if (!$updates) {
373 wfProfileOut( __METHOD__ );
374 return;
375 }
376
377 $dbw = wfGetDB( DB_MASTER );
378 foreach( $updates as $up ) {
379 $up->doUpdate();
380
381 # Commit after every update to prevent lock contention
382 if( $dbw->trxLevel() ) {
383 $dbw->commit();
384 }
385 }
386 wfProfileOut( __METHOD__ );
387 }
388
389 /**
390 * Do a job from the job queue
391 */
392 function doJobs() {
393 $jobRunRate = $this->getVal( 'JobRunRate' );
394
395 if( $jobRunRate <= 0 || wfReadOnly() ) {
396 return;
397 }
398 if( $jobRunRate < 1 ) {
399 $max = mt_getrandmax();
400 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
401 return;
402 }
403 $n = 1;
404 } else {
405 $n = intval( $jobRunRate );
406 }
407
408 while ( $n-- && false != ( $job = Job::pop() ) ) {
409 $output = $job->toString() . "\n";
410 $t = -wfTime();
411 $success = $job->run();
412 $t += wfTime();
413 $t = round( $t*1000 );
414 if( !$success ) {
415 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
416 } else {
417 $output .= "Success, Time: $t ms\n";
418 }
419 wfDebugLog( 'jobqueue', $output );
420 }
421 }
422
423 /**
424 * Ends this task peacefully
425 */
426 function restInPeace() {
427 wfLogProfilingData();
428 # Commit and close up!
429 $factory = wfGetLBFactory();
430 $factory->commitMasterChanges();
431 $factory->shutdown();
432 wfDebug( "Request ended normally\n" );
433 }
434
435 /**
436 * Perform one of the "standard" actions
437 *
438 * @param $output OutputPage
439 * @param $article Article
440 * @param $title Title
441 * @param $user User
442 * @param $request WebRequest
443 */
444 function performAction( &$output, &$article, &$title, &$user, &$request ) {
445 wfProfileIn( __METHOD__ );
446
447 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
448 wfProfileOut( __METHOD__ );
449 return;
450 }
451
452 $action = $this->getVal( 'Action' );
453 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
454 /* No such action; this will switch to the default case */
455 $action = 'nosuchaction';
456 }
457
458 switch( $action ) {
459 case 'view':
460 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
461 $article->view();
462 break;
463 case 'raw': // includes JS/CSS
464 wfProfileIn( __METHOD__.'-raw' );
465 $raw = new RawPage( $article );
466 $raw->view();
467 wfProfileOut( __METHOD__.'-raw' );
468 break;
469 case 'watch':
470 case 'unwatch':
471 case 'delete':
472 case 'revert':
473 case 'rollback':
474 case 'protect':
475 case 'unprotect':
476 case 'info':
477 case 'markpatrolled':
478 case 'render':
479 case 'deletetrackback':
480 case 'purge':
481 $article->$action();
482 break;
483 case 'print':
484 $article->view();
485 break;
486 case 'dublincore':
487 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
488 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
489 } else {
490 $rdf = new DublinCoreRdf( $article );
491 $rdf->show();
492 }
493 break;
494 case 'creativecommons':
495 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
496 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
497 } else {
498 $rdf = new CreativeCommonsRdf( $article );
499 $rdf->show();
500 }
501 break;
502 case 'credits':
503 Credits::showPage( $article );
504 break;
505 case 'submit':
506 if( session_id() == '' ) {
507 /* Send a cookie so anons get talk message notifications */
508 wfSetupSession();
509 }
510 /* Continue... */
511 case 'edit':
512 case 'editredlink':
513 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
514 $internal = $request->getVal( 'internaledit' );
515 $external = $request->getVal( 'externaledit' );
516 $section = $request->getVal( 'section' );
517 $oldid = $request->getVal( 'oldid' );
518 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
519 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
520 $editor = new EditPage( $article );
521 $editor->submit();
522 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
523 $mode = $request->getVal( 'mode' );
524 $extedit = new ExternalEdit( $article, $mode );
525 $extedit->edit();
526 }
527 }
528 break;
529 case 'history':
530 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
531 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
532 }
533 $history = new PageHistory( $article );
534 $history->history();
535 break;
536 default:
537 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
538 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
539 }
540 }
541 wfProfileOut( __METHOD__ );
542
543 }
544
545 }; /* End of class MediaWiki */