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