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