96fca6683bf947ddc9dbefee17bad7cc9ef03825
[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 ( $curid = $wgRequest->getInt( 'curid' ) ) {
106 # URLs like this are generated by RC, because rc_title isn't always accurate
107 $ret = Title::newFromID( $curid );
108 } elseif ( '' == $title && 'delete' != $action ) {
109 $ret = Title::newMainPage();
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( is_null($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_FILE, $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_FILE:
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 // Namespace might change when using redirects
279 // Check for redirects ...
280 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
281 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
282 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
283 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
284 // ... and the article is not a non-redirect image page with associated file
285 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
286 {
287 # Give extensions a change to ignore/handle redirects as needed
288 $ignoreRedirect = $target = false;
289
290 $dbr = wfGetDB( DB_SLAVE );
291 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
292
293 wfRunHooks( 'InitializeArticleMaybeRedirect', array( &$title, &$request, &$ignoreRedirect, &$target ) );
294
295 // Follow redirects only for... redirects
296 if( !$ignoreRedirect && $article->isRedirect() ) {
297 # Is the target already set by an extension?
298 $target = $target ? $target : $article->followRedirect();
299 if( is_string( $target ) ) {
300 if( !$this->getVal( 'DisableHardRedirects' ) ) {
301 // we'll need to redirect
302 return $target;
303 }
304 }
305
306 if( is_object( $target ) ) {
307 // Rewrite environment to redirected article
308 $rarticle = self::articleFromTitle( $target );
309 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
310 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
311 $rarticle->setRedirectedFrom( $title );
312 $article = $rarticle;
313 $title = $target;
314 }
315 }
316 } else {
317 $title = $article->getTitle();
318 }
319 }
320 wfProfileOut( __METHOD__ );
321 return $article;
322 }
323
324 /**
325 * Cleaning up by doing deferred updates, calling LBFactory and doing the output
326 *
327 * @param $deferredUpdates array of updates to do
328 * @param $output OutputPage
329 */
330 function finalCleanup ( &$deferredUpdates, &$output ) {
331 wfProfileIn( __METHOD__ );
332 # Now commit any transactions, so that unreported errors after output() don't roll back the whole thing
333 $factory = wfGetLBFactory();
334 $factory->commitMasterChanges();
335 # Output everything!
336 $output->output();
337 # Do any deferred jobs
338 $this->doUpdates( $deferredUpdates );
339 $this->doJobs();
340 # Commit and close up!
341 $factory->shutdown();
342 wfProfileOut( __METHOD__ );
343 }
344
345 /**
346 * Deferred updates aren't really deferred anymore. It's important to report
347 * errors to the user, and that means doing this before OutputPage::output().
348 * Note that for page saves, the client will wait until the script exits
349 * anyway before following the redirect.
350 *
351 * @param $updates array of objects that hold an update to do
352 */
353 function doUpdates( &$updates ) {
354 /* No need to get master connections in case of empty updates array */
355 if( !$updates ) {
356 return;
357 }
358 wfProfileIn( __METHOD__ );
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 'watch':
442 case 'unwatch':
443 case 'delete':
444 case 'revert':
445 case 'rollback':
446 case 'protect':
447 case 'unprotect':
448 case 'info':
449 case 'markpatrolled':
450 case 'render':
451 case 'deletetrackback':
452 case 'purge':
453 $article->$action();
454 break;
455 case 'print':
456 $article->view();
457 break;
458 case 'dublincore':
459 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
460 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
461 } else {
462 $rdf = new DublinCoreRdf( $article );
463 $rdf->show();
464 }
465 break;
466 case 'creativecommons':
467 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
468 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
469 } else {
470 $rdf = new CreativeCommonsRdf( $article );
471 $rdf->show();
472 }
473 break;
474 case 'credits':
475 Credits::showPage( $article );
476 break;
477 case 'submit':
478 if( session_id() == '' ) {
479 /* Send a cookie so anons get talk message notifications */
480 wfSetupSession();
481 }
482 /* Continue... */
483 case 'edit':
484 case 'editredlink':
485 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
486 $internal = $request->getVal( 'internaledit' );
487 $external = $request->getVal( 'externaledit' );
488 $section = $request->getVal( 'section' );
489 $oldid = $request->getVal( 'oldid' );
490 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
491 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
492 $editor = new EditPage( $article );
493 $editor->submit();
494 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
495 $mode = $request->getVal( 'mode' );
496 $extedit = new ExternalEdit( $article, $mode );
497 $extedit->edit();
498 }
499 }
500 break;
501 case 'history':
502 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
503 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
504 }
505 $history = new PageHistory( $article );
506 $history->history();
507 break;
508 case 'raw':
509 $raw = new RawPage( $article );
510 $raw->view();
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 */