3 * MediaWiki is the to-be base class for this whole project
5 * @internal documentation reviewed 15 Mar 2010
10 * TODO: fold $output, etc, into this
15 public function request( WebRequest
$x = null ){
16 $old = $this->context
->getRequest();
17 $this->context
->setRequest( $x );
21 public function output( OutputPage
$x = null ){
22 $old = $this->context
->getOutput();
23 $this->context
->setOutput( $x );
27 public function __construct( RequestContext
$context = null ) {
29 $context = RequestContext
::getMain();
32 $this->context
= $context;
33 $this->context
->setTitle( $this->parseTitle() );
37 * Parse $request to get the Title object
39 * @return Title object to be $wgTitle
41 private function parseTitle() {
44 $request = $this->context
->getRequest();
45 $curid = $request->getInt( 'curid' );
46 $title = $request->getVal( 'title' );
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' );
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();
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 );
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
73 $rev = Revision
::newFromId( $oldid );
74 $ret = $rev ?
$rev->getTitle() : $ret;
78 if( $ret === null ||
( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ){
85 * Get the Title object that we'll be acting on, as specified in the WebRequest
88 public function getTitle(){
89 if( $this->context
->getTitle() === null ){
90 $this->context
->setTitle( $this->parseTitle() );
92 return $this->context
->getTitle();
96 * Performs the request.
99 * - local interwiki redirects
104 * @return Article object
106 public function performRequest() {
107 global $wgServer, $wgUsePathInfo;
109 wfProfileIn( __METHOD__
);
111 $request = $this->context
->getRequest();
112 $title = $this->context
->getTitle();
113 $output = $this->context
->getOutput();
114 $user = $this->context
->getUser();
116 if ( $request->getVal( 'printable' ) === 'yes' ) {
117 $output->setPrintable();
120 wfRunHooks( 'BeforeInitialize', array(
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' );
141 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
143 $query = $request->getValues();
144 unset( $query['title'] );
145 $url = $title->getFullURL( $query );
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 );
152 $this->context
->setTitle( new BadTitle
);
153 wfProfileOut( __METHOD__
);
154 throw new ErrorPageError( 'badtitle', 'badtitletext' );
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' ) ) ) )
161 if ( $title->getNamespace() == NS_SPECIAL
) {
162 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
164 $title = SpecialPage
::getTitleFor( $name, $subpage );
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";
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 " .
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 " .
189 wfHttpError( 500, "Internal error", $message );
191 $output->setSquidMaxage( 1200 );
192 $output->redirect( $targetUrl, '301' );
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
);
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 ) ) {
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
209 $wgArticle = $article;
211 $this->performAction( $article );
212 wfProfileOut( __METHOD__
);
214 } elseif ( is_string( $article ) ) {
215 $output->redirect( $article );
217 wfProfileOut( __METHOD__
);
218 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
221 wfProfileOut( __METHOD__
);
225 * Create an Article object of the appropriate class for the given page.
227 * @deprecated in 1.19; use Article::newFromTitle() instead
228 * @param $title Title
229 * @param $context RequestContext
230 * @return Article object
232 public static function articleFromTitle( $title, RequestContext
$context ) {
233 return Article
::newFromTitle( $title, $context );
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"
241 * @return String: action
243 public function getAction() {
244 global $wgDisabledActions;
246 $request = $this->context
->getRequest();
247 $action = $request->getVal( 'action', 'view' );
249 // Check for disabled actions
250 if ( in_array( $action, $wgDisabledActions ) ) {
251 return 'nosuchaction';
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';
262 } elseif ( $action == 'editredlink' ) {
270 * Initialize the main Article object for "standard" actions (view, etc)
271 * Create an Article object for the page, following redirects if needed.
273 * @return mixed an Article, or a string to redirect to another URL
275 private function initializeArticle() {
276 global $wgDisableHardRedirects;
278 wfProfileIn( __METHOD__
);
280 $request = $this->context
->getRequest();
281 $title = $this->context
->getTitle();
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__
);
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() ) )
301 // Give extensions a change to ignore/handle redirects as needed
302 $ignoreRedirect = $target = false;
304 wfRunHooks( 'InitializeArticleMaybeRedirect',
305 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
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__
);
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 );
330 $this->context
->setTitle( $article->getTitle() );
333 wfProfileOut( __METHOD__
);
338 * Cleaning up request by doing deferred updates, DB transaction, and the output
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' );
351 wfProfileOut( __METHOD__
);
355 * Do a job from the job queue
357 private function doJobs() {
358 global $wgJobRunRate;
360 if ( $wgJobRunRate <= 0 ||
wfReadOnly() ) {
363 if ( $wgJobRunRate < 1 ) {
364 $max = mt_getrandmax();
365 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
370 $n = intval( $wgJobRunRate );
373 while ( $n-- && false != ( $job = Job
::pop() ) ) {
374 $output = $job->toString() . "\n";
376 $success = $job->run();
378 $t = round( $t * 1000 );
380 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
382 $output .= "Success, Time: $t ms\n";
384 wfDebugLog( 'jobqueue', $output );
389 * Ends this task peacefully
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" );
402 * Perform one of the "standard" actions
404 * @param $article Article
406 private function performAction( $article ) {
407 global $wgSquidMaxage, $wgUseExternalEditor;
409 wfProfileIn( __METHOD__
);
411 $request = $this->context
->getRequest();
412 $output = $this->context
->getOutput();
413 $title = $this->context
->getTitle();
414 $user = $this->context
->getUser();
416 if ( !wfRunHooks( 'MediaWikiPerformAction', array(
417 $output, $article, $title,
418 $user, $request, $this ) ) )
420 wfProfileOut( __METHOD__
);
424 $act = $this->getAction();
426 $action = Action
::factory( $act, $article );
427 if( $action instanceof Action
){
429 wfProfileOut( __METHOD__
);
435 $output->setSquidMaxage( $wgSquidMaxage );
438 case 'raw': // includes JS/CSS
439 wfProfileIn( __METHOD__
. '-raw' );
440 $raw = new RawPage( $article );
442 wfProfileOut( __METHOD__
. '-raw' );
453 if ( session_id() == '' ) {
454 // Send a cookie so anons get talk message notifications
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 );
468 } elseif ( $wgUseExternalEditor && ( $external ||
$user->getOption( 'externaleditor' ) ) ) {
469 $mode = $request->getVal( 'mode' );
470 $extedit = new ExternalEdit( $article, $mode );
476 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
477 $output->setSquidMaxage( $wgSquidMaxage );
479 $history = new HistoryPage( $article );
483 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
484 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
487 wfProfileOut( __METHOD__
);
491 * Run the current MediaWiki instance
492 * index.php just calls this
496 $this->checkMaxLag( true );
498 $this->restInPeace();
499 } catch ( Exception
$e ) {
500 MWExceptionHandler
::handle( $e );
505 * Checks if the request should abort due to a lagged server,
506 * for given maxlag parameter.
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
512 function checkMaxLag( $abort ) {
513 global $wgShowHostnames;
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 ) {
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";
529 echo "Waiting for a database server: $lag seconds lagged\n";
533 wfProfileOut( __METHOD__
);
540 wfProfileOut( __METHOD__
);
545 global $wgUseFileCache, $wgTitle, $wgUseAjax;
547 wfProfileIn( __METHOD__
);
549 # Set title from request parameters
550 $wgTitle = $this->getTitle();
551 $action = $this->getAction();
553 # Send Ajax requests to the Ajax dispatcher.
554 if ( $wgUseAjax && $action == 'ajax' ) {
555 $dispatcher = new AjaxDispatcher();
556 $dispatcher->performAction();
557 wfProfileOut( __METHOD__
);
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();
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__
);
583 wfProfileOut( 'main-try-filecache' );
586 $this->performRequest();
587 $this->finalCleanup();
589 wfProfileOut( __METHOD__
);