Followup r91871 per CR. Write back the actually executed action to . Ping r57415
[lhc/web/wiklou.git] / includes / Wiki.php
1 <?php
2 /**
3 * Helper class for the index.php entry point.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * The MediaWiki class is the helper class for the index.php entry point.
25 *
26 * @internal documentation reviewed 15 Mar 2010
27 */
28 class MediaWiki {
29
30 /**
31 * TODO: fold $output, etc, into this
32 * @var RequestContext
33 */
34 private $context;
35
36 public function request( WebRequest $x = null ){
37 $old = $this->context->getRequest();
38 $this->context->setRequest( $x );
39 return $old;
40 }
41
42 public function output( OutputPage $x = null ){
43 $old = $this->context->getOutput();
44 $this->context->setOutput( $x );
45 return $old;
46 }
47
48 public function __construct( RequestContext $context = null ) {
49 if ( !$context ) {
50 $context = RequestContext::getMain();
51 }
52
53 $this->context = $context;
54 $this->context->setTitle( $this->parseTitle() );
55 }
56
57 /**
58 * Parse the request to get the Title object
59 *
60 * @return Title object to be $wgTitle
61 */
62 private function parseTitle() {
63 global $wgContLang;
64
65 $request = $this->context->getRequest();
66 $curid = $request->getInt( 'curid' );
67 $title = $request->getVal( 'title' );
68
69 if ( $request->getCheck( 'search' ) ) {
70 // Compatibility with old search URLs which didn't use Special:Search
71 // Just check for presence here, so blank requests still
72 // show the search page when using ugly URLs (bug 8054).
73 $ret = SpecialPage::getTitleFor( 'Search' );
74 } elseif ( $curid ) {
75 // URLs like this are generated by RC, because rc_title isn't always accurate
76 $ret = Title::newFromID( $curid );
77 } elseif ( $title == '' && $this->getAction() != 'delete' ) {
78 $ret = Title::newMainPage();
79 } else {
80 $ret = Title::newFromURL( $title );
81 // check variant links so that interwiki links don't have to worry
82 // about the possible different language variants
83 if ( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 ){
84 $wgContLang->findVariantLink( $title, $ret );
85 }
86 }
87 // For non-special titles, check for implicit titles
88 if ( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
89 // We can have urls with just ?diff=,?oldid= or even just ?diff=
90 $oldid = $request->getInt( 'oldid' );
91 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
92 // Allow oldid to override a changed or missing title
93 if ( $oldid ) {
94 $rev = Revision::newFromId( $oldid );
95 $ret = $rev ? $rev->getTitle() : $ret;
96 }
97 }
98
99 if( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ){
100 $ret = new BadTitle;
101 }
102 return $ret;
103 }
104
105 /**
106 * Get the Title object that we'll be acting on, as specified in the WebRequest
107 * @return Title
108 */
109 public function getTitle(){
110 if( $this->context->getTitle() === null ){
111 $this->context->setTitle( $this->parseTitle() );
112 }
113 return $this->context->getTitle();
114 }
115
116 /**
117 * Performs the request.
118 * - bad titles
119 * - read restriction
120 * - local interwiki redirects
121 * - redirect loop
122 * - special pages
123 * - normal pages
124 *
125 * @return void
126 */
127 public function performRequest() {
128 global $wgServer, $wgUsePathInfo;
129
130 wfProfileIn( __METHOD__ );
131
132 $request = $this->context->getRequest();
133 $title = $this->context->getTitle();
134 $output = $this->context->getOutput();
135 $user = $this->context->getUser();
136
137 if ( $request->getVal( 'printable' ) === 'yes' ) {
138 $output->setPrintable();
139 }
140
141 $pageView = false; // was an article or special page viewed?
142
143 wfRunHooks( 'BeforeInitialize',
144 array( &$title, null, &$output, &$user, $request, $this ) );
145
146 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
147 if ( $title instanceof BadTitle ) {
148 throw new ErrorPageError( 'badtitle', 'badtitletext' );
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 } elseif ( !$title->userCanRead() ) {
153 $output->loginToUse();
154 // Interwiki redirects
155 } elseif ( $title->getInterwiki() != '' ) {
156 $rdfrom = $request->getVal( 'rdfrom' );
157 if ( $rdfrom ) {
158 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
159 } else {
160 $query = $request->getValues();
161 unset( $query['title'] );
162 $url = $title->getFullURL( $query );
163 }
164 // Check for a redirect loop
165 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url ) && $title->isLocal() ) {
166 // 301 so google et al report the target as the actual url.
167 $output->redirect( $url, 301 );
168 } else {
169 $this->context->setTitle( new BadTitle );
170 wfProfileOut( __METHOD__ );
171 throw new ErrorPageError( 'badtitle', 'badtitletext' );
172 }
173 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
174 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
175 && ( $request->getVal( 'title' ) === null || $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
176 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
177 {
178 if ( $title->getNamespace() == NS_SPECIAL ) {
179 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
180 if ( $name ) {
181 $title = SpecialPage::getTitleFor( $name, $subpage );
182 }
183 }
184 $targetUrl = $title->getFullURL();
185 // Redirect to canonical url, make it a 301 to allow caching
186 if ( $targetUrl == $request->getFullRequestURL() ) {
187 $message = "Redirect loop detected!\n\n" .
188 "This means the wiki got confused about what page was " .
189 "requested; this sometimes happens when moving a wiki " .
190 "to a new server or changing the server configuration.\n\n";
191
192 if ( $wgUsePathInfo ) {
193 $message .= "The wiki is trying to interpret the page " .
194 "title from the URL path portion (PATH_INFO), which " .
195 "sometimes fails depending on the web server. Try " .
196 "setting \"\$wgUsePathInfo = false;\" in your " .
197 "LocalSettings.php, or check that \$wgArticlePath " .
198 "is correct.";
199 } else {
200 $message .= "Your web server was detected as possibly not " .
201 "supporting URL path components (PATH_INFO) correctly; " .
202 "check your LocalSettings.php for a customized " .
203 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
204 "to true.";
205 }
206 wfHttpError( 500, "Internal error", $message );
207 } else {
208 $output->setSquidMaxage( 1200 );
209 $output->redirect( $targetUrl, '301' );
210 }
211 // Special pages
212 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
213 $pageView = true;
214 // Actions that need to be made when we have a special pages
215 SpecialPageFactory::executePath( $title, $this->context );
216 } else {
217 // ...otherwise treat it as an article view. The article
218 // may be a redirect to another article or URL.
219 $article = $this->initializeArticle();
220 if ( is_object( $article ) ) {
221 $pageView = true;
222 /**
223 * $wgArticle is deprecated, do not use it. This will possibly be removed
224 * entirely in 1.20 or 1.21
225 * @deprecated since 1.19
226 */
227 global $wgArticle;
228 $wgArticle = $article;
229
230 $this->performAction( $article );
231 } elseif ( is_string( $article ) ) {
232 $output->redirect( $article );
233 } else {
234 wfProfileOut( __METHOD__ );
235 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
236 }
237 }
238
239 if ( $pageView ) {
240 // Promote user to any groups they meet the criteria for
241 $user->addAutopromoteOnceGroups( 'onView' );
242 }
243
244 wfProfileOut( __METHOD__ );
245 }
246
247 /**
248 * Create an Article object of the appropriate class for the given page.
249 *
250 * @deprecated in 1.19; use Article::newFromTitle() instead
251 * @param $title Title
252 * @param $context RequestContext
253 * @return Article object
254 */
255 public static function articleFromTitle( $title, RequestContext $context ) {
256 return Article::newFromTitle( $title, $context );
257 }
258
259 /**
260 * Returns the action that will be executed, not necesserly the one passed
261 * passed through the "action" parameter. Actions disabled in
262 * $wgDisabledActions will be replaced by "nosuchaction"
263 *
264 * @return String: action
265 */
266 public function getAction() {
267 global $wgDisabledActions;
268
269 $request = $this->context->getRequest();
270 $action = $request->getVal( 'action', 'view' );
271
272 // Check for disabled actions
273 if ( in_array( $action, $wgDisabledActions ) ) {
274 $action = 'nosuchaction';
275 } elseif ( $action === 'historysubmit' ) {
276 // Workaround for bug #20966: inability of IE to provide an action dependent
277 // on which submit button is clicked.
278 if ( $request->getBool( 'revisiondelete' ) ) {
279 $action = 'revisiondelete';
280 } else {
281 $action = 'view';
282 }
283 } elseif ( $action == 'editredlink' ) {
284 $action = 'edit';
285 }
286
287 // Write back the executed action
288 $request->setVal( 'action', $action );
289 return $action;
290 }
291
292 /**
293 * Initialize the main Article object for "standard" actions (view, etc)
294 * Create an Article object for the page, following redirects if needed.
295 *
296 * @return mixed an Article, or a string to redirect to another URL
297 */
298 private function initializeArticle() {
299 global $wgDisableHardRedirects;
300
301 wfProfileIn( __METHOD__ );
302
303 $request = $this->context->getRequest();
304 $title = $this->context->getTitle();
305
306 $action = $request->getVal( 'action', 'view' );
307 $article = Article::newFromTitle( $title, $this->context );
308 // NS_MEDIAWIKI has no redirects.
309 // It is also used for CSS/JS, so performance matters here...
310 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
311 wfProfileOut( __METHOD__ );
312 return $article;
313 }
314 // Namespace might change when using redirects
315 // Check for redirects ...
316 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
317 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
318 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
319 !$request->getVal( 'diff' ) && // ... and not when showing diff
320 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
321 // ... and the article is not a non-redirect image page with associated file
322 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
323 {
324 // Give extensions a change to ignore/handle redirects as needed
325 $ignoreRedirect = $target = false;
326
327 wfRunHooks( 'InitializeArticleMaybeRedirect',
328 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
329
330 // Follow redirects only for... redirects.
331 // If $target is set, then a hook wanted to redirect.
332 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
333 // Is the target already set by an extension?
334 $target = $target ? $target : $article->followRedirect();
335 if ( is_string( $target ) ) {
336 if ( !$wgDisableHardRedirects ) {
337 // we'll need to redirect
338 wfProfileOut( __METHOD__ );
339 return $target;
340 }
341 }
342 if ( is_object( $target ) ) {
343 // Rewrite environment to redirected article
344 $rarticle = Article::newFromTitle( $target, $this->context );
345 $rarticle->loadPageData();
346 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
347 $rarticle->setRedirectedFrom( $title );
348 $article = $rarticle;
349 $this->context->setTitle( $target );
350 }
351 }
352 } else {
353 $this->context->setTitle( $article->getTitle() );
354 }
355 }
356 wfProfileOut( __METHOD__ );
357 return $article;
358 }
359
360 /**
361 * Cleaning up request by doing deferred updates, DB transaction, and the output
362 */
363 public function finalCleanup() {
364 wfProfileIn( __METHOD__ );
365 // Now commit any transactions, so that unreported errors after
366 // output() don't roll back the whole DB transaction
367 $factory = wfGetLBFactory();
368 $factory->commitMasterChanges();
369 // Output everything!
370 $this->context->getOutput()->output();
371 // Do any deferred jobs
372 wfDoUpdates( 'commit' );
373 $this->doJobs();
374 wfProfileOut( __METHOD__ );
375 }
376
377 /**
378 * Do a job from the job queue
379 */
380 private function doJobs() {
381 global $wgJobRunRate;
382
383 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
384 return;
385 }
386 if ( $wgJobRunRate < 1 ) {
387 $max = mt_getrandmax();
388 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
389 return;
390 }
391 $n = 1;
392 } else {
393 $n = intval( $wgJobRunRate );
394 }
395
396 while ( $n-- && false != ( $job = Job::pop() ) ) {
397 $output = $job->toString() . "\n";
398 $t = -wfTime();
399 $success = $job->run();
400 $t += wfTime();
401 $t = round( $t * 1000 );
402 if ( !$success ) {
403 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
404 } else {
405 $output .= "Success, Time: $t ms\n";
406 }
407 wfDebugLog( 'jobqueue', $output );
408 }
409 }
410
411 /**
412 * Ends this task peacefully
413 */
414 public function restInPeace() {
415 MessageCache::logMessages();
416 wfLogProfilingData();
417 // Commit and close up!
418 $factory = wfGetLBFactory();
419 $factory->commitMasterChanges();
420 $factory->shutdown();
421 wfDebug( "Request ended normally\n" );
422 }
423
424 /**
425 * Perform one of the "standard" actions
426 *
427 * @param $article Article
428 */
429 private function performAction( Page $article ) {
430 global $wgSquidMaxage, $wgUseExternalEditor;
431
432 wfProfileIn( __METHOD__ );
433
434 $request = $this->context->getRequest();
435 $output = $this->context->getOutput();
436 $title = $this->context->getTitle();
437 $user = $this->context->getUser();
438
439 if ( !wfRunHooks( 'MediaWikiPerformAction',
440 array( $output, $article, $title, $user, $request, $this ) ) )
441 {
442 wfProfileOut( __METHOD__ );
443 return;
444 }
445
446 $act = $this->getAction();
447
448 $action = Action::factory( $act, $article );
449 if( $action instanceof Action ){
450 $action->show();
451 wfProfileOut( __METHOD__ );
452 return;
453 }
454
455 switch( $act ) {
456 case 'view':
457 $output->setSquidMaxage( $wgSquidMaxage );
458 $article->view();
459 break;
460 case 'raw': // includes JS/CSS
461 wfProfileIn( __METHOD__ . '-raw' );
462 $raw = new RawPage( $article );
463 $raw->view();
464 wfProfileOut( __METHOD__ . '-raw' );
465 break;
466 case 'delete':
467 case 'protect':
468 case 'unprotect':
469 case 'render':
470 $article->$act();
471 break;
472 case 'submit':
473 if ( session_id() == '' ) {
474 // Send a cookie so anons get talk message notifications
475 wfSetupSession();
476 }
477 // Continue...
478 case 'edit':
479 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
480 $internal = $request->getVal( 'internaledit' );
481 $external = $request->getVal( 'externaledit' );
482 $section = $request->getVal( 'section' );
483 $oldid = $request->getVal( 'oldid' );
484 if ( !$wgUseExternalEditor || $act == 'submit' || $internal ||
485 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
486 $editor = new EditPage( $article );
487 $editor->submit();
488 } elseif ( $wgUseExternalEditor && ( $external || $user->getOption( 'externaleditor' ) ) ) {
489 $mode = $request->getVal( 'mode' );
490 $extedit = new ExternalEdit( $article, $mode );
491 $extedit->edit();
492 }
493 }
494 break;
495 case 'history':
496 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
497 $output->setSquidMaxage( $wgSquidMaxage );
498 }
499 $history = new HistoryPage( $article );
500 $history->history();
501 break;
502 default:
503 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
504 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
505 }
506 }
507 wfProfileOut( __METHOD__ );
508 }
509
510 /**
511 * Run the current MediaWiki instance
512 * index.php just calls this
513 */
514 function run() {
515 try {
516 $this->checkMaxLag( true );
517 $this->main();
518 $this->restInPeace();
519 } catch ( Exception $e ) {
520 MWExceptionHandler::handle( $e );
521 }
522 }
523
524 /**
525 * Checks if the request should abort due to a lagged server,
526 * for given maxlag parameter.
527 *
528 * @param boolean $abort True if this class should abort the
529 * script execution. False to return the result as a boolean.
530 * @return boolean True if we passed the check, false if we surpass the maxlag
531 */
532 function checkMaxLag( $abort ) {
533 global $wgShowHostnames;
534
535 wfProfileIn( __METHOD__ );
536 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
537 if ( !is_null( $maxLag ) ) {
538 $lb = wfGetLB(); // foo()->bar() is not supported in PHP4
539 list( $host, $lag ) = $lb->getMaxLag();
540 if ( $lag > $maxLag ) {
541 if ( $abort ) {
542 header( 'HTTP/1.1 503 Service Unavailable' );
543 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
544 header( 'X-Database-Lag: ' . intval( $lag ) );
545 header( 'Content-Type: text/plain' );
546 if( $wgShowHostnames ) {
547 echo "Waiting for $host: $lag seconds lagged\n";
548 } else {
549 echo "Waiting for a database server: $lag seconds lagged\n";
550 }
551 }
552
553 wfProfileOut( __METHOD__ );
554
555 if ( !$abort )
556 return false;
557 exit;
558 }
559 }
560 wfProfileOut( __METHOD__ );
561 return true;
562 }
563
564 function main() {
565 global $wgUseFileCache, $wgTitle, $wgUseAjax;
566
567 wfProfileIn( __METHOD__ );
568
569 # Set title from request parameters
570 $wgTitle = $this->getTitle();
571 $action = $this->getAction();
572
573 # Send Ajax requests to the Ajax dispatcher.
574 if ( $wgUseAjax && $action == 'ajax' ) {
575 $dispatcher = new AjaxDispatcher();
576 $dispatcher->performAction();
577 wfProfileOut( __METHOD__ );
578 return;
579 }
580
581 if ( $wgUseFileCache && $wgTitle->getNamespace() != NS_SPECIAL ) {
582 wfProfileIn( 'main-try-filecache' );
583 // Raw pages should handle cache control on their own,
584 // even when using file cache. This reduces hits from clients.
585 if ( HTMLFileCache::useFileCache() ) {
586 /* Try low-level file cache hit */
587 $cache = new HTMLFileCache( $wgTitle, $action );
588 if ( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
589 /* Check incoming headers to see if client has this cached */
590 if ( !$this->context->getOutput()->checkLastModified( $cache->fileCacheTime() ) ) {
591 $cache->loadFromFileCache();
592 }
593 # Do any stats increment/watchlist stuff
594 $article = Article::newFromTitle( $wgTitle, $this->context );
595 $article->viewUpdates();
596 # Tell OutputPage that output is taken care of
597 $this->context->getOutput()->disable();
598 wfProfileOut( 'main-try-filecache' );
599 wfProfileOut( __METHOD__ );
600 return;
601 }
602 }
603 wfProfileOut( 'main-try-filecache' );
604 }
605
606 $this->performRequest();
607 $this->finalCleanup();
608
609 wfProfileOut( __METHOD__ );
610 }
611 }