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