Merge "Import: Handle uploads with sha1 starting with 0 properly"
[mediawiki.git] / includes / page / Article.php
blobaf1f00b5050a76e6ba47aba7f7be18c76ac76fa1
1 <?php
2 /**
3 * User interface for page actions.
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.
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.
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
20 * @file
23 /**
24 * Class for viewing MediaWiki article and history.
26 * This maintains WikiPage functions for backwards compatibility.
28 * @todo Move and rewrite code to an Action class
30 * See design.txt for an overview.
31 * Note: edit user interface and cache support functions have been
32 * moved to separate EditPage and HTMLFileCache classes.
34 class Article implements Page {
35 /** @var IContextSource The context this Article is executed in */
36 protected $mContext;
38 /** @var WikiPage The WikiPage object of this instance */
39 protected $mPage;
41 /** @var ParserOptions ParserOptions object for $wgUser articles */
42 public $mParserOptions;
44 /**
45 * @var string Text of the revision we are working on
46 * @todo BC cruft
48 public $mContent;
50 /**
51 * @var Content Content of the revision we are working on
52 * @since 1.21
54 public $mContentObject;
56 /** @var bool Is the content ($mContent) already loaded? */
57 public $mContentLoaded = false;
59 /** @var int|null The oldid of the article that is to be shown, 0 for the current revision */
60 public $mOldId;
62 /** @var Title Title from which we were redirected here */
63 public $mRedirectedFrom = null;
65 /** @var string|bool URL to redirect to or false if none */
66 public $mRedirectUrl = false;
68 /** @var int Revision ID of revision we are working on */
69 public $mRevIdFetched = 0;
71 /** @var Revision Revision we are working on */
72 public $mRevision = null;
74 /** @var ParserOutput */
75 public $mParserOutput;
77 /**
78 * Constructor and clear the article
79 * @param Title $title Reference to a Title object.
80 * @param int $oldId Revision ID, null to fetch from request, zero for current
82 public function __construct( Title $title, $oldId = null ) {
83 $this->mOldId = $oldId;
84 $this->mPage = $this->newPage( $title );
87 /**
88 * @param Title $title
89 * @return WikiPage
91 protected function newPage( Title $title ) {
92 return new WikiPage( $title );
95 /**
96 * Constructor from a page id
97 * @param int $id Article ID to load
98 * @return Article|null
100 public static function newFromID( $id ) {
101 $t = Title::newFromID( $id );
102 # @todo FIXME: Doesn't inherit right
103 return $t == null ? null : new self( $t );
104 # return $t == null ? null : new static( $t ); // PHP 5.3
108 * Create an Article object of the appropriate class for the given page.
110 * @param Title $title
111 * @param IContextSource $context
112 * @return Article
114 public static function newFromTitle( $title, IContextSource $context ) {
115 if ( NS_MEDIA == $title->getNamespace() ) {
116 // FIXME: where should this go?
117 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
120 $page = null;
121 Hooks::run( 'ArticleFromTitle', array( &$title, &$page, $context ) );
122 if ( !$page ) {
123 switch ( $title->getNamespace() ) {
124 case NS_FILE:
125 $page = new ImagePage( $title );
126 break;
127 case NS_CATEGORY:
128 $page = new CategoryPage( $title );
129 break;
130 default:
131 $page = new Article( $title );
134 $page->setContext( $context );
136 return $page;
140 * Create an Article object of the appropriate class for the given page.
142 * @param WikiPage $page
143 * @param IContextSource $context
144 * @return Article
146 public static function newFromWikiPage( WikiPage $page, IContextSource $context ) {
147 $article = self::newFromTitle( $page->getTitle(), $context );
148 $article->mPage = $page; // override to keep process cached vars
149 return $article;
153 * Tell the page view functions that this view was redirected
154 * from another page on the wiki.
155 * @param Title $from
157 public function setRedirectedFrom( Title $from ) {
158 $this->mRedirectedFrom = $from;
162 * Get the title object of the article
164 * @return Title Title object of this page
166 public function getTitle() {
167 return $this->mPage->getTitle();
171 * Get the WikiPage object of this instance
173 * @since 1.19
174 * @return WikiPage
176 public function getPage() {
177 return $this->mPage;
181 * Clear the object
183 public function clear() {
184 $this->mContentLoaded = false;
186 $this->mRedirectedFrom = null; # Title object if set
187 $this->mRevIdFetched = 0;
188 $this->mRedirectUrl = false;
190 $this->mPage->clear();
194 * Note that getContent does not follow redirects anymore.
195 * If you need to fetch redirectable content easily, try
196 * the shortcut in WikiPage::getRedirectTarget()
198 * This function has side effects! Do not use this function if you
199 * only want the real revision text if any.
201 * @deprecated since 1.21; use WikiPage::getContent() instead
203 * @return string Return the text of this revision
205 public function getContent() {
206 ContentHandler::deprecated( __METHOD__, '1.21' );
207 $content = $this->getContentObject();
208 return ContentHandler::getContentText( $content );
212 * Returns a Content object representing the pages effective display content,
213 * not necessarily the revision's content!
215 * Note that getContent does not follow redirects anymore.
216 * If you need to fetch redirectable content easily, try
217 * the shortcut in WikiPage::getRedirectTarget()
219 * This function has side effects! Do not use this function if you
220 * only want the real revision text if any.
222 * @return Content Return the content of this revision
224 * @since 1.21
226 protected function getContentObject() {
228 if ( $this->mPage->getID() === 0 ) {
229 # If this is a MediaWiki:x message, then load the messages
230 # and return the message value for x.
231 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI ) {
232 $text = $this->getTitle()->getDefaultMessageText();
233 if ( $text === false ) {
234 $text = '';
237 $content = ContentHandler::makeContent( $text, $this->getTitle() );
238 } else {
239 $message = $this->getContext()->getUser()->isLoggedIn() ? 'noarticletext' : 'noarticletextanon';
240 $content = new MessageContent( $message, null, 'parsemag' );
242 } else {
243 $this->fetchContentObject();
244 $content = $this->mContentObject;
247 return $content;
251 * @return int The oldid of the article that is to be shown, 0 for the current revision
253 public function getOldID() {
254 if ( is_null( $this->mOldId ) ) {
255 $this->mOldId = $this->getOldIDFromRequest();
258 return $this->mOldId;
262 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
264 * @return int The old id for the request
266 public function getOldIDFromRequest() {
267 $this->mRedirectUrl = false;
269 $request = $this->getContext()->getRequest();
270 $oldid = $request->getIntOrNull( 'oldid' );
272 if ( $oldid === null ) {
273 return 0;
276 if ( $oldid !== 0 ) {
277 # Load the given revision and check whether the page is another one.
278 # In that case, update this instance to reflect the change.
279 if ( $oldid === $this->mPage->getLatest() ) {
280 $this->mRevision = $this->mPage->getRevision();
281 } else {
282 $this->mRevision = Revision::newFromId( $oldid );
283 if ( $this->mRevision !== null ) {
284 // Revision title doesn't match the page title given?
285 if ( $this->mPage->getID() != $this->mRevision->getPage() ) {
286 $function = array( get_class( $this->mPage ), 'newFromID' );
287 $this->mPage = call_user_func( $function, $this->mRevision->getPage() );
293 if ( $request->getVal( 'direction' ) == 'next' ) {
294 $nextid = $this->getTitle()->getNextRevisionID( $oldid );
295 if ( $nextid ) {
296 $oldid = $nextid;
297 $this->mRevision = null;
298 } else {
299 $this->mRedirectUrl = $this->getTitle()->getFullURL( 'redirect=no' );
301 } elseif ( $request->getVal( 'direction' ) == 'prev' ) {
302 $previd = $this->getTitle()->getPreviousRevisionID( $oldid );
303 if ( $previd ) {
304 $oldid = $previd;
305 $this->mRevision = null;
309 return $oldid;
313 * Get text of an article from database
314 * Does *NOT* follow redirects.
316 * @protected
317 * @note This is really internal functionality that should really NOT be
318 * used by other functions. For accessing article content, use the WikiPage
319 * class, especially WikiBase::getContent(). However, a lot of legacy code
320 * uses this method to retrieve page text from the database, so the function
321 * has to remain public for now.
323 * @return string|bool String containing article contents, or false if null
324 * @deprecated since 1.21, use WikiPage::getContent() instead
326 function fetchContent() {
327 // BC cruft!
329 ContentHandler::deprecated( __METHOD__, '1.21' );
331 if ( $this->mContentLoaded && $this->mContent ) {
332 return $this->mContent;
335 $content = $this->fetchContentObject();
337 if ( !$content ) {
338 return false;
341 // @todo Get rid of mContent everywhere!
342 $this->mContent = ContentHandler::getContentText( $content );
343 ContentHandler::runLegacyHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) );
345 return $this->mContent;
349 * Get text content object
350 * Does *NOT* follow redirects.
351 * @todo When is this null?
353 * @note Code that wants to retrieve page content from the database should
354 * use WikiPage::getContent().
356 * @return Content|null|bool
358 * @since 1.21
360 protected function fetchContentObject() {
361 if ( $this->mContentLoaded ) {
362 return $this->mContentObject;
365 $this->mContentLoaded = true;
366 $this->mContent = null;
368 $oldid = $this->getOldID();
370 # Pre-fill content with error message so that if something
371 # fails we'll have something telling us what we intended.
372 // XXX: this isn't page content but a UI message. horrible.
373 $this->mContentObject = new MessageContent( 'missing-revision', array( $oldid ) );
375 if ( $oldid ) {
376 # $this->mRevision might already be fetched by getOldIDFromRequest()
377 if ( !$this->mRevision ) {
378 $this->mRevision = Revision::newFromId( $oldid );
379 if ( !$this->mRevision ) {
380 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
381 return false;
384 } else {
385 $oldid = $this->mPage->getLatest();
386 if ( !$oldid ) {
387 wfDebug( __METHOD__ . " failed to find page data for title " .
388 $this->getTitle()->getPrefixedText() . "\n" );
389 return false;
392 # Update error message with correct oldid
393 $this->mContentObject = new MessageContent( 'missing-revision', array( $oldid ) );
395 $this->mRevision = $this->mPage->getRevision();
397 if ( !$this->mRevision ) {
398 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id $oldid\n" );
399 return false;
403 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
404 // We should instead work with the Revision object when we need it...
405 // Loads if user is allowed
406 $content = $this->mRevision->getContent(
407 Revision::FOR_THIS_USER,
408 $this->getContext()->getUser()
411 if ( !$content ) {
412 wfDebug( __METHOD__ . " failed to retrieve content of revision " .
413 $this->mRevision->getId() . "\n" );
414 return false;
417 $this->mContentObject = $content;
418 $this->mRevIdFetched = $this->mRevision->getId();
420 Hooks::run( 'ArticleAfterFetchContentObject', array( &$this, &$this->mContentObject ) );
422 return $this->mContentObject;
426 * Returns true if the currently-referenced revision is the current edit
427 * to this page (and it exists).
428 * @return bool
430 public function isCurrent() {
431 # If no oldid, this is the current version.
432 if ( $this->getOldID() == 0 ) {
433 return true;
436 return $this->mPage->exists() && $this->mRevision && $this->mRevision->isCurrent();
440 * Get the fetched Revision object depending on request parameters or null
441 * on failure.
443 * @since 1.19
444 * @return Revision|null
446 public function getRevisionFetched() {
447 $this->fetchContentObject();
449 return $this->mRevision;
453 * Use this to fetch the rev ID used on page views
455 * @return int Revision ID of last article revision
457 public function getRevIdFetched() {
458 if ( $this->mRevIdFetched ) {
459 return $this->mRevIdFetched;
460 } else {
461 return $this->mPage->getLatest();
466 * This is the default action of the index.php entry point: just view the
467 * page of the given title.
469 public function view() {
470 global $wgUseFileCache, $wgUseETag, $wgDebugToolbar, $wgMaxRedirects;
472 # Get variables from query string
473 # As side effect this will load the revision and update the title
474 # in a revision ID is passed in the request, so this should remain
475 # the first call of this method even if $oldid is used way below.
476 $oldid = $this->getOldID();
478 $user = $this->getContext()->getUser();
479 # Another whitelist check in case getOldID() is altering the title
480 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'read', $user );
481 if ( count( $permErrors ) ) {
482 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
483 throw new PermissionsError( 'read', $permErrors );
486 $outputPage = $this->getContext()->getOutput();
487 # getOldID() may as well want us to redirect somewhere else
488 if ( $this->mRedirectUrl ) {
489 $outputPage->redirect( $this->mRedirectUrl );
490 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
492 return;
495 # If we got diff in the query, we want to see a diff page instead of the article.
496 if ( $this->getContext()->getRequest()->getCheck( 'diff' ) ) {
497 wfDebug( __METHOD__ . ": showing diff page\n" );
498 $this->showDiffPage();
500 return;
503 # Set page title (may be overridden by DISPLAYTITLE)
504 $outputPage->setPageTitle( $this->getTitle()->getPrefixedText() );
506 $outputPage->setArticleFlag( true );
507 # Allow frames by default
508 $outputPage->allowClickjacking();
510 $parserCache = ParserCache::singleton();
512 $parserOptions = $this->getParserOptions();
513 # Render printable version, use printable version cache
514 if ( $outputPage->isPrintable() ) {
515 $parserOptions->setIsPrintable( true );
516 $parserOptions->setEditSection( false );
517 } elseif ( !$this->isCurrent() || !$this->getTitle()->quickUserCan( 'edit', $user ) ) {
518 $parserOptions->setEditSection( false );
521 # Try client and file cache
522 if ( !$wgDebugToolbar && $oldid === 0 && $this->mPage->checkTouched() ) {
523 if ( $wgUseETag ) {
524 $outputPage->setETag( $parserCache->getETag( $this, $parserOptions ) );
527 # Use the greatest of the page's timestamp or the timestamp of any
528 # redirect in the chain (bug 67849)
529 $timestamp = $this->mPage->getTouched();
530 if ( isset( $this->mRedirectedFrom ) ) {
531 $timestamp = max( $timestamp, $this->mRedirectedFrom->getTouched() );
533 # If there can be more than one redirect in the chain, we have
534 # to go through the whole chain too in case an intermediate
535 # redirect was changed.
536 if ( $wgMaxRedirects > 1 ) {
537 $titles = Revision::newFromTitle( $this->mRedirectedFrom )
538 ->getContent( Revision::FOR_THIS_USER, $user )
539 ->getRedirectChain();
540 $thisTitle = $this->getTitle();
541 foreach ( $titles as $title ) {
542 if ( Title::compare( $title, $thisTitle ) === 0 ) {
543 break;
545 $timestamp = max( $timestamp, $title->getTouched() );
550 # Is it client cached?
551 if ( $outputPage->checkLastModified( $timestamp ) ) {
552 wfDebug( __METHOD__ . ": done 304\n" );
554 return;
555 # Try file cache
556 } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
557 wfDebug( __METHOD__ . ": done file cache\n" );
558 # tell wgOut that output is taken care of
559 $outputPage->disable();
560 $this->mPage->doViewUpdates( $user, $oldid );
562 return;
566 # Should the parser cache be used?
567 $useParserCache = $this->mPage->shouldCheckParserCache( $parserOptions, $oldid );
568 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
569 if ( $user->getStubThreshold() ) {
570 $this->getContext()->getStats()->increment( 'pcache_miss_stub' );
573 $this->showRedirectedFromHeader();
574 $this->showNamespaceHeader();
576 # Iterate through the possible ways of constructing the output text.
577 # Keep going until $outputDone is set, or we run out of things to do.
578 $pass = 0;
579 $outputDone = false;
580 $this->mParserOutput = false;
582 while ( !$outputDone && ++$pass ) {
583 switch ( $pass ) {
584 case 1:
585 Hooks::run( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
586 break;
587 case 2:
588 # Early abort if the page doesn't exist
589 if ( !$this->mPage->exists() ) {
590 wfDebug( __METHOD__ . ": showing missing article\n" );
591 $this->showMissingArticle();
592 $this->mPage->doViewUpdates( $user );
593 return;
596 # Try the parser cache
597 if ( $useParserCache ) {
598 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
600 if ( $this->mParserOutput !== false ) {
601 if ( $oldid ) {
602 wfDebug( __METHOD__ . ": showing parser cache contents for current rev permalink\n" );
603 $this->setOldSubtitle( $oldid );
604 } else {
605 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
607 $outputPage->addParserOutput( $this->mParserOutput );
608 # Ensure that UI elements requiring revision ID have
609 # the correct version information.
610 $outputPage->setRevisionId( $this->mPage->getLatest() );
611 # Preload timestamp to avoid a DB hit
612 $cachedTimestamp = $this->mParserOutput->getTimestamp();
613 if ( $cachedTimestamp !== null ) {
614 $outputPage->setRevisionTimestamp( $cachedTimestamp );
615 $this->mPage->setTimestamp( $cachedTimestamp );
617 $outputDone = true;
620 break;
621 case 3:
622 # This will set $this->mRevision if needed
623 $this->fetchContentObject();
625 # Are we looking at an old revision
626 if ( $oldid && $this->mRevision ) {
627 $this->setOldSubtitle( $oldid );
629 if ( !$this->showDeletedRevisionHeader() ) {
630 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
631 return;
635 # Ensure that UI elements requiring revision ID have
636 # the correct version information.
637 $outputPage->setRevisionId( $this->getRevIdFetched() );
638 # Preload timestamp to avoid a DB hit
639 $outputPage->setRevisionTimestamp( $this->getTimestamp() );
641 # Pages containing custom CSS or JavaScript get special treatment
642 if ( $this->getTitle()->isCssOrJsPage() || $this->getTitle()->isCssJsSubpage() ) {
643 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
644 $this->showCssOrJsPage();
645 $outputDone = true;
646 } elseif ( !Hooks::run( 'ArticleContentViewCustom',
647 array( $this->fetchContentObject(), $this->getTitle(), $outputPage ) ) ) {
649 # Allow extensions do their own custom view for certain pages
650 $outputDone = true;
651 } elseif ( !ContentHandler::runLegacyHooks( 'ArticleViewCustom',
652 array( $this->fetchContentObject(), $this->getTitle(), $outputPage ) ) ) {
654 # Allow extensions do their own custom view for certain pages
655 $outputDone = true;
657 break;
658 case 4:
659 # Run the parse, protected by a pool counter
660 wfDebug( __METHOD__ . ": doing uncached parse\n" );
662 $content = $this->getContentObject();
663 $poolArticleView = new PoolWorkArticleView( $this->getPage(), $parserOptions,
664 $this->getRevIdFetched(), $useParserCache, $content );
666 if ( !$poolArticleView->execute() ) {
667 $error = $poolArticleView->getError();
668 if ( $error ) {
669 $outputPage->clearHTML(); // for release() errors
670 $outputPage->enableClientCache( false );
671 $outputPage->setRobotPolicy( 'noindex,nofollow' );
673 $errortext = $error->getWikiText( false, 'view-pool-error' );
674 $outputPage->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
676 # Connection or timeout error
677 return;
680 $this->mParserOutput = $poolArticleView->getParserOutput();
681 $outputPage->addParserOutput( $this->mParserOutput );
682 if ( $content->getRedirectTarget() ) {
683 $outputPage->addSubtitle( "<span id=\"redirectsub\">" .
684 $this->getContext()->msg( 'redirectpagesub' )->parse() . "</span>" );
687 # Don't cache a dirty ParserOutput object
688 if ( $poolArticleView->getIsDirty() ) {
689 $outputPage->setCdnMaxage( 0 );
690 $outputPage->addHTML( "<!-- parser cache is expired, " .
691 "sending anyway due to pool overload-->\n" );
694 $outputDone = true;
695 break;
696 # Should be unreachable, but just in case...
697 default:
698 break 2;
702 # Get the ParserOutput actually *displayed* here.
703 # Note that $this->mParserOutput is the *current*/oldid version output.
704 $pOutput = ( $outputDone instanceof ParserOutput )
705 ? $outputDone // object fetched by hook
706 : $this->mParserOutput;
708 # Adjust title for main page & pages with displaytitle
709 if ( $pOutput ) {
710 $this->adjustDisplayTitle( $pOutput );
713 # For the main page, overwrite the <title> element with the con-
714 # tents of 'pagetitle-view-mainpage' instead of the default (if
715 # that's not empty).
716 # This message always exists because it is in the i18n files
717 if ( $this->getTitle()->isMainPage() ) {
718 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
719 if ( !$msg->isDisabled() ) {
720 $outputPage->setHTMLTitle( $msg->title( $this->getTitle() )->text() );
724 # Check for any __NOINDEX__ tags on the page using $pOutput
725 $policy = $this->getRobotPolicy( 'view', $pOutput );
726 $outputPage->setIndexPolicy( $policy['index'] );
727 $outputPage->setFollowPolicy( $policy['follow'] );
729 $this->showViewFooter();
730 $this->mPage->doViewUpdates( $user, $oldid );
732 $outputPage->addModules( 'mediawiki.action.view.postEdit' );
737 * Adjust title for pages with displaytitle, -{T|}- or language conversion
738 * @param ParserOutput $pOutput
740 public function adjustDisplayTitle( ParserOutput $pOutput ) {
741 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
742 $titleText = $pOutput->getTitleText();
743 if ( strval( $titleText ) !== '' ) {
744 $this->getContext()->getOutput()->setPageTitle( $titleText );
749 * Show a diff page according to current request variables. For use within
750 * Article::view() only, other callers should use the DifferenceEngine class.
753 protected function showDiffPage() {
754 $request = $this->getContext()->getRequest();
755 $user = $this->getContext()->getUser();
756 $diff = $request->getVal( 'diff' );
757 $rcid = $request->getVal( 'rcid' );
758 $diffOnly = $request->getBool( 'diffonly', $user->getOption( 'diffonly' ) );
759 $purge = $request->getVal( 'action' ) == 'purge';
760 $unhide = $request->getInt( 'unhide' ) == 1;
761 $oldid = $this->getOldID();
763 $rev = $this->getRevisionFetched();
765 if ( !$rev ) {
766 $this->getContext()->getOutput()->setPageTitle( wfMessage( 'errorpagetitle' ) );
767 $msg = $this->getContext()->msg( 'difference-missing-revision' )
768 ->params( $oldid )
769 ->numParams( 1 )
770 ->parseAsBlock();
771 $this->getContext()->getOutput()->addHtml( $msg );
772 return;
775 $contentHandler = $rev->getContentHandler();
776 $de = $contentHandler->createDifferenceEngine(
777 $this->getContext(),
778 $oldid,
779 $diff,
780 $rcid,
781 $purge,
782 $unhide
785 // DifferenceEngine directly fetched the revision:
786 $this->mRevIdFetched = $de->mNewid;
787 $de->showDiffPage( $diffOnly );
789 // Run view updates for the newer revision being diffed (and shown
790 // below the diff if not $diffOnly).
791 list( $old, $new ) = $de->mapDiffPrevNext( $oldid, $diff );
792 // New can be false, convert it to 0 - this conveniently means the latest revision
793 $this->mPage->doViewUpdates( $user, (int)$new );
797 * Show a page view for a page formatted as CSS or JavaScript. To be called by
798 * Article::view() only.
800 * This exists mostly to serve the deprecated ShowRawCssJs hook (used to customize these views).
801 * It has been replaced by the ContentGetParserOutput hook, which lets you do the same but with
802 * more flexibility.
804 * @param bool $showCacheHint Whether to show a message telling the user
805 * to clear the browser cache (default: true).
807 protected function showCssOrJsPage( $showCacheHint = true ) {
808 $outputPage = $this->getContext()->getOutput();
810 if ( $showCacheHint ) {
811 $dir = $this->getContext()->getLanguage()->getDir();
812 $lang = $this->getContext()->getLanguage()->getHtmlCode();
814 $outputPage->wrapWikiMsg(
815 "<div id='mw-clearyourcache' lang='$lang' dir='$dir' class='mw-content-$dir'>\n$1\n</div>",
816 'clearyourcache'
820 $this->fetchContentObject();
822 if ( $this->mContentObject ) {
823 // Give hooks a chance to customise the output
824 if ( ContentHandler::runLegacyHooks(
825 'ShowRawCssJs',
826 array( $this->mContentObject, $this->getTitle(), $outputPage ) )
828 // If no legacy hooks ran, display the content of the parser output, including RL modules,
829 // but excluding metadata like categories and language links
830 $po = $this->mContentObject->getParserOutput( $this->getTitle() );
831 $outputPage->addParserOutputContent( $po );
837 * Get the robot policy to be used for the current view
838 * @param string $action The action= GET parameter
839 * @param ParserOutput|null $pOutput
840 * @return array The policy that should be set
841 * @todo actions other than 'view'
843 public function getRobotPolicy( $action, $pOutput = null ) {
844 global $wgArticleRobotPolicies, $wgNamespaceRobotPolicies, $wgDefaultRobotPolicy;
846 $ns = $this->getTitle()->getNamespace();
848 # Don't index user and user talk pages for blocked users (bug 11443)
849 if ( ( $ns == NS_USER || $ns == NS_USER_TALK ) && !$this->getTitle()->isSubpage() ) {
850 $specificTarget = null;
851 $vagueTarget = null;
852 $titleText = $this->getTitle()->getText();
853 if ( IP::isValid( $titleText ) ) {
854 $vagueTarget = $titleText;
855 } else {
856 $specificTarget = $titleText;
858 if ( Block::newFromTarget( $specificTarget, $vagueTarget ) instanceof Block ) {
859 return array(
860 'index' => 'noindex',
861 'follow' => 'nofollow'
866 if ( $this->mPage->getID() === 0 || $this->getOldID() ) {
867 # Non-articles (special pages etc), and old revisions
868 return array(
869 'index' => 'noindex',
870 'follow' => 'nofollow'
872 } elseif ( $this->getContext()->getOutput()->isPrintable() ) {
873 # Discourage indexing of printable versions, but encourage following
874 return array(
875 'index' => 'noindex',
876 'follow' => 'follow'
878 } elseif ( $this->getContext()->getRequest()->getInt( 'curid' ) ) {
879 # For ?curid=x urls, disallow indexing
880 return array(
881 'index' => 'noindex',
882 'follow' => 'follow'
886 # Otherwise, construct the policy based on the various config variables.
887 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
889 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
890 # Honour customised robot policies for this namespace
891 $policy = array_merge(
892 $policy,
893 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
896 if ( $this->getTitle()->canUseNoindex() && is_object( $pOutput ) && $pOutput->getIndexPolicy() ) {
897 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
898 # a final sanity check that we have really got the parser output.
899 $policy = array_merge(
900 $policy,
901 array( 'index' => $pOutput->getIndexPolicy() )
905 if ( isset( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] ) ) {
906 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
907 $policy = array_merge(
908 $policy,
909 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] )
913 return $policy;
917 * Converts a String robot policy into an associative array, to allow
918 * merging of several policies using array_merge().
919 * @param array|string $policy Returns empty array on null/false/'', transparent
920 * to already-converted arrays, converts string.
921 * @return array 'index' => \<indexpolicy\>, 'follow' => \<followpolicy\>
923 public static function formatRobotPolicy( $policy ) {
924 if ( is_array( $policy ) ) {
925 return $policy;
926 } elseif ( !$policy ) {
927 return array();
930 $policy = explode( ',', $policy );
931 $policy = array_map( 'trim', $policy );
933 $arr = array();
934 foreach ( $policy as $var ) {
935 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
936 $arr['index'] = $var;
937 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
938 $arr['follow'] = $var;
942 return $arr;
946 * If this request is a redirect view, send "redirected from" subtitle to
947 * the output. Returns true if the header was needed, false if this is not
948 * a redirect view. Handles both local and remote redirects.
950 * @return bool
952 public function showRedirectedFromHeader() {
953 global $wgRedirectSources;
955 $context = $this->getContext();
956 $outputPage = $context->getOutput();
957 $request = $context->getRequest();
958 $rdfrom = $request->getVal( 'rdfrom' );
960 // Construct a URL for the current page view, but with the target title
961 $query = $request->getValues();
962 unset( $query['rdfrom'] );
963 unset( $query['title'] );
964 if ( $this->getTitle()->isRedirect() ) {
965 // Prevent double redirects
966 $query['redirect'] = 'no';
968 $redirectTargetUrl = $this->getTitle()->getLinkURL( $query );
970 if ( isset( $this->mRedirectedFrom ) ) {
971 // This is an internally redirected page view.
972 // We'll need a backlink to the source page for navigation.
973 if ( Hooks::run( 'ArticleViewRedirect', array( &$this ) ) ) {
974 $redir = Linker::linkKnown(
975 $this->mRedirectedFrom,
976 null,
977 array(),
978 array( 'redirect' => 'no' )
981 $outputPage->addSubtitle( "<span class=\"mw-redirectedfrom\">" .
982 $context->msg( 'redirectedfrom' )->rawParams( $redir )->parse()
983 . "</span>" );
985 // Add the script to update the displayed URL and
986 // set the fragment if one was specified in the redirect
987 $outputPage->addJsConfigVars( array(
988 'wgInternalRedirectTargetUrl' => $redirectTargetUrl,
989 ) );
990 $outputPage->addModules( 'mediawiki.action.view.redirect' );
992 // Add a <link rel="canonical"> tag
993 $outputPage->setCanonicalUrl( $this->getTitle()->getCanonicalURL() );
995 // Tell the output object that the user arrived at this article through a redirect
996 $outputPage->setRedirectedFrom( $this->mRedirectedFrom );
998 return true;
1000 } elseif ( $rdfrom ) {
1001 // This is an externally redirected view, from some other wiki.
1002 // If it was reported from a trusted site, supply a backlink.
1003 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1004 $redir = Linker::makeExternalLink( $rdfrom, $rdfrom );
1005 $outputPage->addSubtitle( "<span class=\"mw-redirectedfrom\">" .
1006 $context->msg( 'redirectedfrom' )->rawParams( $redir )->parse()
1007 . "</span>" );
1009 // Add the script to update the displayed URL
1010 $outputPage->addJsConfigVars( array(
1011 'wgInternalRedirectTargetUrl' => $redirectTargetUrl,
1012 ) );
1013 $outputPage->addModules( 'mediawiki.action.view.redirect' );
1015 return true;
1019 return false;
1023 * Show a header specific to the namespace currently being viewed, like
1024 * [[MediaWiki:Talkpagetext]]. For Article::view().
1026 public function showNamespaceHeader() {
1027 if ( $this->getTitle()->isTalkPage() ) {
1028 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1029 $this->getContext()->getOutput()->wrapWikiMsg(
1030 "<div class=\"mw-talkpageheader\">\n$1\n</div>",
1031 array( 'talkpageheader' )
1038 * Show the footer section of an ordinary page view
1040 public function showViewFooter() {
1041 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1042 if ( $this->getTitle()->getNamespace() == NS_USER_TALK
1043 && IP::isValid( $this->getTitle()->getText() )
1045 $this->getContext()->getOutput()->addWikiMsg( 'anontalkpagetext' );
1048 // Show a footer allowing the user to patrol the shown revision or page if possible
1049 $patrolFooterShown = $this->showPatrolFooter();
1051 Hooks::run( 'ArticleViewFooter', array( $this, $patrolFooterShown ) );
1055 * If patrol is possible, output a patrol UI box. This is called from the
1056 * footer section of ordinary page views. If patrol is not possible or not
1057 * desired, does nothing.
1058 * Side effect: When the patrol link is build, this method will call
1059 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
1061 * @return bool
1063 public function showPatrolFooter() {
1064 global $wgUseNPPatrol, $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
1066 $outputPage = $this->getContext()->getOutput();
1067 $user = $this->getContext()->getUser();
1068 $rc = false;
1070 if ( !$this->getTitle()->quickUserCan( 'patrol', $user )
1071 || !( $wgUseRCPatrol || $wgUseNPPatrol )
1073 // Patrolling is disabled or the user isn't allowed to
1074 return false;
1077 // New page patrol: Get the timestamp of the oldest revison which
1078 // the revision table holds for the given page. Then we look
1079 // whether it's within the RC lifespan and if it is, we try
1080 // to get the recentchanges row belonging to that entry
1081 // (with rc_new = 1).
1083 if ( $this->mRevision
1084 && !RecentChange::isInRCLifespan( $this->mRevision->getTimestamp(), 21600 )
1086 // The current revision is already older than what could be in the RC table
1087 // 6h tolerance because the RC might not be cleaned out regularly
1088 return false;
1091 // Check for cached results
1092 $key = wfMemcKey( 'unpatrollable-page', $this->getTitle()->getArticleID() );
1093 $cache = ObjectCache::getMainWANInstance();
1094 if ( $cache->get( $key ) ) {
1095 return false;
1098 $dbr = wfGetDB( DB_SLAVE );
1099 $oldestRevisionTimestamp = $dbr->selectField(
1100 'revision',
1101 'MIN( rev_timestamp )',
1102 array( 'rev_page' => $this->getTitle()->getArticleID() ),
1103 __METHOD__
1106 if ( $oldestRevisionTimestamp
1107 && RecentChange::isInRCLifespan( $oldestRevisionTimestamp, 21600 )
1109 // 6h tolerance because the RC might not be cleaned out regularly
1110 $rc = RecentChange::newFromConds(
1111 array(
1112 'rc_new' => 1,
1113 'rc_timestamp' => $oldestRevisionTimestamp,
1114 'rc_namespace' => $this->getTitle()->getNamespace(),
1115 'rc_cur_id' => $this->getTitle()->getArticleID()
1117 __METHOD__
1119 } else {
1120 // Cache the information we gathered above in case we can't patrol
1121 // Don't cache in case we can patrol as this could change
1122 $cache->set( $key, '1' );
1125 if ( !$rc ) {
1126 // Don't cache: This can be hit if the page gets accessed very fast after
1127 // its creation or in case we have high slave lag. In case the revision is
1128 // too old, we will already return above.
1129 return false;
1132 if ( $rc->getAttribute( 'rc_patrolled' ) ) {
1133 // Patrolled RC entry around
1135 // Cache the information we gathered above in case we can't patrol
1136 // Don't cache in case we can patrol as this could change
1137 $cache->set( $key, '1' );
1139 return false;
1142 if ( $rc->getPerformer()->equals( $user ) ) {
1143 // Don't show a patrol link for own creations. If the user could
1144 // patrol them, they already would be patrolled
1145 return false;
1148 $rcid = $rc->getAttribute( 'rc_id' );
1150 $token = $user->getEditToken( $rcid );
1152 $outputPage->preventClickjacking();
1153 if ( $wgEnableAPI && $wgEnableWriteAPI && $user->isAllowed( 'writeapi' ) ) {
1154 $outputPage->addModules( 'mediawiki.page.patrol.ajax' );
1157 $link = Linker::linkKnown(
1158 $this->getTitle(),
1159 wfMessage( 'markaspatrolledtext' )->escaped(),
1160 array(),
1161 array(
1162 'action' => 'markpatrolled',
1163 'rcid' => $rcid,
1164 'token' => $token,
1168 $outputPage->addHTML(
1169 "<div class='patrollink'>" .
1170 wfMessage( 'markaspatrolledlink' )->rawParams( $link )->escaped() .
1171 '</div>'
1174 return true;
1178 * Show the error text for a missing article. For articles in the MediaWiki
1179 * namespace, show the default message text. To be called from Article::view().
1181 public function showMissingArticle() {
1182 global $wgSend404Code;
1184 $outputPage = $this->getContext()->getOutput();
1185 // Whether the page is a root user page of an existing user (but not a subpage)
1186 $validUserPage = false;
1188 $title = $this->getTitle();
1190 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1191 if ( $title->getNamespace() == NS_USER
1192 || $title->getNamespace() == NS_USER_TALK
1194 $parts = explode( '/', $title->getText() );
1195 $rootPart = $parts[0];
1196 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1197 $ip = User::isIP( $rootPart );
1198 $block = Block::newFromTarget( $user, $user );
1200 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1201 $outputPage->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1202 array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
1203 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
1204 # Show log extract if the user is currently blocked
1205 LogEventsList::showLogExtract(
1206 $outputPage,
1207 'block',
1208 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
1210 array(
1211 'lim' => 1,
1212 'showIfEmpty' => false,
1213 'msgKey' => array(
1214 'blocked-notice-logextract',
1215 $user->getName() # Support GENDER in notice
1219 $validUserPage = !$title->isSubpage();
1220 } else {
1221 $validUserPage = !$title->isSubpage();
1225 Hooks::run( 'ShowMissingArticle', array( $this ) );
1227 # Show delete and move logs if there were any such events.
1228 # The logging query can DOS the site when bots/crawlers cause 404 floods,
1229 # so be careful showing this. 404 pages must be cheap as they are hard to cache.
1230 $cache = ObjectCache::getMainStashInstance();
1231 $key = wfMemcKey( 'page-recent-delete', md5( $title->getPrefixedText() ) );
1232 $loggedIn = $this->getContext()->getUser()->isLoggedIn();
1233 if ( $loggedIn || $cache->get( $key ) ) {
1234 $logTypes = array( 'delete', 'move' );
1235 $conds = array( "log_action != 'revision'" );
1236 // Give extensions a chance to hide their (unrelated) log entries
1237 Hooks::run( 'Article::MissingArticleConditions', array( &$conds, $logTypes ) );
1238 LogEventsList::showLogExtract(
1239 $outputPage,
1240 $logTypes,
1241 $title,
1243 array(
1244 'lim' => 10,
1245 'conds' => $conds,
1246 'showIfEmpty' => false,
1247 'msgKey' => array( $loggedIn
1248 ? 'moveddeleted-notice'
1249 : 'moveddeleted-notice-recent'
1255 if ( !$this->mPage->hasViewableContent() && $wgSend404Code && !$validUserPage ) {
1256 // If there's no backing content, send a 404 Not Found
1257 // for better machine handling of broken links.
1258 $this->getContext()->getRequest()->response()->statusHeader( 404 );
1261 // Also apply the robot policy for nonexisting pages (even if a 404 was used for sanity)
1262 $policy = $this->getRobotPolicy( 'view' );
1263 $outputPage->setIndexPolicy( $policy['index'] );
1264 $outputPage->setFollowPolicy( $policy['follow'] );
1266 $hookResult = Hooks::run( 'BeforeDisplayNoArticleText', array( $this ) );
1268 if ( !$hookResult ) {
1269 return;
1272 # Show error message
1273 $oldid = $this->getOldID();
1274 if ( !$oldid && $title->getNamespace() === NS_MEDIAWIKI && $title->hasSourceText() ) {
1275 $outputPage->addParserOutput( $this->getContentObject()->getParserOutput( $title ) );
1276 } else {
1277 if ( $oldid ) {
1278 $text = wfMessage( 'missing-revision', $oldid )->plain();
1279 } elseif ( $title->quickUserCan( 'create', $this->getContext()->getUser() )
1280 && $title->quickUserCan( 'edit', $this->getContext()->getUser() )
1282 $message = $this->getContext()->getUser()->isLoggedIn() ? 'noarticletext' : 'noarticletextanon';
1283 $text = wfMessage( $message )->plain();
1284 } else {
1285 $text = wfMessage( 'noarticletext-nopermission' )->plain();
1288 $dir = $this->getContext()->getLanguage()->getDir();
1289 $lang = $this->getContext()->getLanguage()->getCode();
1290 $outputPage->addWikiText( Xml::openElement( 'div', array(
1291 'class' => "noarticletext mw-content-$dir",
1292 'dir' => $dir,
1293 'lang' => $lang,
1294 ) ) . "\n$text\n</div>" );
1299 * If the revision requested for view is deleted, check permissions.
1300 * Send either an error message or a warning header to the output.
1302 * @return bool True if the view is allowed, false if not.
1304 public function showDeletedRevisionHeader() {
1305 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1306 // Not deleted
1307 return true;
1310 $outputPage = $this->getContext()->getOutput();
1311 $user = $this->getContext()->getUser();
1312 // If the user is not allowed to see it...
1313 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT, $user ) ) {
1314 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1315 'rev-deleted-text-permission' );
1317 return false;
1318 // If the user needs to confirm that they want to see it...
1319 } elseif ( $this->getContext()->getRequest()->getInt( 'unhide' ) != 1 ) {
1320 # Give explanation and add a link to view the revision...
1321 $oldid = intval( $this->getOldID() );
1322 $link = $this->getTitle()->getFullURL( "oldid={$oldid}&unhide=1" );
1323 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1324 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1325 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1326 array( $msg, $link ) );
1328 return false;
1329 // We are allowed to see...
1330 } else {
1331 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1332 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1333 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1335 return true;
1340 * Generate the navigation links when browsing through an article revisions
1341 * It shows the information as:
1342 * Revision as of \<date\>; view current revision
1343 * \<- Previous version | Next Version -\>
1345 * @param int $oldid Revision ID of this article revision
1347 public function setOldSubtitle( $oldid = 0 ) {
1348 if ( !Hooks::run( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
1349 return;
1352 $context = $this->getContext();
1353 $unhide = $context->getRequest()->getInt( 'unhide' ) == 1;
1355 # Cascade unhide param in links for easy deletion browsing
1356 $extraParams = array();
1357 if ( $unhide ) {
1358 $extraParams['unhide'] = 1;
1361 if ( $this->mRevision && $this->mRevision->getId() === $oldid ) {
1362 $revision = $this->mRevision;
1363 } else {
1364 $revision = Revision::newFromId( $oldid );
1367 $timestamp = $revision->getTimestamp();
1369 $current = ( $oldid == $this->mPage->getLatest() );
1370 $language = $context->getLanguage();
1371 $user = $context->getUser();
1373 $td = $language->userTimeAndDate( $timestamp, $user );
1374 $tddate = $language->userDate( $timestamp, $user );
1375 $tdtime = $language->userTime( $timestamp, $user );
1377 # Show user links if allowed to see them. If hidden, then show them only if requested...
1378 $userlinks = Linker::revUserTools( $revision, !$unhide );
1380 $infomsg = $current && !$context->msg( 'revision-info-current' )->isDisabled()
1381 ? 'revision-info-current'
1382 : 'revision-info';
1384 $outputPage = $context->getOutput();
1385 $outputPage->addSubtitle( "<div id=\"mw-{$infomsg}\">" .
1386 $context->msg( $infomsg, $td )
1387 ->rawParams( $userlinks )
1388 ->params( $revision->getID(), $tddate, $tdtime, $revision->getUserText() )
1389 ->rawParams( Linker::revComment( $revision, true, true ) )
1390 ->parse() .
1391 "</div>"
1394 $lnk = $current
1395 ? $context->msg( 'currentrevisionlink' )->escaped()
1396 : Linker::linkKnown(
1397 $this->getTitle(),
1398 $context->msg( 'currentrevisionlink' )->escaped(),
1399 array(),
1400 $extraParams
1402 $curdiff = $current
1403 ? $context->msg( 'diff' )->escaped()
1404 : Linker::linkKnown(
1405 $this->getTitle(),
1406 $context->msg( 'diff' )->escaped(),
1407 array(),
1408 array(
1409 'diff' => 'cur',
1410 'oldid' => $oldid
1411 ) + $extraParams
1413 $prev = $this->getTitle()->getPreviousRevisionID( $oldid );
1414 $prevlink = $prev
1415 ? Linker::linkKnown(
1416 $this->getTitle(),
1417 $context->msg( 'previousrevision' )->escaped(),
1418 array(),
1419 array(
1420 'direction' => 'prev',
1421 'oldid' => $oldid
1422 ) + $extraParams
1424 : $context->msg( 'previousrevision' )->escaped();
1425 $prevdiff = $prev
1426 ? Linker::linkKnown(
1427 $this->getTitle(),
1428 $context->msg( 'diff' )->escaped(),
1429 array(),
1430 array(
1431 'diff' => 'prev',
1432 'oldid' => $oldid
1433 ) + $extraParams
1435 : $context->msg( 'diff' )->escaped();
1436 $nextlink = $current
1437 ? $context->msg( 'nextrevision' )->escaped()
1438 : Linker::linkKnown(
1439 $this->getTitle(),
1440 $context->msg( 'nextrevision' )->escaped(),
1441 array(),
1442 array(
1443 'direction' => 'next',
1444 'oldid' => $oldid
1445 ) + $extraParams
1447 $nextdiff = $current
1448 ? $context->msg( 'diff' )->escaped()
1449 : Linker::linkKnown(
1450 $this->getTitle(),
1451 $context->msg( 'diff' )->escaped(),
1452 array(),
1453 array(
1454 'diff' => 'next',
1455 'oldid' => $oldid
1456 ) + $extraParams
1459 $cdel = Linker::getRevDeleteLink( $user, $revision, $this->getTitle() );
1460 if ( $cdel !== '' ) {
1461 $cdel .= ' ';
1464 $outputPage->addSubtitle( "<div id=\"mw-revision-nav\">" . $cdel .
1465 $context->msg( 'revision-nav' )->rawParams(
1466 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff
1467 )->escaped() . "</div>" );
1471 * Return the HTML for the top of a redirect page
1473 * Chances are you should just be using the ParserOutput from
1474 * WikitextContent::getParserOutput instead of calling this for redirects.
1476 * @param Title|array $target Destination(s) to redirect
1477 * @param bool $appendSubtitle [optional]
1478 * @param bool $forceKnown Should the image be shown as a bluelink regardless of existence?
1479 * @return string Containing HTML with redirect link
1481 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1482 $lang = $this->getTitle()->getPageLanguage();
1483 $out = $this->getContext()->getOutput();
1484 if ( $appendSubtitle ) {
1485 $out->addSubtitle( wfMessage( 'redirectpagesub' ) );
1487 $out->addModuleStyles( 'mediawiki.action.view.redirectPage' );
1488 return static::getRedirectHeaderHtml( $lang, $target, $forceKnown );
1492 * Return the HTML for the top of a redirect page
1494 * Chances are you should just be using the ParserOutput from
1495 * WikitextContent::getParserOutput instead of calling this for redirects.
1497 * @since 1.23
1498 * @param Language $lang
1499 * @param Title|array $target Destination(s) to redirect
1500 * @param bool $forceKnown Should the image be shown as a bluelink regardless of existence?
1501 * @return string Containing HTML with redirect link
1503 public static function getRedirectHeaderHtml( Language $lang, $target, $forceKnown = false ) {
1504 if ( !is_array( $target ) ) {
1505 $target = array( $target );
1508 $html = '<ul class="redirectText">';
1509 /** @var Title $title */
1510 foreach ( $target as $title ) {
1511 $html .= '<li>' . Linker::link(
1512 $title,
1513 htmlspecialchars( $title->getFullText() ),
1514 array(),
1515 // Automatically append redirect=no to each link, since most of them are
1516 // redirect pages themselves.
1517 array( 'redirect' => 'no' ),
1518 ( $forceKnown ? array( 'known', 'noclasses' ) : array() )
1519 ) . '</li>';
1521 $html .= '</ul>';
1523 $redirectToText = wfMessage( 'redirectto' )->inLanguage( $lang )->escaped();
1525 return '<div class="redirectMsg">' .
1526 '<p>' . $redirectToText . '</p>' .
1527 $html .
1528 '</div>';
1532 * Adds help link with an icon via page indicators.
1533 * Link target can be overridden by a local message containing a wikilink:
1534 * the message key is: 'namespace-' + namespace number + '-helppage'.
1535 * @param string $to Target MediaWiki.org page title or encoded URL.
1536 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1537 * @since 1.25
1539 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1540 $msg = wfMessage(
1541 'namespace-' . $this->getTitle()->getNamespace() . '-helppage'
1544 $out = $this->getContext()->getOutput();
1545 if ( !$msg->isDisabled() ) {
1546 $helpUrl = Skin::makeUrl( $msg->plain() );
1547 $out->addHelpLink( $helpUrl, true );
1548 } else {
1549 $out->addHelpLink( $to, $overrideBaseUrl );
1554 * Handle action=render
1556 public function render() {
1557 $this->getContext()->getRequest()->response()->header( 'X-Robots-Tag: noindex' );
1558 $this->getContext()->getOutput()->setArticleBodyOnly( true );
1559 $this->getContext()->getOutput()->enableSectionEditLinks( false );
1560 $this->view();
1564 * action=protect handler
1566 public function protect() {
1567 $form = new ProtectionForm( $this );
1568 $form->execute();
1572 * action=unprotect handler (alias)
1574 public function unprotect() {
1575 $this->protect();
1579 * UI entry point for page deletion
1581 public function delete() {
1582 # This code desperately needs to be totally rewritten
1584 $title = $this->getTitle();
1585 $context = $this->getContext();
1586 $user = $context->getUser();
1588 # Check permissions
1589 $permissionErrors = $title->getUserPermissionsErrors( 'delete', $user );
1590 if ( count( $permissionErrors ) ) {
1591 throw new PermissionsError( 'delete', $permissionErrors );
1594 # Read-only check...
1595 if ( wfReadOnly() ) {
1596 throw new ReadOnlyError;
1599 # Better double-check that it hasn't been deleted yet!
1600 $this->mPage->loadPageData( 'fromdbmaster' );
1601 if ( !$this->mPage->exists() ) {
1602 $deleteLogPage = new LogPage( 'delete' );
1603 $outputPage = $context->getOutput();
1604 $outputPage->setPageTitle( $context->msg( 'cannotdelete-title', $title->getPrefixedText() ) );
1605 $outputPage->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1606 array( 'cannotdelete', wfEscapeWikiText( $title->getPrefixedText() ) )
1608 $outputPage->addHTML(
1609 Xml::element( 'h2', null, $deleteLogPage->getName()->text() )
1611 LogEventsList::showLogExtract(
1612 $outputPage,
1613 'delete',
1614 $title
1617 return;
1620 $request = $context->getRequest();
1621 $deleteReasonList = $request->getText( 'wpDeleteReasonList', 'other' );
1622 $deleteReason = $request->getText( 'wpReason' );
1624 if ( $deleteReasonList == 'other' ) {
1625 $reason = $deleteReason;
1626 } elseif ( $deleteReason != '' ) {
1627 // Entry from drop down menu + additional comment
1628 $colonseparator = wfMessage( 'colon-separator' )->inContentLanguage()->text();
1629 $reason = $deleteReasonList . $colonseparator . $deleteReason;
1630 } else {
1631 $reason = $deleteReasonList;
1634 if ( $request->wasPosted() && $user->matchEditToken( $request->getVal( 'wpEditToken' ),
1635 array( 'delete', $this->getTitle()->getPrefixedText() ) )
1637 # Flag to hide all contents of the archived revisions
1638 $suppress = $request->getVal( 'wpSuppress' ) && $user->isAllowed( 'suppressrevision' );
1640 $this->doDelete( $reason, $suppress );
1642 WatchAction::doWatchOrUnwatch( $request->getCheck( 'wpWatch' ), $title, $user );
1644 return;
1647 // Generate deletion reason
1648 $hasHistory = false;
1649 if ( !$reason ) {
1650 try {
1651 $reason = $this->generateReason( $hasHistory );
1652 } catch ( Exception $e ) {
1653 # if a page is horribly broken, we still want to be able to
1654 # delete it. So be lenient about errors here.
1655 wfDebug( "Error while building auto delete summary: $e" );
1656 $reason = '';
1660 // If the page has a history, insert a warning
1661 if ( $hasHistory ) {
1662 $title = $this->getTitle();
1664 // The following can use the real revision count as this is only being shown for users
1665 // that can delete this page.
1666 // This, as a side-effect, also makes sure that the following query isn't being run for
1667 // pages with a larger history, unless the user has the 'bigdelete' right
1668 // (and is about to delete this page).
1669 $dbr = wfGetDB( DB_SLAVE );
1670 $revisions = $edits = (int)$dbr->selectField(
1671 'revision',
1672 'COUNT(rev_page)',
1673 array( 'rev_page' => $title->getArticleID() ),
1674 __METHOD__
1677 // @todo FIXME: i18n issue/patchwork message
1678 $context->getOutput()->addHTML(
1679 '<strong class="mw-delete-warning-revisions">' .
1680 $context->msg( 'historywarning' )->numParams( $revisions )->parse() .
1681 $context->msg( 'word-separator' )->escaped() . Linker::linkKnown( $title,
1682 $context->msg( 'history' )->escaped(),
1683 array(),
1684 array( 'action' => 'history' ) ) .
1685 '</strong>'
1688 if ( $title->isBigDeletion() ) {
1689 global $wgDeleteRevisionsLimit;
1690 $context->getOutput()->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1691 array(
1692 'delete-warning-toobig',
1693 $context->getLanguage()->formatNum( $wgDeleteRevisionsLimit )
1699 $this->confirmDelete( $reason );
1703 * Output deletion confirmation dialog
1704 * @todo FIXME: Move to another file?
1705 * @param string $reason Prefilled reason
1707 public function confirmDelete( $reason ) {
1708 wfDebug( "Article::confirmDelete\n" );
1710 $title = $this->getTitle();
1711 $ctx = $this->getContext();
1712 $outputPage = $ctx->getOutput();
1713 $useMediaWikiUIEverywhere = $ctx->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1714 $outputPage->setPageTitle( wfMessage( 'delete-confirm', $title->getPrefixedText() ) );
1715 $outputPage->addBacklinkSubtitle( $title );
1716 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1717 $backlinkCache = $title->getBacklinkCache();
1718 if ( $backlinkCache->hasLinks( 'pagelinks' ) || $backlinkCache->hasLinks( 'templatelinks' ) ) {
1719 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1720 'deleting-backlinks-warning' );
1722 $outputPage->addWikiMsg( 'confirmdeletetext' );
1724 Hooks::run( 'ArticleConfirmDelete', array( $this, $outputPage, &$reason ) );
1726 $user = $this->getContext()->getUser();
1728 if ( $user->isAllowed( 'suppressrevision' ) ) {
1729 $suppress = Html::openElement( 'div', array( 'id' => 'wpDeleteSuppressRow' ) ) .
1730 Xml::checkLabel( wfMessage( 'revdelete-suppress' )->text(),
1731 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
1732 Html::closeElement( 'div' );
1733 } else {
1734 $suppress = '';
1736 $checkWatch = $user->getBoolOption( 'watchdeletion' ) || $user->isWatched( $title );
1738 $form = Html::openElement( 'form', array( 'method' => 'post',
1739 'action' => $title->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
1740 Html::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
1741 Html::element( 'legend', null, wfMessage( 'delete-legend' )->text() ) .
1742 Html::openElement( 'div', array( 'id' => 'mw-deleteconfirm-table' ) ) .
1743 Html::openElement( 'div', array( 'id' => 'wpDeleteReasonListRow' ) ) .
1744 Html::label( wfMessage( 'deletecomment' )->text(), 'wpDeleteReasonList' ) .
1745 '&nbsp;' .
1746 Xml::listDropDown(
1747 'wpDeleteReasonList',
1748 wfMessage( 'deletereason-dropdown' )->inContentLanguage()->text(),
1749 wfMessage( 'deletereasonotherlist' )->inContentLanguage()->text(),
1751 'wpReasonDropDown',
1754 Html::closeElement( 'div' ) .
1755 Html::openElement( 'div', array( 'id' => 'wpDeleteReasonRow' ) ) .
1756 Html::label( wfMessage( 'deleteotherreason' )->text(), 'wpReason' ) .
1757 '&nbsp;' .
1758 Html::input( 'wpReason', $reason, 'text', array(
1759 'size' => '60',
1760 'maxlength' => '255',
1761 'tabindex' => '2',
1762 'id' => 'wpReason',
1763 'class' => 'mw-ui-input-inline',
1764 'autofocus'
1765 ) ) .
1766 Html::closeElement( 'div' );
1768 # Disallow watching if user is not logged in
1769 if ( $user->isLoggedIn() ) {
1770 $form .=
1771 Xml::checkLabel( wfMessage( 'watchthis' )->text(),
1772 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) );
1775 $form .=
1776 Html::openElement( 'div' ) .
1777 $suppress .
1778 Xml::submitButton( wfMessage( 'deletepage' )->text(),
1779 array(
1780 'name' => 'wpConfirmB',
1781 'id' => 'wpConfirmB',
1782 'tabindex' => '5',
1783 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button mw-ui-destructive' : '',
1786 Html::closeElement( 'div' ) .
1787 Html::closeElement( 'div' ) .
1788 Xml::closeElement( 'fieldset' ) .
1789 Html::hidden(
1790 'wpEditToken',
1791 $user->getEditToken( array( 'delete', $title->getPrefixedText() ) )
1793 Xml::closeElement( 'form' );
1795 if ( $user->isAllowed( 'editinterface' ) ) {
1796 $link = Linker::linkKnown(
1797 $ctx->msg( 'deletereason-dropdown' )->inContentLanguage()->getTitle(),
1798 wfMessage( 'delete-edit-reasonlist' )->escaped(),
1799 array(),
1800 array( 'action' => 'edit' )
1802 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
1805 $outputPage->addHTML( $form );
1807 $deleteLogPage = new LogPage( 'delete' );
1808 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1809 LogEventsList::showLogExtract( $outputPage, 'delete', $title );
1813 * Perform a deletion and output success or failure messages
1814 * @param string $reason
1815 * @param bool $suppress
1817 public function doDelete( $reason, $suppress = false ) {
1818 $error = '';
1819 $context = $this->getContext();
1820 $outputPage = $context->getOutput();
1821 $user = $context->getUser();
1822 $status = $this->mPage->doDeleteArticleReal( $reason, $suppress, 0, true, $error, $user );
1824 if ( $status->isGood() ) {
1825 $deleted = $this->getTitle()->getPrefixedText();
1827 $outputPage->setPageTitle( wfMessage( 'actioncomplete' ) );
1828 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1830 $loglink = '[[Special:Log/delete|' . wfMessage( 'deletionlog' )->text() . ']]';
1832 $outputPage->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1834 Hooks::run( 'ArticleDeleteAfterSuccess', array( $this->getTitle(), $outputPage ) );
1836 $outputPage->returnToMain( false );
1837 } else {
1838 $outputPage->setPageTitle(
1839 wfMessage( 'cannotdelete-title',
1840 $this->getTitle()->getPrefixedText() )
1843 if ( $error == '' ) {
1844 $outputPage->addWikiText(
1845 "<div class=\"error mw-error-cannotdelete\">\n" . $status->getWikiText() . "\n</div>"
1847 $deleteLogPage = new LogPage( 'delete' );
1848 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1850 LogEventsList::showLogExtract(
1851 $outputPage,
1852 'delete',
1853 $this->getTitle()
1855 } else {
1856 $outputPage->addHTML( $error );
1861 /* Caching functions */
1864 * checkLastModified returns true if it has taken care of all
1865 * output to the client that is necessary for this request.
1866 * (that is, it has sent a cached version of the page)
1868 * @return bool True if cached version send, false otherwise
1870 protected function tryFileCache() {
1871 static $called = false;
1873 if ( $called ) {
1874 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1875 return false;
1878 $called = true;
1879 if ( $this->isFileCacheable() ) {
1880 $cache = new HTMLFileCache( $this->getTitle(), 'view' );
1881 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1882 wfDebug( "Article::tryFileCache(): about to load file\n" );
1883 $cache->loadFromFileCache( $this->getContext() );
1884 return true;
1885 } else {
1886 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1887 ob_start( array( &$cache, 'saveToFileCache' ) );
1889 } else {
1890 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1893 return false;
1897 * Check if the page can be cached
1898 * @return bool
1900 public function isFileCacheable() {
1901 $cacheable = false;
1903 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
1904 $cacheable = $this->mPage->getID()
1905 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
1906 // Extension may have reason to disable file caching on some pages.
1907 if ( $cacheable ) {
1908 $cacheable = Hooks::run( 'IsFileCacheable', array( &$this ) );
1912 return $cacheable;
1915 /**#@-*/
1918 * Lightweight method to get the parser output for a page, checking the parser cache
1919 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1920 * consider, so it's not appropriate to use there.
1922 * @since 1.16 (r52326) for LiquidThreads
1924 * @param int|null $oldid Revision ID or null
1925 * @param User $user The relevant user
1926 * @return ParserOutput|bool ParserOutput or false if the given revision ID is not found
1928 public function getParserOutput( $oldid = null, User $user = null ) {
1929 // XXX: bypasses mParserOptions and thus setParserOptions()
1931 if ( $user === null ) {
1932 $parserOptions = $this->getParserOptions();
1933 } else {
1934 $parserOptions = $this->mPage->makeParserOptions( $user );
1937 return $this->mPage->getParserOutput( $parserOptions, $oldid );
1941 * Override the ParserOptions used to render the primary article wikitext.
1943 * @param ParserOptions $options
1944 * @throws MWException If the parser options where already initialized.
1946 public function setParserOptions( ParserOptions $options ) {
1947 if ( $this->mParserOptions ) {
1948 throw new MWException( "can't change parser options after they have already been set" );
1951 // clone, so if $options is modified later, it doesn't confuse the parser cache.
1952 $this->mParserOptions = clone $options;
1956 * Get parser options suitable for rendering the primary article wikitext
1957 * @return ParserOptions
1959 public function getParserOptions() {
1960 if ( !$this->mParserOptions ) {
1961 $this->mParserOptions = $this->mPage->makeParserOptions( $this->getContext() );
1963 // Clone to allow modifications of the return value without affecting cache
1964 return clone $this->mParserOptions;
1968 * Sets the context this Article is executed in
1970 * @param IContextSource $context
1971 * @since 1.18
1973 public function setContext( $context ) {
1974 $this->mContext = $context;
1978 * Gets the context this Article is executed in
1980 * @return IContextSource
1981 * @since 1.18
1983 public function getContext() {
1984 if ( $this->mContext instanceof IContextSource ) {
1985 return $this->mContext;
1986 } else {
1987 wfDebug( __METHOD__ . " called and \$mContext is null. " .
1988 "Return RequestContext::getMain(); for sanity\n" );
1989 return RequestContext::getMain();
1994 * Use PHP's magic __get handler to handle accessing of
1995 * raw WikiPage fields for backwards compatibility.
1997 * @param string $fname Field name
1998 * @return mixed
2000 public function __get( $fname ) {
2001 if ( property_exists( $this->mPage, $fname ) ) {
2002 # wfWarn( "Access to raw $fname field " . __CLASS__ );
2003 return $this->mPage->$fname;
2005 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE );
2009 * Use PHP's magic __set handler to handle setting of
2010 * raw WikiPage fields for backwards compatibility.
2012 * @param string $fname Field name
2013 * @param mixed $fvalue New value
2015 public function __set( $fname, $fvalue ) {
2016 if ( property_exists( $this->mPage, $fname ) ) {
2017 # wfWarn( "Access to raw $fname field of " . __CLASS__ );
2018 $this->mPage->$fname = $fvalue;
2019 // Note: extensions may want to toss on new fields
2020 } elseif ( !in_array( $fname, array( 'mContext', 'mPage' ) ) ) {
2021 $this->mPage->$fname = $fvalue;
2022 } else {
2023 trigger_error( 'Inaccessible property via __set(): ' . $fname, E_USER_NOTICE );
2028 * Use PHP's magic __call handler to transform instance calls to
2029 * WikiPage functions for backwards compatibility.
2031 * @param string $fname Name of called method
2032 * @param array $args Arguments to the method
2033 * @return mixed
2035 public function __call( $fname, $args ) {
2036 if ( is_callable( array( $this->mPage, $fname ) ) ) {
2037 # wfWarn( "Call to " . __CLASS__ . "::$fname; please use WikiPage instead" );
2038 return call_user_func_array( array( $this->mPage, $fname ), $args );
2040 trigger_error( 'Inaccessible function via __call(): ' . $fname, E_USER_ERROR );
2043 // ****** B/C functions to work-around PHP silliness with __call and references ****** //
2046 * @param array $limit
2047 * @param array $expiry
2048 * @param bool $cascade
2049 * @param string $reason
2050 * @param User $user
2051 * @return Status
2053 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade,
2054 $reason, User $user
2056 return $this->mPage->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user );
2060 * @param array $limit
2061 * @param string $reason
2062 * @param int $cascade
2063 * @param array $expiry
2064 * @return bool
2066 public function updateRestrictions( $limit = array(), $reason = '',
2067 &$cascade = 0, $expiry = array()
2069 return $this->mPage->doUpdateRestrictions(
2070 $limit,
2071 $expiry,
2072 $cascade,
2073 $reason,
2074 $this->getContext()->getUser()
2079 * @param string $reason
2080 * @param bool $suppress
2081 * @param int $u1 Unused
2082 * @param bool $u2 Unused
2083 * @param string $error
2084 * @return bool
2086 public function doDeleteArticle(
2087 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = ''
2089 return $this->mPage->doDeleteArticle( $reason, $suppress, $u1, $u2, $error );
2093 * @param string $fromP
2094 * @param string $summary
2095 * @param string $token
2096 * @param bool $bot
2097 * @param array $resultDetails
2098 * @param User|null $user
2099 * @return array
2101 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails, User $user = null ) {
2102 $user = is_null( $user ) ? $this->getContext()->getUser() : $user;
2103 return $this->mPage->doRollback( $fromP, $summary, $token, $bot, $resultDetails, $user );
2107 * @param string $fromP
2108 * @param string $summary
2109 * @param bool $bot
2110 * @param array $resultDetails
2111 * @param User|null $guser
2112 * @return array
2114 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
2115 $guser = is_null( $guser ) ? $this->getContext()->getUser() : $guser;
2116 return $this->mPage->commitRollback( $fromP, $summary, $bot, $resultDetails, $guser );
2120 * @param bool $hasHistory
2121 * @return mixed
2123 public function generateReason( &$hasHistory ) {
2124 $title = $this->mPage->getTitle();
2125 $handler = ContentHandler::getForTitle( $title );
2126 return $handler->getAutoDeleteReason( $title, $hasHistory );
2129 // ****** B/C functions for static methods ( __callStatic is PHP>=5.3 ) ****** //
2132 * @return array
2134 * @deprecated since 1.24, use WikiPage::selectFields() instead
2136 public static function selectFields() {
2137 wfDeprecated( __METHOD__, '1.24' );
2138 return WikiPage::selectFields();
2142 * @param Title $title
2144 * @deprecated since 1.24, use WikiPage::onArticleCreate() instead
2146 public static function onArticleCreate( $title ) {
2147 wfDeprecated( __METHOD__, '1.24' );
2148 WikiPage::onArticleCreate( $title );
2152 * @param Title $title
2154 * @deprecated since 1.24, use WikiPage::onArticleDelete() instead
2156 public static function onArticleDelete( $title ) {
2157 wfDeprecated( __METHOD__, '1.24' );
2158 WikiPage::onArticleDelete( $title );
2162 * @param Title $title
2164 * @deprecated since 1.24, use WikiPage::onArticleEdit() instead
2166 public static function onArticleEdit( $title ) {
2167 wfDeprecated( __METHOD__, '1.24' );
2168 WikiPage::onArticleEdit( $title );
2172 * @param string $oldtext
2173 * @param string $newtext
2174 * @param int $flags
2175 * @return string
2176 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
2178 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2179 return WikiPage::getAutosummary( $oldtext, $newtext, $flags );
2181 // ******