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