Minor tweak to r95521: remove outdated comment about $wgArticle
[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 throw new ErrorPageError( 'badtitle', 'badtitletext' );
153 // If the user is not logged in, the Namespace:title of the article must be in
154 // the Read array in order for the user to see it. (We have to check here to
155 // catch special pages etc. We check again in Article::view())
156 } elseif ( !$title->userCanRead() ) {
157 $output->loginToUse();
158 // Interwiki redirects
159 } elseif ( $title->getInterwiki() != '' ) {
160 $rdfrom = $request->getVal( 'rdfrom' );
161 if ( $rdfrom ) {
162 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
163 } else {
164 $query = $request->getValues();
165 unset( $query['title'] );
166 $url = $title->getFullURL( $query );
167 }
168 // Check for a redirect loop
169 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url )
170 && $title->isLocal() )
171 {
172 // 301 so google et al report the target as the actual url.
173 $output->redirect( $url, 301 );
174 } else {
175 $this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
176 wfProfileOut( __METHOD__ );
177 throw new ErrorPageError( 'badtitle', 'badtitletext' );
178 }
179 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
180 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
181 && ( $request->getVal( 'title' ) === null ||
182 $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
183 && !count( $request->getValueNames( array( 'action', 'title' ) ) ) )
184 {
185 if ( $title->getNamespace() == NS_SPECIAL ) {
186 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
187 if ( $name ) {
188 $title = SpecialPage::getTitleFor( $name, $subpage );
189 }
190 }
191 $targetUrl = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
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 ( $wgUsePathInfo ) {
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 } else {
215 $output->setSquidMaxage( 1200 );
216 $output->redirect( $targetUrl, '301' );
217 }
218 // Special pages
219 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
220 $pageView = true;
221 // Actions that need to be made when we have a special pages
222 SpecialPageFactory::executePath( $title, $this->context );
223 } else {
224 // ...otherwise treat it as an article view. The article
225 // may be a redirect to another article or URL.
226 $article = $this->initializeArticle();
227 if ( is_object( $article ) ) {
228 $pageView = true;
229 /**
230 * $wgArticle is deprecated, do not use it. This will possibly be removed
231 * entirely in 1.20 or 1.21
232 * @deprecated since 1.18
233 */
234 global $wgArticle;
235 $wgArticle = $article;
236
237 $this->performAction( $article );
238 } elseif ( is_string( $article ) ) {
239 $output->redirect( $article );
240 } else {
241 wfProfileOut( __METHOD__ );
242 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
243 }
244 }
245
246 if ( $pageView ) {
247 // Promote user to any groups they meet the criteria for
248 $user->addAutopromoteOnceGroups( 'onView' );
249 }
250
251 wfProfileOut( __METHOD__ );
252 }
253
254 /**
255 * Create an Article object of the appropriate class for the given page.
256 *
257 * @deprecated in 1.18; use Article::newFromTitle() instead
258 * @param $title Title
259 * @param $context RequestContext
260 * @return Article object
261 */
262 public static function articleFromTitle( $title, RequestContext $context ) {
263 return Article::newFromTitle( $title, $context );
264 }
265
266 /**
267 * Returns the action that will be executed, not necessarily the one passed
268 * passed through the "action" parameter. Actions disabled in
269 * $wgDisabledActions will be replaced by "nosuchaction"
270 *
271 * @return String: action
272 */
273 public function getAction() {
274 global $wgDisabledActions;
275
276 $request = $this->context->getRequest();
277 $action = $request->getVal( 'action', 'view' );
278
279 // Check for disabled actions
280 if ( in_array( $action, $wgDisabledActions ) ) {
281 return 'nosuchaction';
282 }
283
284 // Workaround for bug #20966: inability of IE to provide an action dependent
285 // on which submit button is clicked.
286 if ( $action === 'historysubmit' ) {
287 if ( $request->getBool( 'revisiondelete' ) ) {
288 return 'revisiondelete';
289 } else {
290 return 'view';
291 }
292 } elseif ( $action == 'editredlink' ) {
293 return 'edit';
294 }
295
296 return $action;
297 }
298
299 /**
300 * Initialize the main Article object for "standard" actions (view, etc)
301 * Create an Article object for the page, following redirects if needed.
302 *
303 * @return mixed an Article, or a string to redirect to another URL
304 */
305 private function initializeArticle() {
306 global $wgDisableHardRedirects;
307
308 wfProfileIn( __METHOD__ );
309
310 $request = $this->context->getRequest();
311 $title = $this->context->getTitle();
312
313 $action = $request->getVal( 'action', 'view' );
314 $article = Article::newFromTitle( $title, $this->context );
315 // NS_MEDIAWIKI has no redirects.
316 // It is also used for CSS/JS, so performance matters here...
317 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
318 wfProfileOut( __METHOD__ );
319 return $article;
320 }
321 // Namespace might change when using redirects
322 // Check for redirects ...
323 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
324 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
325 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
326 !$request->getVal( 'diff' ) && // ... and not when showing diff
327 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
328 // ... and the article is not a non-redirect image page with associated file
329 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
330 {
331 // Give extensions a change to ignore/handle redirects as needed
332 $ignoreRedirect = $target = false;
333
334 wfRunHooks( 'InitializeArticleMaybeRedirect',
335 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
336
337 // Follow redirects only for... redirects.
338 // If $target is set, then a hook wanted to redirect.
339 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
340 // Is the target already set by an extension?
341 $target = $target ? $target : $article->followRedirect();
342 if ( is_string( $target ) ) {
343 if ( !$wgDisableHardRedirects ) {
344 // we'll need to redirect
345 wfProfileOut( __METHOD__ );
346 return $target;
347 }
348 }
349 if ( is_object( $target ) ) {
350 // Rewrite environment to redirected article
351 $rarticle = Article::newFromTitle( $target, $this->context );
352 $rarticle->loadPageData();
353 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
354 $rarticle->setRedirectedFrom( $title );
355 $article = $rarticle;
356 $this->context->setTitle( $target );
357 }
358 }
359 } else {
360 $this->context->setTitle( $article->getTitle() );
361 }
362 }
363
364 wfProfileOut( __METHOD__ );
365 return $article;
366 }
367
368 /**
369 * Cleaning up request by doing deferred updates, DB transaction, and the output
370 */
371 public function finalCleanup() {
372 wfProfileIn( __METHOD__ );
373 // Now commit any transactions, so that unreported errors after
374 // output() don't roll back the whole DB transaction
375 $factory = wfGetLBFactory();
376 $factory->commitMasterChanges();
377 // Output everything!
378 $this->context->getOutput()->output();
379 // Do any deferred jobs
380 wfDoUpdates( 'commit' );
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 $article Article
436 */
437 private function performAction( Page $article ) {
438 global $wgSquidMaxage, $wgUseExternalEditor;
439
440 wfProfileIn( __METHOD__ );
441
442 $request = $this->context->getRequest();
443 $output = $this->context->getOutput();
444 $title = $this->context->getTitle();
445 $user = $this->context->getUser();
446
447 if ( !wfRunHooks( 'MediaWikiPerformAction',
448 array( $output, $article, $title, $user, $request, $this ) ) )
449 {
450 wfProfileOut( __METHOD__ );
451 return;
452 }
453
454 $act = $this->getAction();
455
456 $action = Action::factory( $act, $article );
457 if ( $action instanceof Action ) {
458 $action->show();
459 wfProfileOut( __METHOD__ );
460 return;
461 }
462
463 switch( $act ) {
464 case 'view':
465 $output->setSquidMaxage( $wgSquidMaxage );
466 $article->view();
467 break;
468 case 'raw': // includes JS/CSS
469 wfProfileIn( __METHOD__ . '-raw' );
470 $raw = new RawPage( $article );
471 $raw->view();
472 wfProfileOut( __METHOD__ . '-raw' );
473 break;
474 case 'delete':
475 case 'protect':
476 case 'unprotect':
477 case 'render':
478 $article->$act();
479 break;
480 case 'submit':
481 if ( session_id() == '' ) {
482 // Send a cookie so anons get talk message notifications
483 wfSetupSession();
484 }
485 // Continue...
486 case 'edit':
487 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
488 $internal = $request->getVal( 'internaledit' );
489 $external = $request->getVal( 'externaledit' );
490 $section = $request->getVal( 'section' );
491 $oldid = $request->getVal( 'oldid' );
492 if ( !$wgUseExternalEditor || $act == 'submit' || $internal ||
493 $section || $oldid ||
494 ( !$user->getOption( 'externaleditor' ) && !$external ) )
495 {
496 $editor = new EditPage( $article );
497 $editor->submit();
498 } elseif ( $wgUseExternalEditor
499 && ( $external || $user->getOption( 'externaleditor' ) ) )
500 {
501 $mode = $request->getVal( 'mode' );
502 $extedit = new ExternalEdit( $article->getTitle(), $mode );
503 $extedit->edit();
504 }
505 }
506 break;
507 case 'history':
508 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
509 $output->setSquidMaxage( $wgSquidMaxage );
510 }
511 $history = new HistoryPage( $article );
512 $history->history();
513 break;
514 default:
515 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
516 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
517 }
518 }
519 wfProfileOut( __METHOD__ );
520 }
521
522 /**
523 * Run the current MediaWiki instance
524 * index.php just calls this
525 */
526 public function run() {
527 try {
528 $this->checkMaxLag( true );
529 $this->main();
530 $this->restInPeace();
531 } catch ( Exception $e ) {
532 MWExceptionHandler::handle( $e );
533 }
534 }
535
536 /**
537 * Checks if the request should abort due to a lagged server,
538 * for given maxlag parameter.
539 *
540 * @param boolean $abort True if this class should abort the
541 * script execution. False to return the result as a boolean.
542 * @return boolean True if we passed the check, false if we surpass the maxlag
543 */
544 private function checkMaxLag( $abort ) {
545 global $wgShowHostnames;
546
547 wfProfileIn( __METHOD__ );
548 $maxLag = $this->context->getRequest()->getVal( 'maxlag' );
549 if ( !is_null( $maxLag ) ) {
550 $lb = wfGetLB(); // foo()->bar() is not supported in PHP4
551 list( $host, $lag ) = $lb->getMaxLag();
552 if ( $lag > $maxLag ) {
553 if ( $abort ) {
554 $resp = $this->context->getRequest()->response();
555 $resp->header( 'HTTP/1.1 503 Service Unavailable' );
556 $resp->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
557 $resp->header( 'X-Database-Lag: ' . intval( $lag ) );
558 $resp->header( 'Content-Type: text/plain' );
559 if( $wgShowHostnames ) {
560 echo "Waiting for $host: $lag seconds lagged\n";
561 } else {
562 echo "Waiting for a database server: $lag seconds lagged\n";
563 }
564 }
565
566 wfProfileOut( __METHOD__ );
567
568 if ( !$abort ) {
569 return false;
570 }
571 exit;
572 }
573 }
574 wfProfileOut( __METHOD__ );
575 return true;
576 }
577
578 private function main() {
579 global $wgUseFileCache, $wgTitle, $wgUseAjax;
580
581 wfProfileIn( __METHOD__ );
582
583 # Set title from request parameters
584 $wgTitle = $this->getTitle();
585 $action = $this->getAction();
586 $user = $this->context->getUser();
587
588 # Send Ajax requests to the Ajax dispatcher.
589 if ( $wgUseAjax && $action == 'ajax' ) {
590 $dispatcher = new AjaxDispatcher();
591 $dispatcher->performAction();
592 wfProfileOut( __METHOD__ );
593 return;
594 }
595
596 if ( $wgUseFileCache && $wgTitle->getNamespace() != NS_SPECIAL ) {
597 wfProfileIn( 'main-try-filecache' );
598 // Raw pages should handle cache control on their own,
599 // even when using file cache. This reduces hits from clients.
600 if ( HTMLFileCache::useFileCache() ) {
601 /* Try low-level file cache hit */
602 $cache = new HTMLFileCache( $wgTitle, $action );
603 if ( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
604 /* Check incoming headers to see if client has this cached */
605 $timestamp = $cache->fileCacheTime();
606 if ( !$this->context->getOutput()->checkLastModified( $timestamp ) ) {
607 $cache->loadFromFileCache();
608 }
609 # Do any stats increment/watchlist stuff
610 $article = WikiPage::factory( $wgTitle );
611 $article->doViewUpdates( $user );
612 # Tell OutputPage that output is taken care of
613 $this->context->getOutput()->disable();
614 wfProfileOut( 'main-try-filecache' );
615 wfProfileOut( __METHOD__ );
616 return;
617 }
618 }
619 wfProfileOut( 'main-try-filecache' );
620 }
621
622 $this->performRequest();
623 $this->finalCleanup();
624
625 wfProfileOut( __METHOD__ );
626 }
627 }