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