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