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