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