Warn that SpecialPage::execute() will be made abstract at some point in the future...
[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 }
144 // For non-special titles, check for implicit titles
145 if ( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
146 // We can have urls with just ?diff=,?oldid= or even just ?diff=
147 $oldid = $this->context->request->getInt( 'oldid' );
148 $oldid = $oldid ? $oldid : $this->context->request->getInt( 'diff' );
149 // Allow oldid to override a changed or missing title
150 if ( $oldid ) {
151 $rev = Revision::newFromId( $oldid );
152 $ret = $rev ? $rev->getTitle() : $ret;
153 }
154 }
155
156 if( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ){
157 $ret = new BadTitle;
158 }
159 return $ret;
160 }
161
162 /**
163 * Get the Title object that we'll be acting on, as specified in the WebRequest
164 * @return Title
165 */
166 public function getTitle(){
167 if( $this->context->title === null ){
168 $this->context->title = $this->parseTitle();
169 }
170 return $this->context->title;
171 }
172
173 /**
174 * Initialize some special cases:
175 * - bad titles
176 * - local interwiki redirects
177 * - redirect loop
178 * - special pages
179 *
180 * @return bool true if the request is already executed
181 */
182 private function handleSpecialCases() {
183 wfProfileIn( __METHOD__ );
184
185 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
186 if ( $this->context->title instanceof BadTitle ) {
187 // Die now before we mess up $wgArticle and the skin stops working
188 throw new ErrorPageError( 'badtitle', 'badtitletext' );
189
190 // Interwiki redirects
191 } else if ( $this->context->title->getInterwiki() != '' ) {
192 $rdfrom = $this->context->request->getVal( 'rdfrom' );
193 if ( $rdfrom ) {
194 $url = $this->context->title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
195 } else {
196 $query = $this->context->request->getValues();
197 unset( $query['title'] );
198 $url = $this->context->title->getFullURL( $query );
199 }
200 // Check for a redirect loop
201 if ( !preg_match( '/^' . preg_quote( $this->getVal( 'Server' ), '/' ) . '/', $url ) && $this->context->title->isLocal() ) {
202 // 301 so google et al report the target as the actual url.
203 $this->context->output->redirect( $url, 301 );
204 } else {
205 $this->context->title = new BadTitle;
206 wfProfileOut( __METHOD__ );
207 throw new ErrorPageError( 'badtitle', 'badtitletext' );
208 }
209 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
210 } else if ( $this->context->request->getVal( 'action', 'view' ) == 'view' && !$this->context->request->wasPosted()
211 && ( $this->context->request->getVal( 'title' ) === null || $this->context->title->getPrefixedDBKey() != $this->context->request->getVal( 'title' ) )
212 && !count( array_diff( array_keys( $this->context->request->getValues() ), array( 'action', 'title' ) ) ) )
213 {
214 if ( $this->context->title->getNamespace() == NS_SPECIAL ) {
215 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $this->context->title->getDBkey() );
216 if ( $name ) {
217 $this->context->title = SpecialPage::getTitleFor( $name, $subpage );
218 }
219 }
220 $targetUrl = $this->context->title->getFullURL();
221 // Redirect to canonical url, make it a 301 to allow caching
222 if ( $targetUrl == $this->context->request->getFullRequestURL() ) {
223 $message = "Redirect loop detected!\n\n" .
224 "This means the wiki got confused about what page was " .
225 "requested; this sometimes happens when moving a wiki " .
226 "to a new server or changing the server configuration.\n\n";
227
228 if ( $this->getVal( 'UsePathInfo' ) ) {
229 $message .= "The wiki is trying to interpret the page " .
230 "title from the URL path portion (PATH_INFO), which " .
231 "sometimes fails depending on the web server. Try " .
232 "setting \"\$wgUsePathInfo = false;\" in your " .
233 "LocalSettings.php, or check that \$wgArticlePath " .
234 "is correct.";
235 } else {
236 $message .= "Your web server was detected as possibly not " .
237 "supporting URL path components (PATH_INFO) correctly; " .
238 "check your LocalSettings.php for a customized " .
239 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
240 "to true.";
241 }
242 wfHttpError( 500, "Internal error", $message );
243 wfProfileOut( __METHOD__ );
244 return false;
245 } else {
246 $this->context->output->setSquidMaxage( 1200 );
247 $this->context->output->redirect( $targetUrl, '301' );
248 }
249 // Special pages
250 } else if ( NS_SPECIAL == $this->context->title->getNamespace() ) {
251 // actions that need to be made when we have a special pages
252 SpecialPageFactory::executePath( $this->context->title, $this->context );
253 } else {
254 // No match to special cases
255 wfProfileOut( __METHOD__ );
256 return false;
257 }
258 // Did match a special case
259 wfProfileOut( __METHOD__ );
260 return true;
261 }
262
263 /**
264 * Create an Article object of the appropriate class for the given page.
265 *
266 * @param $title Title
267 * @return Article object
268 */
269 public static function articleFromTitle( &$title, RequestContext &$context ) {
270 if ( NS_MEDIA == $title->getNamespace() ) {
271 // FIXME: where should this go?
272 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
273 }
274
275 $article = null;
276 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
277 if ( $article ) {
278 return $article;
279 }
280
281 switch( $title->getNamespace() ) {
282 case NS_FILE:
283 $page = new ImagePage( $title );
284 break;
285 case NS_CATEGORY:
286 $page = new CategoryPage( $title );
287 break;
288 default:
289 $page = new Article( $title );
290 }
291 $page->setContext( $context );
292 return $page;
293 }
294
295 /**
296 * Returns the action that will be executed, not necesserly the one passed
297 * passed through the "action" parameter. Actions disabled in
298 * $wgDisabledActions will be replaced by "nosuchaction"
299 *
300 * @return String: action
301 */
302 public function getAction() {
303 global $wgDisabledActions;
304
305 $action = $this->context->request->getVal( 'action', 'view' );
306
307 // Check for disabled actions
308 if ( in_array( $action, $wgDisabledActions ) ) {
309 return 'nosuchaction';
310 }
311
312 // Workaround for bug #20966: inability of IE to provide an action dependent
313 // on which submit button is clicked.
314 if ( $action === 'historysubmit' ) {
315 if ( $this->context->request->getBool( 'revisiondelete' ) ) {
316 return 'revisiondelete';
317 } elseif ( $this->context->request->getBool( 'revisionmove' ) ) {
318 return 'revisionmove';
319 } else {
320 return 'view';
321 }
322 } elseif ( $action == 'editredlink' ) {
323 return 'edit';
324 }
325
326 return $action;
327 }
328
329 /**
330 * Initialize the object to be known as $wgArticle for "standard" actions
331 * Create an Article object for the page, following redirects if needed.
332 *
333 * @return mixed an Article, or a string to redirect to another URL
334 */
335 private function initializeArticle() {
336 wfProfileIn( __METHOD__ );
337
338 $action = $this->context->request->getVal( 'action', 'view' );
339 $article = self::articleFromTitle( $this->context->title, $this->context );
340 // NS_MEDIAWIKI has no redirects.
341 // It is also used for CSS/JS, so performance matters here...
342 if ( $this->context->title->getNamespace() == NS_MEDIAWIKI ) {
343 wfProfileOut( __METHOD__ );
344 return $article;
345 }
346 // Namespace might change when using redirects
347 // Check for redirects ...
348 $file = ( $this->context->title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
349 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
350 && !$this->context->request->getVal( 'oldid' ) && // ... and are not old revisions
351 !$this->context->request->getVal( 'diff' ) && // ... and not when showing diff
352 $this->context->request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
353 // ... and the article is not a non-redirect image page with associated file
354 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
355 {
356 // Give extensions a change to ignore/handle redirects as needed
357 $ignoreRedirect = $target = false;
358
359 wfRunHooks( 'InitializeArticleMaybeRedirect',
360 array( &$this->context->title, &$this->context->request, &$ignoreRedirect, &$target, &$article ) );
361
362 // Follow redirects only for... redirects.
363 // If $target is set, then a hook wanted to redirect.
364 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
365 // Is the target already set by an extension?
366 $target = $target ? $target : $article->followRedirect();
367 if ( is_string( $target ) ) {
368 if ( !$this->getVal( 'DisableHardRedirects' ) ) {
369 // we'll need to redirect
370 wfProfileOut( __METHOD__ );
371 return $target;
372 }
373 }
374 if ( is_object( $target ) ) {
375 // Rewrite environment to redirected article
376 $rarticle = self::articleFromTitle( $target, $this->context );
377 $rarticle->loadPageData();
378 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
379 $rarticle->setRedirectedFrom( $this->context->title );
380 $article = $rarticle;
381 $this->context->title = $target;
382 }
383 }
384 } else {
385 $this->context->title = $article->getTitle();
386 }
387 }
388 wfProfileOut( __METHOD__ );
389 return $article;
390 }
391
392 /**
393 * Cleaning up request by doing deferred updates, DB transaction, and the output
394 */
395 public function finalCleanup() {
396 wfProfileIn( __METHOD__ );
397 // Now commit any transactions, so that unreported errors after
398 // output() don't roll back the whole DB transaction
399 $factory = wfGetLBFactory();
400 $factory->commitMasterChanges();
401 // Output everything!
402 $this->context->output->output();
403 // Do any deferred jobs
404 wfDoUpdates( 'commit' );
405 // Close the session so that jobs don't access the current session
406 session_write_close();
407 $this->doJobs();
408 wfProfileOut( __METHOD__ );
409 }
410
411 /**
412 * Do a job from the job queue
413 */
414 private function doJobs() {
415 global $wgJobRunRate;
416
417 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
418 return;
419 }
420 if ( $wgJobRunRate < 1 ) {
421 $max = mt_getrandmax();
422 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
423 return;
424 }
425 $n = 1;
426 } else {
427 $n = intval( $wgJobRunRate );
428 }
429
430 while ( $n-- && false != ( $job = Job::pop() ) ) {
431 $output = $job->toString() . "\n";
432 $t = -wfTime();
433 $success = $job->run();
434 $t += wfTime();
435 $t = round( $t * 1000 );
436 if ( !$success ) {
437 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
438 } else {
439 $output .= "Success, Time: $t ms\n";
440 }
441 wfDebugLog( 'jobqueue', $output );
442 }
443 }
444
445 /**
446 * Ends this task peacefully
447 */
448 public function restInPeace() {
449 MessageCache::logMessages();
450 wfLogProfilingData();
451 // Commit and close up!
452 $factory = wfGetLBFactory();
453 $factory->commitMasterChanges();
454 $factory->shutdown();
455 wfDebug( "Request ended normally\n" );
456 }
457
458 /**
459 * Perform one of the "standard" actions
460 *
461 * @param $article Article
462 */
463 private function performAction( &$article ) {
464 wfProfileIn( __METHOD__ );
465
466 if ( !wfRunHooks( 'MediaWikiPerformAction', array(
467 $this->context->output, $article, $this->context->title,
468 $this->context->user, $this->context->request, $this ) ) )
469 {
470 wfProfileOut( __METHOD__ );
471 return;
472 }
473
474 $act = $this->getAction();
475
476 $action = Action::factory( $this->getAction(), $article );
477 if( $action instanceof Action ){
478 $action->show();
479 wfProfileOut( __METHOD__ );
480 return;
481 }
482
483 switch( $act ) {
484 case 'view':
485 $this->context->output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
486 $article->view();
487 break;
488 case 'raw': // includes JS/CSS
489 wfProfileIn( __METHOD__ . '-raw' );
490 $raw = new RawPage( $article );
491 $raw->view();
492 wfProfileOut( __METHOD__ . '-raw' );
493 break;
494 case 'delete':
495 case 'revert':
496 case 'rollback':
497 case 'protect':
498 case 'unprotect':
499 case 'info':
500 case 'markpatrolled':
501 case 'render':
502 case 'deletetrackback':
503 $article->$act();
504 break;
505 case 'print':
506 $article->view();
507 break;
508 case 'dublincore':
509 if ( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
510 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
511 } else {
512 $rdf = new DublinCoreRdf( $article );
513 $rdf->show();
514 }
515 break;
516 case 'creativecommons':
517 if ( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
518 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
519 } else {
520 $rdf = new CreativeCommonsRdf( $article );
521 $rdf->show();
522 }
523 break;
524 case 'submit':
525 if ( session_id() == '' ) {
526 // Send a cookie so anons get talk message notifications
527 wfSetupSession();
528 }
529 // Continue...
530 case 'edit':
531 if ( wfRunHooks( 'CustomEditor', array( $article, $this->context->user ) ) ) {
532 $internal = $this->context->request->getVal( 'internaledit' );
533 $external = $this->context->request->getVal( 'externaledit' );
534 $section = $this->context->request->getVal( 'section' );
535 $oldid = $this->context->request->getVal( 'oldid' );
536 if ( !$this->getVal( 'UseExternalEditor' ) || $act == 'submit' || $internal ||
537 $section || $oldid || ( !$this->context->user->getOption( 'externaleditor' ) && !$external ) ) {
538 $editor = new EditPage( $article );
539 $editor->submit();
540 } elseif ( $this->getVal( 'UseExternalEditor' ) && ( $external || $this->context->user->getOption( 'externaleditor' ) ) ) {
541 $mode = $this->context->request->getVal( 'mode' );
542 $extedit = new ExternalEdit( $article, $mode );
543 $extedit->edit();
544 }
545 }
546 break;
547 case 'history':
548 if ( $this->context->request->getFullRequestURL() == $this->context->title->getInternalURL( 'action=history' ) ) {
549 $this->context->output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
550 }
551 $history = new HistoryPage( $article );
552 $history->history();
553 break;
554 case 'revisiondelete':
555 // For show/hide submission from history page
556 $special = SpecialPageFactory::getPage( 'Revisiondelete' );
557 $special->execute( '' );
558 break;
559 default:
560 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
561 $this->context->output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
562 }
563 }
564 wfProfileOut( __METHOD__ );
565 }
566 }