Cleanup in Wiki.php and index.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 * @internal documentation reviewed 15 Mar 2010
6 */
7 class MediaWiki {
8
9 /**
10 * Array of options which may or may not be used
11 * FIXME: this seems currently to be a messy halfway-house between globals
12 * and a config object. Pick one and run with it
13 * @var array
14 */
15 private $params = array();
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 public 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 public 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 public function performRequestForTitle( &$title, &$article, &$output, &$user, $request ) {
56 wfProfileIn( __METHOD__ );
57
58 $output->setTitle( $title );
59 if ( $request->getVal( 'printable' ) === 'yes' ) {
60 $output->setPrintable();
61 }
62
63 wfRunHooks( 'BeforeInitialize', array( &$title, &$article, &$output, &$user, $request, $this ) );
64
65 // If the user is not logged in, the Namespace:title of the article must be in
66 // the Read array in order for the user to see it. (We have to check here to
67 // catch special pages etc. We check again in Article::view())
68 if ( !is_null( $title ) && !$title->userCanRead() ) {
69 $output->loginToUse();
70 $this->finalCleanup( $output );
71 $output->disable();
72 wfProfileOut( __METHOD__ );
73 return false;
74 }
75
76 // Call handleSpecialCases() to deal with all special requests...
77 if ( !$this->handleSpecialCases( $title, $output, $request ) ) {
78 // ...otherwise treat it as an article view. The article
79 // may be a redirect to another article or URL.
80 $new_article = $this->initializeArticle( $title, $output, $request );
81 if ( is_object( $new_article ) ) {
82 $article = $new_article;
83 $this->performAction( $output, $article, $title, $user, $request );
84 } elseif ( is_string( $new_article ) ) {
85 $output->redirect( $new_article );
86 } else {
87 wfProfileOut( __METHOD__ );
88 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
89 }
90 }
91 wfProfileOut( __METHOD__ );
92 }
93
94 /**
95 * Checks some initial queries
96 * FIXME: rename to parseTitle() ?
97 *
98 * @param $request WebRequest
99 * @return Title object to be $wgTitle
100 */
101 /* private */ function checkInitialQueries( WebRequest $request ) {
102 global $wgContLang;
103
104 $curid = $request->getInt( 'curid' );
105 $title = $request->getVal( 'title' );
106
107 if ( $request->getCheck( 'search' ) ) {
108 // Compatibility with old search URLs which didn't use Special:Search
109 // Just check for presence here, so blank requests still
110 // show the search page when using ugly URLs (bug 8054).
111 $ret = SpecialPage::getTitleFor( 'Search' );
112 } elseif ( $curid ) {
113 // URLs like this are generated by RC, because rc_title isn't always accurate
114 $ret = Title::newFromID( $curid );
115 } elseif ( $title == '' && $this->getAction( $request ) != 'delete' ) {
116 $ret = Title::newMainPage();
117 } else {
118 $ret = Title::newFromURL( $title );
119 // check variant links so that interwiki links don't have to worry
120 // about the possible different language variants
121 if ( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 )
122 $wgContLang->findVariantLink( $title, $ret );
123 }
124 // For non-special titles, check for implicit titles
125 if ( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
126 // We can have urls with just ?diff=,?oldid= or even just ?diff=
127 $oldid = $request->getInt( 'oldid' );
128 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
129 // Allow oldid to override a changed or missing title
130 if ( $oldid ) {
131 $rev = Revision::newFromId( $oldid );
132 $ret = $rev ? $rev->getTitle() : $ret;
133 }
134 }
135 return $ret;
136 }
137
138 /**
139 * Initialize some special cases:
140 * - bad titles
141 * - local interwiki redirects
142 * - redirect loop
143 * - special pages
144 *
145 * @param $title Title
146 * @param $output OutputPage
147 * @param $request WebRequest
148 * @return bool true if the request is already executed
149 */
150 private function handleSpecialCases( &$title, &$output, $request ) {
151 wfProfileIn( __METHOD__ );
152
153 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
154 if ( is_null( $title ) || ( ( $title->getDBkey() == '' ) && ( $title->getInterwiki() == '' ) ) ) {
155 $title = SpecialPage::getTitleFor( 'Badtitle' );
156 $output->setTitle( $title ); // bug 21456
157 // Die now before we mess up $wgArticle and the skin stops working
158 throw new ErrorPageError( 'badtitle', 'badtitletext' );
159
160 // Interwiki redirects
161 } else if ( $title->getInterwiki() != '' ) {
162 $rdfrom = $request->getVal( 'rdfrom' );
163 if ( $rdfrom ) {
164 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
165 } else {
166 $query = $request->getValues();
167 unset( $query['title'] );
168 $url = $title->getFullURL( $query );
169 }
170 /* Check for a redirect loop */
171 if ( !preg_match( '/^' . preg_quote( $this->getVal( 'Server' ), '/' ) . '/', $url ) && $title->isLocal() ) {
172 // 301 so google et al report the target as the actual url.
173 $output->redirect( $url, 301 );
174 } else {
175 $title = SpecialPage::getTitleFor( 'Badtitle' );
176 $output->setTitle( $title ); // bug 21456
177 wfProfileOut( __METHOD__ );
178 throw new ErrorPageError( 'badtitle', 'badtitletext' );
179 }
180 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
181 } else if ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
182 && ( $request->getVal( 'title' ) === null || $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
183 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
184 {
185 if ( $title->getNamespace() == NS_SPECIAL ) {
186 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
187 if ( $name ) {
188 $title = SpecialPage::getTitleFor( $name, $subpage );
189 }
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 wfProfileOut( __METHOD__ );
215 return false;
216 } else {
217 $output->setSquidMaxage( 1200 );
218 $output->redirect( $targetUrl, '301' );
219 }
220 // Special pages
221 } else if ( NS_SPECIAL == $title->getNamespace() ) {
222 /* actions that need to be made when we have a special pages */
223 SpecialPage::executePath( $title );
224 } else {
225 /* No match to special cases */
226 wfProfileOut( __METHOD__ );
227 return false;
228 }
229 /* Did match a special case */
230 wfProfileOut( __METHOD__ );
231 return true;
232 }
233
234 /**
235 * Create an Article object of the appropriate class for the given page.
236 *
237 * @param $title Title
238 * @return Article object
239 */
240 public static function articleFromTitle( &$title ) {
241 if ( NS_MEDIA == $title->getNamespace() ) {
242 // FIXME: where should this go?
243 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
244 }
245
246 $article = null;
247 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
248 if ( $article ) {
249 return $article;
250 }
251
252 switch( $title->getNamespace() ) {
253 case NS_FILE:
254 return new ImagePage( $title );
255 case NS_CATEGORY:
256 return new CategoryPage( $title );
257 default:
258 return new Article( $title );
259 }
260 }
261
262 /**
263 * Returns the action that will be executed, not necesserly the one passed
264 * passed through the "action" parameter. Actions disabled in
265 * $wgDisabledActions will be replaced by "nosuchaction"
266 *
267 * @param $request WebRequest
268 * @return String: action
269 */
270 public function getAction( WebRequest $request ) {
271 global $wgDisabledActions;
272
273 $action = $request->getVal( 'action', 'view' );
274
275 // Check for disabled actions
276 if ( in_array( $action, $wgDisabledActions ) ) {
277 return 'nosuchaction';
278 }
279
280 // Workaround for bug #20966: inability of IE to provide an action dependent
281 // on which submit button is clicked.
282 if ( $action === 'historysubmit' ) {
283 if ( $request->getBool( 'revisiondelete' ) ) {
284 return 'revisiondelete';
285 } elseif ( $request->getBool( 'revisionmove' ) ) {
286 return 'revisionmove';
287 } else {
288 return 'view';
289 }
290 } elseif ( $action == 'editredlink' ) {
291 return 'edit';
292 }
293
294 return $action;
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 private function initializeArticle( &$title, &$output, $request ) {
307 wfProfileIn( __METHOD__ );
308
309 $action = $request->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( 'diff' ) && // ... and not when showing diff
323 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
324 // ... and the article is not a non-redirect image page with associated file
325 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
326 {
327 // Give extensions a change to ignore/handle redirects as needed
328 $ignoreRedirect = $target = false;
329
330 wfRunHooks( 'InitializeArticleMaybeRedirect',
331 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
332
333 // Follow redirects only for... redirects.
334 // If $target is set, then a hook wanted to redirect.
335 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
336 // Is the target already set by an extension?
337 $target = $target ? $target : $article->followRedirect();
338 if ( is_string( $target ) ) {
339 if ( !$this->getVal( 'DisableHardRedirects' ) ) {
340 // we'll need to redirect
341 wfProfileOut( __METHOD__ );
342 return $target;
343 }
344 }
345 if ( is_object( $target ) ) {
346 // Rewrite environment to redirected article
347 $rarticle = self::articleFromTitle( $target );
348 $rarticle->loadPageData();
349 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
350 $rarticle->setRedirectedFrom( $title );
351 $article = $rarticle;
352 $title = $target;
353 $output->setTitle( $title );
354 }
355 }
356 } else {
357 $title = $article->getTitle();
358 }
359 }
360 wfProfileOut( __METHOD__ );
361 return $article;
362 }
363
364 /**
365 * Cleaning up request by doing deferred updates, DB transaction, and the output
366 *
367 * @param $output OutputPage
368 */
369 public function finalCleanup( &$output ) {
370 wfProfileIn( __METHOD__ );
371 // Now commit any transactions, so that unreported errors after
372 // output() don't roll back the whole DB transaction
373 $factory = wfGetLBFactory();
374 $factory->commitMasterChanges();
375 // Output everything!
376 $output->output();
377 // Do any deferred jobs
378 wfDoUpdates( 'commit' );
379 // Close the session so that jobs don't access the current session
380 session_write_close();
381 $this->doJobs();
382 wfProfileOut( __METHOD__ );
383 }
384
385 /**
386 * Do a job from the job queue
387 */
388 private function doJobs() {
389 global $wgJobRunRate;
390
391 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
392 return;
393 }
394 if ( $wgJobRunRate < 1 ) {
395 $max = mt_getrandmax();
396 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
397 return;
398 }
399 $n = 1;
400 } else {
401 $n = intval( $wgJobRunRate );
402 }
403
404 while ( $n-- && false != ( $job = Job::pop() ) ) {
405 $output = $job->toString() . "\n";
406 $t = -wfTime();
407 $success = $job->run();
408 $t += wfTime();
409 $t = round( $t * 1000 );
410 if ( !$success ) {
411 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
412 } else {
413 $output .= "Success, Time: $t ms\n";
414 }
415 wfDebugLog( 'jobqueue', $output );
416 }
417 }
418
419 /**
420 * Ends this task peacefully
421 */
422 public function restInPeace() {
423 MessageCache::logMessages();
424 wfLogProfilingData();
425 // Commit and close up!
426 $factory = wfGetLBFactory();
427 $factory->commitMasterChanges();
428 $factory->shutdown();
429 wfDebug( "Request ended normally\n" );
430 }
431
432 /**
433 * Perform one of the "standard" actions
434 *
435 * @param $output OutputPage
436 * @param $article Article
437 * @param $title Title
438 * @param $user User
439 * @param $request WebRequest
440 */
441 private function performAction( &$output, &$article, &$title, &$user, &$request ) {
442 wfProfileIn( __METHOD__ );
443
444 if ( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
445 wfProfileOut( __METHOD__ );
446 return;
447 }
448
449 $action = $this->getAction( $request );
450
451 switch( $action ) {
452 case 'view':
453 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
454 $article->view();
455 break;
456 case 'raw': // includes JS/CSS
457 wfProfileIn( __METHOD__ . '-raw' );
458 $raw = new RawPage( $article );
459 $raw->view();
460 wfProfileOut( __METHOD__ . '-raw' );
461 break;
462 case 'watch':
463 case 'unwatch':
464 case 'delete':
465 case 'revert':
466 case 'rollback':
467 case 'protect':
468 case 'unprotect':
469 case 'info':
470 case 'markpatrolled':
471 case 'render':
472 case 'deletetrackback':
473 case 'purge':
474 $article->$action();
475 break;
476 case 'print':
477 $article->view();
478 break;
479 case 'dublincore':
480 if ( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
481 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
482 } else {
483 $rdf = new DublinCoreRdf( $article );
484 $rdf->show();
485 }
486 break;
487 case 'creativecommons':
488 if ( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
489 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
490 } else {
491 $rdf = new CreativeCommonsRdf( $article );
492 $rdf->show();
493 }
494 break;
495 case 'credits':
496 Credits::showPage( $article );
497 break;
498 case 'submit':
499 if ( session_id() == '' ) {
500 /* Send a cookie so anons get talk message notifications */
501 wfSetupSession();
502 }
503 /* Continue... */
504 case 'edit':
505 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
506 $internal = $request->getVal( 'internaledit' );
507 $external = $request->getVal( 'externaledit' );
508 $section = $request->getVal( 'section' );
509 $oldid = $request->getVal( 'oldid' );
510 if ( !$this->getVal( 'UseExternalEditor' ) || $action == 'submit' || $internal ||
511 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
512 $editor = new EditPage( $article );
513 $editor->submit();
514 } elseif ( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
515 $mode = $request->getVal( 'mode' );
516 $extedit = new ExternalEdit( $article, $mode );
517 $extedit->edit();
518 }
519 }
520 break;
521 case 'history':
522 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
523 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
524 }
525 $history = new HistoryPage( $article );
526 $history->history();
527 break;
528 case 'revisiondelete':
529 // For show/hide submission from history page
530 $special = SpecialPage::getPage( 'Revisiondelete' );
531 $special->execute( '' );
532 break;
533 case 'revisionmove':
534 // For revision move submission from history page
535 $special = SpecialPage::getPage( 'RevisionMove' );
536 $special->execute( '' );
537 break;
538 default:
539 if ( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
540 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
541 }
542 }
543 wfProfileOut( __METHOD__ );
544 }
545 }