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