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