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