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