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