Non-word characters don't terminate tag names.
[mediawiki.git] / includes / Article.php
blob732b1c20c9bd7d2a8ed84d60bed1d999546600a5
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 * @internal documentation reviewed 15 Mar 2010
36 class Article implements Page {
37 /**@{{
38 * @private
41 /**
42 * The context this Article is executed in
43 * @var IContextSource $mContext
45 protected $mContext;
47 /**
48 * The WikiPage object of this instance
49 * @var WikiPage $mPage
51 protected $mPage;
53 /**
54 * ParserOptions object for $wgUser articles
55 * @var ParserOptions $mParserOptions
57 public $mParserOptions;
59 /**
60 * Text of the revision we are working on
61 * @var string $mContent
63 var $mContent; // !< #BC cruft
65 /**
66 * Content of the revision we are working on
67 * @var Content
68 * @since 1.21
70 var $mContentObject; // !<
72 /**
73 * Is the content ($mContent) already loaded?
74 * @var bool $mContentLoaded
76 var $mContentLoaded = false; // !<
78 /**
79 * The oldid of the article that is to be shown, 0 for the
80 * current revision
81 * @var int|null $mOldId
83 var $mOldId; // !<
85 /**
86 * Title from which we were redirected here
87 * @var Title $mRedirectedFrom
89 var $mRedirectedFrom = null;
91 /**
92 * URL to redirect to or false if none
93 * @var string|false $mRedirectUrl
95 var $mRedirectUrl = false; // !<
97 /**
98 * Revision ID of revision we are working on
99 * @var int $mRevIdFetched
101 var $mRevIdFetched = 0; // !<
104 * Revision we are working on
105 * @var Revision $mRevision
107 var $mRevision = null;
110 * ParserOutput object
111 * @var ParserOutput $mParserOutput
113 var $mParserOutput;
115 /**@}}*/
118 * Constructor and clear the article
119 * @param $title Title Reference to a Title object.
120 * @param $oldId Integer revision ID, null to fetch from request, zero for current
122 public function __construct( Title $title, $oldId = null ) {
123 $this->mOldId = $oldId;
124 $this->mPage = $this->newPage( $title );
128 * @param $title Title
129 * @return WikiPage
131 protected function newPage( Title $title ) {
132 return new WikiPage( $title );
136 * Constructor from a page id
137 * @param int $id article ID to load
138 * @return Article|null
140 public static function newFromID( $id ) {
141 $t = Title::newFromID( $id );
142 # @todo FIXME: Doesn't inherit right
143 return $t == null ? null : new self( $t );
144 # return $t == null ? null : new static( $t ); // PHP 5.3
148 * Create an Article object of the appropriate class for the given page.
150 * @param $title Title
151 * @param $context IContextSource
152 * @return Article object
154 public static function newFromTitle( $title, IContextSource $context ) {
155 if ( NS_MEDIA == $title->getNamespace() ) {
156 // FIXME: where should this go?
157 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
160 $page = null;
161 wfRunHooks( 'ArticleFromTitle', array( &$title, &$page ) );
162 if ( !$page ) {
163 switch ( $title->getNamespace() ) {
164 case NS_FILE:
165 $page = new ImagePage( $title );
166 break;
167 case NS_CATEGORY:
168 $page = new CategoryPage( $title );
169 break;
170 default:
171 $page = new Article( $title );
174 $page->setContext( $context );
176 return $page;
180 * Create an Article object of the appropriate class for the given page.
182 * @param $page WikiPage
183 * @param $context IContextSource
184 * @return Article object
186 public static function newFromWikiPage( WikiPage $page, IContextSource $context ) {
187 $article = self::newFromTitle( $page->getTitle(), $context );
188 $article->mPage = $page; // override to keep process cached vars
189 return $article;
193 * Tell the page view functions that this view was redirected
194 * from another page on the wiki.
195 * @param $from Title object.
197 public function setRedirectedFrom( Title $from ) {
198 $this->mRedirectedFrom = $from;
202 * Get the title object of the article
204 * @return Title object of this page
206 public function getTitle() {
207 return $this->mPage->getTitle();
211 * Get the WikiPage object of this instance
213 * @since 1.19
214 * @return WikiPage
216 public function getPage() {
217 return $this->mPage;
221 * Clear the object
223 public function clear() {
224 $this->mContentLoaded = false;
226 $this->mRedirectedFrom = null; # Title object if set
227 $this->mRevIdFetched = 0;
228 $this->mRedirectUrl = false;
230 $this->mPage->clear();
234 * Note that getContent/loadContent do not follow redirects anymore.
235 * If you need to fetch redirectable content easily, try
236 * the shortcut in WikiPage::getRedirectTarget()
238 * This function has side effects! Do not use this function if you
239 * only want the real revision text if any.
241 * @deprecated in 1.21; use WikiPage::getContent() instead
243 * @return string Return the text of this revision
245 public function getContent() {
246 ContentHandler::deprecated( __METHOD__, '1.21' );
247 $content = $this->getContentObject();
248 return ContentHandler::getContentText( $content );
252 * Returns a Content object representing the pages effective display content,
253 * not necessarily the revision's content!
255 * Note that getContent/loadContent do not follow redirects anymore.
256 * If you need to fetch redirectable content easily, try
257 * the shortcut in WikiPage::getRedirectTarget()
259 * This function has side effects! Do not use this function if you
260 * only want the real revision text if any.
262 * @return Content Return the content of this revision
264 * @since 1.21
266 protected function getContentObject() {
267 wfProfileIn( __METHOD__ );
269 if ( $this->mPage->getID() === 0 ) {
270 # If this is a MediaWiki:x message, then load the messages
271 # and return the message value for x.
272 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI ) {
273 $text = $this->getTitle()->getDefaultMessageText();
274 if ( $text === false ) {
275 $text = '';
278 $content = ContentHandler::makeContent( $text, $this->getTitle() );
279 } else {
280 $message = $this->getContext()->getUser()->isLoggedIn() ? 'noarticletext' : 'noarticletextanon';
281 $content = new MessageContent( $message, null, 'parsemag' );
283 } else {
284 $this->fetchContentObject();
285 $content = $this->mContentObject;
288 wfProfileOut( __METHOD__ );
289 return $content;
293 * @return int The oldid of the article that is to be shown, 0 for the
294 * current revision
296 public function getOldID() {
297 if ( is_null( $this->mOldId ) ) {
298 $this->mOldId = $this->getOldIDFromRequest();
301 return $this->mOldId;
305 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
307 * @return int The old id for the request
309 public function getOldIDFromRequest() {
310 $this->mRedirectUrl = false;
312 $request = $this->getContext()->getRequest();
313 $oldid = $request->getIntOrNull( 'oldid' );
315 if ( $oldid === null ) {
316 return 0;
319 if ( $oldid !== 0 ) {
320 # Load the given revision and check whether the page is another one.
321 # In that case, update this instance to reflect the change.
322 if ( $oldid === $this->mPage->getLatest() ) {
323 $this->mRevision = $this->mPage->getRevision();
324 } else {
325 $this->mRevision = Revision::newFromId( $oldid );
326 if ( $this->mRevision !== null ) {
327 // Revision title doesn't match the page title given?
328 if ( $this->mPage->getID() != $this->mRevision->getPage() ) {
329 $function = array( get_class( $this->mPage ), 'newFromID' );
330 $this->mPage = call_user_func( $function, $this->mRevision->getPage() );
336 if ( $request->getVal( 'direction' ) == 'next' ) {
337 $nextid = $this->getTitle()->getNextRevisionID( $oldid );
338 if ( $nextid ) {
339 $oldid = $nextid;
340 $this->mRevision = null;
341 } else {
342 $this->mRedirectUrl = $this->getTitle()->getFullURL( 'redirect=no' );
344 } elseif ( $request->getVal( 'direction' ) == 'prev' ) {
345 $previd = $this->getTitle()->getPreviousRevisionID( $oldid );
346 if ( $previd ) {
347 $oldid = $previd;
348 $this->mRevision = null;
352 return $oldid;
356 * Load the revision (including text) into this object
358 * @deprecated in 1.19; use fetchContent()
360 function loadContent() {
361 wfDeprecated( __METHOD__, '1.19' );
362 $this->fetchContent();
366 * Get text of an article from database
367 * Does *NOT* follow redirects.
369 * @protected
370 * @note this is really internal functionality that should really NOT be used by other functions. For accessing
371 * article content, use the WikiPage class, especially WikiBase::getContent(). However, a lot of legacy code
372 * uses this method to retrieve page text from the database, so the function has to remain public for now.
374 * @return mixed string containing article contents, or false if null
375 * @deprecated in 1.21, use WikiPage::getContent() instead
377 function fetchContent() { #BC cruft!
378 ContentHandler::deprecated( __METHOD__, '1.21' );
380 if ( $this->mContentLoaded && $this->mContent ) {
381 return $this->mContent;
384 wfProfileIn( __METHOD__ );
386 $content = $this->fetchContentObject();
388 // @todo Get rid of mContent everywhere!
389 $this->mContent = ContentHandler::getContentText( $content );
390 ContentHandler::runLegacyHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) );
392 wfProfileOut( __METHOD__ );
394 return $this->mContent;
398 * Get text content object
399 * Does *NOT* follow redirects.
400 * TODO: when is this null?
402 * @note code that wants to retrieve page content from the database should use WikiPage::getContent().
404 * @return Content|null|boolean false
406 * @since 1.21
408 protected function fetchContentObject() {
409 if ( $this->mContentLoaded ) {
410 return $this->mContentObject;
413 wfProfileIn( __METHOD__ );
415 $this->mContentLoaded = true;
416 $this->mContent = null;
418 $oldid = $this->getOldID();
420 # Pre-fill content with error message so that if something
421 # fails we'll have something telling us what we intended.
422 //XXX: this isn't page content but a UI message. horrible.
423 $this->mContentObject = new MessageContent( 'missing-revision', array( $oldid ), array() );
425 if ( $oldid ) {
426 # $this->mRevision might already be fetched by getOldIDFromRequest()
427 if ( !$this->mRevision ) {
428 $this->mRevision = Revision::newFromId( $oldid );
429 if ( !$this->mRevision ) {
430 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
431 wfProfileOut( __METHOD__ );
432 return false;
435 } else {
436 if ( !$this->mPage->getLatest() ) {
437 wfDebug( __METHOD__ . " failed to find page data for title " . $this->getTitle()->getPrefixedText() . "\n" );
438 wfProfileOut( __METHOD__ );
439 return false;
442 $this->mRevision = $this->mPage->getRevision();
444 if ( !$this->mRevision ) {
445 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id " . $this->mPage->getLatest() . "\n" );
446 wfProfileOut( __METHOD__ );
447 return false;
451 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
452 // We should instead work with the Revision object when we need it...
453 $this->mContentObject = $this->mRevision->getContent( Revision::FOR_THIS_USER, $this->getContext()->getUser() ); // Loads if user is allowed
454 $this->mRevIdFetched = $this->mRevision->getId();
456 wfRunHooks( 'ArticleAfterFetchContentObject', array( &$this, &$this->mContentObject ) );
458 wfProfileOut( __METHOD__ );
460 return $this->mContentObject;
464 * No-op
465 * @deprecated since 1.18
467 public function forUpdate() {
468 wfDeprecated( __METHOD__, '1.18' );
472 * Returns true if the currently-referenced revision is the current edit
473 * to this page (and it exists).
474 * @return bool
476 public function isCurrent() {
477 # If no oldid, this is the current version.
478 if ( $this->getOldID() == 0 ) {
479 return true;
482 return $this->mPage->exists() && $this->mRevision && $this->mRevision->isCurrent();
486 * Get the fetched Revision object depending on request parameters or null
487 * on failure.
489 * @since 1.19
490 * @return Revision|null
492 public function getRevisionFetched() {
493 $this->fetchContentObject();
495 return $this->mRevision;
499 * Use this to fetch the rev ID used on page views
501 * @return int revision ID of last article revision
503 public function getRevIdFetched() {
504 if ( $this->mRevIdFetched ) {
505 return $this->mRevIdFetched;
506 } else {
507 return $this->mPage->getLatest();
512 * This is the default action of the index.php entry point: just view the
513 * page of the given title.
515 public function view() {
516 global $wgUseFileCache, $wgUseETag, $wgDebugToolbar;
518 wfProfileIn( __METHOD__ );
520 # Get variables from query string
521 # As side effect this will load the revision and update the title
522 # in a revision ID is passed in the request, so this should remain
523 # the first call of this method even if $oldid is used way below.
524 $oldid = $this->getOldID();
526 $user = $this->getContext()->getUser();
527 # Another whitelist check in case getOldID() is altering the title
528 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'read', $user );
529 if ( count( $permErrors ) ) {
530 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
531 wfProfileOut( __METHOD__ );
532 throw new PermissionsError( 'read', $permErrors );
535 $outputPage = $this->getContext()->getOutput();
536 # getOldID() may as well want us to redirect somewhere else
537 if ( $this->mRedirectUrl ) {
538 $outputPage->redirect( $this->mRedirectUrl );
539 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
540 wfProfileOut( __METHOD__ );
542 return;
545 # If we got diff in the query, we want to see a diff page instead of the article.
546 if ( $this->getContext()->getRequest()->getCheck( 'diff' ) ) {
547 wfDebug( __METHOD__ . ": showing diff page\n" );
548 $this->showDiffPage();
549 wfProfileOut( __METHOD__ );
551 return;
554 # Set page title (may be overridden by DISPLAYTITLE)
555 $outputPage->setPageTitle( $this->getTitle()->getPrefixedText() );
557 $outputPage->setArticleFlag( true );
558 # Allow frames by default
559 $outputPage->allowClickjacking();
561 $parserCache = ParserCache::singleton();
563 $parserOptions = $this->getParserOptions();
564 # Render printable version, use printable version cache
565 if ( $outputPage->isPrintable() ) {
566 $parserOptions->setIsPrintable( true );
567 $parserOptions->setEditSection( false );
568 } elseif ( !$this->isCurrent() || !$this->getTitle()->quickUserCan( 'edit', $user ) ) {
569 $parserOptions->setEditSection( false );
572 # Try client and file cache
573 if ( !$wgDebugToolbar && $oldid === 0 && $this->mPage->checkTouched() ) {
574 if ( $wgUseETag ) {
575 $outputPage->setETag( $parserCache->getETag( $this, $parserOptions ) );
578 # Is it client cached?
579 if ( $outputPage->checkLastModified( $this->mPage->getTouched() ) ) {
580 wfDebug( __METHOD__ . ": done 304\n" );
581 wfProfileOut( __METHOD__ );
583 return;
584 # Try file cache
585 } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
586 wfDebug( __METHOD__ . ": done file cache\n" );
587 # tell wgOut that output is taken care of
588 $outputPage->disable();
589 $this->mPage->doViewUpdates( $user );
590 wfProfileOut( __METHOD__ );
592 return;
596 # Should the parser cache be used?
597 $useParserCache = $this->mPage->isParserCacheUsed( $parserOptions, $oldid );
598 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
599 if ( $user->getStubThreshold() ) {
600 wfIncrStats( 'pcache_miss_stub' );
603 $this->showRedirectedFromHeader();
604 $this->showNamespaceHeader();
606 # Iterate through the possible ways of constructing the output text.
607 # Keep going until $outputDone is set, or we run out of things to do.
608 $pass = 0;
609 $outputDone = false;
610 $this->mParserOutput = false;
612 while ( !$outputDone && ++$pass ) {
613 switch ( $pass ) {
614 case 1:
615 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
616 break;
617 case 2:
618 # Early abort if the page doesn't exist
619 if ( !$this->mPage->exists() ) {
620 wfDebug( __METHOD__ . ": showing missing article\n" );
621 $this->showMissingArticle();
622 wfProfileOut( __METHOD__ );
623 return;
626 # Try the parser cache
627 if ( $useParserCache ) {
628 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
630 if ( $this->mParserOutput !== false ) {
631 if ( $oldid ) {
632 wfDebug( __METHOD__ . ": showing parser cache contents for current rev permalink\n" );
633 $this->setOldSubtitle( $oldid );
634 } else {
635 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
637 $outputPage->addParserOutput( $this->mParserOutput );
638 # Ensure that UI elements requiring revision ID have
639 # the correct version information.
640 $outputPage->setRevisionId( $this->mPage->getLatest() );
641 # Preload timestamp to avoid a DB hit
642 $cachedTimestamp = $this->mParserOutput->getTimestamp();
643 if ( $cachedTimestamp !== null ) {
644 $outputPage->setRevisionTimestamp( $cachedTimestamp );
645 $this->mPage->setTimestamp( $cachedTimestamp );
647 $outputDone = true;
650 break;
651 case 3:
652 # This will set $this->mRevision if needed
653 $this->fetchContentObject();
655 # Are we looking at an old revision
656 if ( $oldid && $this->mRevision ) {
657 $this->setOldSubtitle( $oldid );
659 if ( !$this->showDeletedRevisionHeader() ) {
660 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
661 wfProfileOut( __METHOD__ );
662 return;
666 # Ensure that UI elements requiring revision ID have
667 # the correct version information.
668 $outputPage->setRevisionId( $this->getRevIdFetched() );
669 # Preload timestamp to avoid a DB hit
670 $outputPage->setRevisionTimestamp( $this->getTimestamp() );
672 # Pages containing custom CSS or JavaScript get special treatment
673 if ( $this->getTitle()->isCssOrJsPage() || $this->getTitle()->isCssJsSubpage() ) {
674 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
675 $this->showCssOrJsPage();
676 $outputDone = true;
677 } elseif ( !wfRunHooks( 'ArticleContentViewCustom',
678 array( $this->fetchContentObject(), $this->getTitle(), $outputPage ) ) ) {
680 # Allow extensions do their own custom view for certain pages
681 $outputDone = true;
682 } elseif ( !ContentHandler::runLegacyHooks( 'ArticleViewCustom',
683 array( $this->fetchContentObject(), $this->getTitle(), $outputPage ) ) ) {
685 # Allow extensions do their own custom view for certain pages
686 $outputDone = true;
687 } else {
688 $content = $this->getContentObject();
689 $rt = $content ? $content->getRedirectChain() : null;
690 if ( $rt ) {
691 wfDebug( __METHOD__ . ": showing redirect=no page\n" );
692 # Viewing a redirect page (e.g. with parameter redirect=no)
693 $outputPage->addHTML( $this->viewRedirect( $rt ) );
694 # Parse just to get categories, displaytitle, etc.
695 $this->mParserOutput = $content->getParserOutput( $this->getTitle(), $oldid, $parserOptions, false );
696 $outputPage->addParserOutputNoText( $this->mParserOutput );
697 $outputDone = true;
700 break;
701 case 4:
702 # Run the parse, protected by a pool counter
703 wfDebug( __METHOD__ . ": doing uncached parse\n" );
705 $poolArticleView = new PoolWorkArticleView( $this->getPage(), $parserOptions,
706 $this->getRevIdFetched(), $useParserCache, $this->getContentObject() );
708 if ( !$poolArticleView->execute() ) {
709 $error = $poolArticleView->getError();
710 if ( $error ) {
711 $outputPage->clearHTML(); // for release() errors
712 $outputPage->enableClientCache( false );
713 $outputPage->setRobotPolicy( 'noindex,nofollow' );
715 $errortext = $error->getWikiText( false, 'view-pool-error' );
716 $outputPage->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
718 # Connection or timeout error
719 wfProfileOut( __METHOD__ );
720 return;
723 $this->mParserOutput = $poolArticleView->getParserOutput();
724 $outputPage->addParserOutput( $this->mParserOutput );
726 # Don't cache a dirty ParserOutput object
727 if ( $poolArticleView->getIsDirty() ) {
728 $outputPage->setSquidMaxage( 0 );
729 $outputPage->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
732 $outputDone = true;
733 break;
734 # Should be unreachable, but just in case...
735 default:
736 break 2;
740 # Get the ParserOutput actually *displayed* here.
741 # Note that $this->mParserOutput is the *current* version output.
742 $pOutput = ( $outputDone instanceof ParserOutput )
743 ? $outputDone // object fetched by hook
744 : $this->mParserOutput;
746 # Adjust title for main page & pages with displaytitle
747 if ( $pOutput ) {
748 $this->adjustDisplayTitle( $pOutput );
751 # For the main page, overwrite the <title> element with the con-
752 # tents of 'pagetitle-view-mainpage' instead of the default (if
753 # that's not empty).
754 # This message always exists because it is in the i18n files
755 if ( $this->getTitle()->isMainPage() ) {
756 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
757 if ( !$msg->isDisabled() ) {
758 $outputPage->setHTMLTitle( $msg->title( $this->getTitle() )->text() );
762 # Check for any __NOINDEX__ tags on the page using $pOutput
763 $policy = $this->getRobotPolicy( 'view', $pOutput );
764 $outputPage->setIndexPolicy( $policy['index'] );
765 $outputPage->setFollowPolicy( $policy['follow'] );
767 $this->showViewFooter();
768 $this->mPage->doViewUpdates( $user );
770 $outputPage->addModules( 'mediawiki.action.view.postEdit' );
772 wfProfileOut( __METHOD__ );
776 * Adjust title for pages with displaytitle, -{T|}- or language conversion
777 * @param $pOutput ParserOutput
779 public function adjustDisplayTitle( ParserOutput $pOutput ) {
780 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
781 $titleText = $pOutput->getTitleText();
782 if ( strval( $titleText ) !== '' ) {
783 $this->getContext()->getOutput()->setPageTitle( $titleText );
788 * Show a diff page according to current request variables. For use within
789 * Article::view() only, other callers should use the DifferenceEngine class.
791 * @todo Make protected
793 public function showDiffPage() {
794 $request = $this->getContext()->getRequest();
795 $user = $this->getContext()->getUser();
796 $diff = $request->getVal( 'diff' );
797 $rcid = $request->getVal( 'rcid' );
798 $diffOnly = $request->getBool( 'diffonly', $user->getOption( 'diffonly' ) );
799 $purge = $request->getVal( 'action' ) == 'purge';
800 $unhide = $request->getInt( 'unhide' ) == 1;
801 $oldid = $this->getOldID();
803 $rev = $this->getRevisionFetched();
805 if ( !$rev ) {
806 $this->getContext()->getOutput()->setPageTitle( wfMessage( 'errorpagetitle' ) );
807 $this->getContext()->getOutput()->addWikiMsg( 'difference-missing-revision', $oldid, 1 );
808 return;
811 $contentHandler = $rev->getContentHandler();
812 $de = $contentHandler->createDifferenceEngine( $this->getContext(), $oldid, $diff, $rcid, $purge, $unhide );
814 // DifferenceEngine directly fetched the revision:
815 $this->mRevIdFetched = $de->mNewid;
816 $de->showDiffPage( $diffOnly );
818 if ( $diff == 0 || $diff == $this->mPage->getLatest() ) {
819 # Run view updates for current revision only
820 $this->mPage->doViewUpdates( $user );
825 * Show a page view for a page formatted as CSS or JavaScript. To be called by
826 * Article::view() only.
828 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
829 * page views.
831 * @param bool $showCacheHint whether to show a message telling the user to clear the browser cache (default: true).
833 protected function showCssOrJsPage( $showCacheHint = true ) {
834 $outputPage = $this->getContext()->getOutput();
836 if ( $showCacheHint ) {
837 $dir = $this->getContext()->getLanguage()->getDir();
838 $lang = $this->getContext()->getLanguage()->getCode();
840 $outputPage->wrapWikiMsg( "<div id='mw-clearyourcache' lang='$lang' dir='$dir' class='mw-content-$dir'>\n$1\n</div>",
841 'clearyourcache' );
844 $this->fetchContentObject();
846 if ( $this->mContentObject ) {
847 // Give hooks a chance to customise the output
848 if ( ContentHandler::runLegacyHooks( 'ShowRawCssJs', array( $this->mContentObject, $this->getTitle(), $outputPage ) ) ) {
849 $po = $this->mContentObject->getParserOutput( $this->getTitle() );
850 $outputPage->addHTML( $po->getText() );
856 * Get the robot policy to be used for the current view
857 * @param string $action the action= GET parameter
858 * @param $pOutput ParserOutput|null
859 * @return Array the policy that should be set
860 * TODO: actions other than 'view'
862 public function getRobotPolicy( $action, $pOutput = null ) {
863 global $wgArticleRobotPolicies, $wgNamespaceRobotPolicies, $wgDefaultRobotPolicy;
865 $ns = $this->getTitle()->getNamespace();
867 # Don't index user and user talk pages for blocked users (bug 11443)
868 if ( ( $ns == NS_USER || $ns == NS_USER_TALK ) && !$this->getTitle()->isSubpage() ) {
869 $specificTarget = null;
870 $vagueTarget = null;
871 $titleText = $this->getTitle()->getText();
872 if ( IP::isValid( $titleText ) ) {
873 $vagueTarget = $titleText;
874 } else {
875 $specificTarget = $titleText;
877 if ( Block::newFromTarget( $specificTarget, $vagueTarget ) instanceof Block ) {
878 return array(
879 'index' => 'noindex',
880 'follow' => 'nofollow'
885 if ( $this->mPage->getID() === 0 || $this->getOldID() ) {
886 # Non-articles (special pages etc), and old revisions
887 return array(
888 'index' => 'noindex',
889 'follow' => 'nofollow'
891 } elseif ( $this->getContext()->getOutput()->isPrintable() ) {
892 # Discourage indexing of printable versions, but encourage following
893 return array(
894 'index' => 'noindex',
895 'follow' => 'follow'
897 } elseif ( $this->getContext()->getRequest()->getInt( 'curid' ) ) {
898 # For ?curid=x urls, disallow indexing
899 return array(
900 'index' => 'noindex',
901 'follow' => 'follow'
905 # Otherwise, construct the policy based on the various config variables.
906 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
908 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
909 # Honour customised robot policies for this namespace
910 $policy = array_merge(
911 $policy,
912 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
915 if ( $this->getTitle()->canUseNoindex() && is_object( $pOutput ) && $pOutput->getIndexPolicy() ) {
916 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
917 # a final sanity check that we have really got the parser output.
918 $policy = array_merge(
919 $policy,
920 array( 'index' => $pOutput->getIndexPolicy() )
924 if ( isset( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] ) ) {
925 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
926 $policy = array_merge(
927 $policy,
928 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] )
932 return $policy;
936 * Converts a String robot policy into an associative array, to allow
937 * merging of several policies using array_merge().
938 * @param $policy Mixed, returns empty array on null/false/'', transparent
939 * to already-converted arrays, converts String.
940 * @return Array: 'index' => \<indexpolicy\>, 'follow' => \<followpolicy\>
942 public static function formatRobotPolicy( $policy ) {
943 if ( is_array( $policy ) ) {
944 return $policy;
945 } elseif ( !$policy ) {
946 return array();
949 $policy = explode( ',', $policy );
950 $policy = array_map( 'trim', $policy );
952 $arr = array();
953 foreach ( $policy as $var ) {
954 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
955 $arr['index'] = $var;
956 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
957 $arr['follow'] = $var;
961 return $arr;
965 * If this request is a redirect view, send "redirected from" subtitle to
966 * the output. Returns true if the header was needed, false if this is not
967 * a redirect view. Handles both local and remote redirects.
969 * @return boolean
971 public function showRedirectedFromHeader() {
972 global $wgRedirectSources;
973 $outputPage = $this->getContext()->getOutput();
975 $rdfrom = $this->getContext()->getRequest()->getVal( 'rdfrom' );
977 if ( isset( $this->mRedirectedFrom ) ) {
978 // This is an internally redirected page view.
979 // We'll need a backlink to the source page for navigation.
980 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
981 $redir = Linker::linkKnown(
982 $this->mRedirectedFrom,
983 null,
984 array(),
985 array( 'redirect' => 'no' )
988 $outputPage->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
990 // Set the fragment if one was specified in the redirect
991 if ( strval( $this->getTitle()->getFragment() ) != '' ) {
992 $outputPage->addInlineScript( Xml::encodeJsCall(
993 'redirectToFragment', array( $this->getTitle()->getFragmentForURL() )
994 ) );
997 // Add a <link rel="canonical"> tag
998 $outputPage->setCanonicalUrl( $this->getTitle()->getLocalURL() );
1000 // Tell the output object that the user arrived at this article through a redirect
1001 $outputPage->setRedirectedFrom( $this->mRedirectedFrom );
1003 return true;
1005 } elseif ( $rdfrom ) {
1006 // This is an externally redirected view, from some other wiki.
1007 // If it was reported from a trusted site, supply a backlink.
1008 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1009 $redir = Linker::makeExternalLink( $rdfrom, $rdfrom );
1010 $outputPage->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
1012 return true;
1016 return false;
1020 * Show a header specific to the namespace currently being viewed, like
1021 * [[MediaWiki:Talkpagetext]]. For Article::view().
1023 public function showNamespaceHeader() {
1024 if ( $this->getTitle()->isTalkPage() ) {
1025 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1026 $this->getContext()->getOutput()->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1032 * Show the footer section of an ordinary page view
1034 public function showViewFooter() {
1035 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1036 if ( $this->getTitle()->getNamespace() == NS_USER_TALK && IP::isValid( $this->getTitle()->getText() ) ) {
1037 $this->getContext()->getOutput()->addWikiMsg( 'anontalkpagetext' );
1040 // Show a footer allowing the user to patrol the shown revision or page if possible
1041 $patrolFooterShown = $this->showPatrolFooter();
1043 wfRunHooks( 'ArticleViewFooter', array( $this, $patrolFooterShown ) );
1048 * If patrol is possible, output a patrol UI box. This is called from the
1049 * footer section of ordinary page views. If patrol is not possible or not
1050 * desired, does nothing.
1051 * Side effect: When the patrol link is build, this method will call
1052 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
1054 * @return bool
1056 public function showPatrolFooter() {
1057 global $wgUseNPPatrol, $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
1059 $outputPage = $this->getContext()->getOutput();
1060 $user = $this->getContext()->getUser();
1061 $cache = wfGetMainCache();
1062 $rc = false;
1064 if ( !$this->getTitle()->quickUserCan( 'patrol', $user ) || !( $wgUseRCPatrol || $wgUseNPPatrol ) ) {
1065 // Patrolling is disabled or the user isn't allowed to
1066 return false;
1069 wfProfileIn( __METHOD__ );
1071 // New page patrol: Get the timestamp of the oldest revison which
1072 // the revision table holds for the given page. Then we look
1073 // whether it's within the RC lifespan and if it is, we try
1074 // to get the recentchanges row belonging to that entry
1075 // (with rc_new = 1).
1077 // Check for cached results
1078 if ( $cache->get( wfMemcKey( 'NotPatrollablePage', $this->getTitle()->getArticleID() ) ) ) {
1079 wfProfileOut( __METHOD__ );
1080 return false;
1083 if ( $this->mRevision && !RecentChange::isInRCLifespan( $this->mRevision->getTimestamp(), 21600 ) ) {
1084 // The current revision is already older than what could be in the RC table
1085 // 6h tolerance because the RC might not be cleaned out regularly
1086 wfProfileOut( __METHOD__ );
1087 return false;
1090 $dbr = wfGetDB( DB_SLAVE );
1091 $oldestRevisionTimestamp = $dbr->selectField(
1092 'revision',
1093 'MIN( rev_timestamp )',
1094 array( 'rev_page' => $this->getTitle()->getArticleID() ),
1095 __METHOD__
1098 if ( $oldestRevisionTimestamp && RecentChange::isInRCLifespan( $oldestRevisionTimestamp, 21600 ) ) {
1099 // 6h tolerance because the RC might not be cleaned out regularly
1100 $rc = RecentChange::newFromConds(
1101 array(
1102 'rc_new' => 1,
1103 'rc_timestamp' => $oldestRevisionTimestamp,
1104 'rc_namespace' => $this->getTitle()->getNamespace(),
1105 'rc_cur_id' => $this->getTitle()->getArticleID(),
1106 'rc_patrolled' => 0
1108 __METHOD__,
1109 array( 'USE INDEX' => 'new_name_timestamp' )
1113 if ( !$rc ) {
1114 // No RC entry around
1116 // Cache the information we gathered above in case we can't patrol
1117 // Don't cache in case we can patrol as this could change
1118 $cache->set( wfMemcKey( 'NotPatrollablePage', $this->getTitle()->getArticleID() ), '1' );
1120 wfProfileOut( __METHOD__ );
1121 return false;
1124 $rcid = $rc->getAttribute( 'rc_id' );
1126 $token = $user->getEditToken( $rcid );
1128 $outputPage->preventClickjacking();
1129 if ( $wgEnableAPI && $wgEnableWriteAPI && $user->isAllowed( 'writeapi' ) ) {
1130 $outputPage->addModules( 'mediawiki.page.patrol.ajax' );
1133 $link = Linker::linkKnown(
1134 $this->getTitle(),
1135 wfMessage( 'markaspatrolledtext' )->escaped(),
1136 array(),
1137 array(
1138 'action' => 'markpatrolled',
1139 'rcid' => $rcid,
1140 'token' => $token,
1144 $outputPage->addHTML(
1145 "<div class='patrollink'>" .
1146 wfMessage( 'markaspatrolledlink' )->rawParams( $link )->escaped() .
1147 '</div>'
1150 wfProfileOut( __METHOD__ );
1151 return true;
1155 * Show the error text for a missing article. For articles in the MediaWiki
1156 * namespace, show the default message text. To be called from Article::view().
1158 public function showMissingArticle() {
1159 global $wgSend404Code;
1160 $outputPage = $this->getContext()->getOutput();
1161 // Whether the page is a root user page of an existing user (but not a subpage)
1162 $validUserPage = false;
1164 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1165 if ( $this->getTitle()->getNamespace() == NS_USER || $this->getTitle()->getNamespace() == NS_USER_TALK ) {
1166 $parts = explode( '/', $this->getTitle()->getText() );
1167 $rootPart = $parts[0];
1168 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1169 $ip = User::isIP( $rootPart );
1171 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1172 $outputPage->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1173 array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
1174 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1175 LogEventsList::showLogExtract(
1176 $outputPage,
1177 'block',
1178 $user->getUserPage(),
1180 array(
1181 'lim' => 1,
1182 'showIfEmpty' => false,
1183 'msgKey' => array(
1184 'blocked-notice-logextract',
1185 $user->getName() # Support GENDER in notice
1189 $validUserPage = !$this->getTitle()->isSubpage();
1190 } else {
1191 $validUserPage = !$this->getTitle()->isSubpage();
1195 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1197 # Show delete and move logs
1198 LogEventsList::showLogExtract( $outputPage, array( 'delete', 'move' ), $this->getTitle(), '',
1199 array( 'lim' => 10,
1200 'conds' => array( "log_action != 'revision'" ),
1201 'showIfEmpty' => false,
1202 'msgKey' => array( 'moveddeleted-notice' ) )
1205 if ( !$this->mPage->hasViewableContent() && $wgSend404Code && !$validUserPage ) {
1206 // If there's no backing content, send a 404 Not Found
1207 // for better machine handling of broken links.
1208 $this->getContext()->getRequest()->response()->header( "HTTP/1.1 404 Not Found" );
1211 if ( $validUserPage ) {
1212 // Also apply the robot policy for nonexisting user pages (as those aren't served as 404)
1213 $policy = $this->getRobotPolicy( 'view' );
1214 $outputPage->setIndexPolicy( $policy['index'] );
1215 $outputPage->setFollowPolicy( $policy['follow'] );
1218 $hookResult = wfRunHooks( 'BeforeDisplayNoArticleText', array( $this ) );
1220 if ( ! $hookResult ) {
1221 return;
1224 # Show error message
1225 $oldid = $this->getOldID();
1226 if ( $oldid ) {
1227 $text = wfMessage( 'missing-revision', $oldid )->plain();
1228 } elseif ( $this->getTitle()->getNamespace() === NS_MEDIAWIKI ) {
1229 // Use the default message text
1230 $text = $this->getTitle()->getDefaultMessageText();
1231 } elseif ( $this->getTitle()->quickUserCan( 'create', $this->getContext()->getUser() )
1232 && $this->getTitle()->quickUserCan( 'edit', $this->getContext()->getUser() )
1234 $text = wfMessage( 'noarticletext' )->plain();
1235 } else {
1236 $text = wfMessage( 'noarticletext-nopermission' )->plain();
1238 $text = "<div class='noarticletext'>\n$text\n</div>";
1240 $outputPage->addWikiText( $text );
1244 * If the revision requested for view is deleted, check permissions.
1245 * Send either an error message or a warning header to the output.
1247 * @return boolean true if the view is allowed, false if not.
1249 public function showDeletedRevisionHeader() {
1250 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1251 // Not deleted
1252 return true;
1255 $outputPage = $this->getContext()->getOutput();
1256 $user = $this->getContext()->getUser();
1257 // If the user is not allowed to see it...
1258 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT, $user ) ) {
1259 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1260 'rev-deleted-text-permission' );
1262 return false;
1263 // If the user needs to confirm that they want to see it...
1264 } elseif ( $this->getContext()->getRequest()->getInt( 'unhide' ) != 1 ) {
1265 # Give explanation and add a link to view the revision...
1266 $oldid = intval( $this->getOldID() );
1267 $link = $this->getTitle()->getFullURL( "oldid={$oldid}&unhide=1" );
1268 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1269 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1270 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1271 array( $msg, $link ) );
1273 return false;
1274 // We are allowed to see...
1275 } else {
1276 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1277 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1278 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1280 return true;
1285 * Generate the navigation links when browsing through an article revisions
1286 * It shows the information as:
1287 * Revision as of \<date\>; view current revision
1288 * \<- Previous version | Next Version -\>
1290 * @param int $oldid revision ID of this article revision
1292 public function setOldSubtitle( $oldid = 0 ) {
1293 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
1294 return;
1297 $unhide = $this->getContext()->getRequest()->getInt( 'unhide' ) == 1;
1299 # Cascade unhide param in links for easy deletion browsing
1300 $extraParams = array();
1301 if ( $unhide ) {
1302 $extraParams['unhide'] = 1;
1305 if ( $this->mRevision && $this->mRevision->getId() === $oldid ) {
1306 $revision = $this->mRevision;
1307 } else {
1308 $revision = Revision::newFromId( $oldid );
1311 $timestamp = $revision->getTimestamp();
1313 $current = ( $oldid == $this->mPage->getLatest() );
1314 $language = $this->getContext()->getLanguage();
1315 $user = $this->getContext()->getUser();
1317 $td = $language->userTimeAndDate( $timestamp, $user );
1318 $tddate = $language->userDate( $timestamp, $user );
1319 $tdtime = $language->userTime( $timestamp, $user );
1321 # Show user links if allowed to see them. If hidden, then show them only if requested...
1322 $userlinks = Linker::revUserTools( $revision, !$unhide );
1324 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
1325 ? 'revision-info-current'
1326 : 'revision-info';
1328 $outputPage = $this->getContext()->getOutput();
1329 $outputPage->addSubtitle( "<div id=\"mw-{$infomsg}\">" . wfMessage( $infomsg,
1330 $td )->rawParams( $userlinks )->params( $revision->getID(), $tddate,
1331 $tdtime, $revision->getUser() )->parse() . "</div>" );
1333 $lnk = $current
1334 ? wfMessage( 'currentrevisionlink' )->escaped()
1335 : Linker::linkKnown(
1336 $this->getTitle(),
1337 wfMessage( 'currentrevisionlink' )->escaped(),
1338 array(),
1339 $extraParams
1341 $curdiff = $current
1342 ? wfMessage( 'diff' )->escaped()
1343 : Linker::linkKnown(
1344 $this->getTitle(),
1345 wfMessage( 'diff' )->escaped(),
1346 array(),
1347 array(
1348 'diff' => 'cur',
1349 'oldid' => $oldid
1350 ) + $extraParams
1352 $prev = $this->getTitle()->getPreviousRevisionID( $oldid );
1353 $prevlink = $prev
1354 ? Linker::linkKnown(
1355 $this->getTitle(),
1356 wfMessage( 'previousrevision' )->escaped(),
1357 array(),
1358 array(
1359 'direction' => 'prev',
1360 'oldid' => $oldid
1361 ) + $extraParams
1363 : wfMessage( 'previousrevision' )->escaped();
1364 $prevdiff = $prev
1365 ? Linker::linkKnown(
1366 $this->getTitle(),
1367 wfMessage( 'diff' )->escaped(),
1368 array(),
1369 array(
1370 'diff' => 'prev',
1371 'oldid' => $oldid
1372 ) + $extraParams
1374 : wfMessage( 'diff' )->escaped();
1375 $nextlink = $current
1376 ? wfMessage( 'nextrevision' )->escaped()
1377 : Linker::linkKnown(
1378 $this->getTitle(),
1379 wfMessage( 'nextrevision' )->escaped(),
1380 array(),
1381 array(
1382 'direction' => 'next',
1383 'oldid' => $oldid
1384 ) + $extraParams
1386 $nextdiff = $current
1387 ? wfMessage( 'diff' )->escaped()
1388 : Linker::linkKnown(
1389 $this->getTitle(),
1390 wfMessage( 'diff' )->escaped(),
1391 array(),
1392 array(
1393 'diff' => 'next',
1394 'oldid' => $oldid
1395 ) + $extraParams
1398 $cdel = Linker::getRevDeleteLink( $user, $revision, $this->getTitle() );
1399 if ( $cdel !== '' ) {
1400 $cdel .= ' ';
1403 $outputPage->addSubtitle( "<div id=\"mw-revision-nav\">" . $cdel .
1404 wfMessage( 'revision-nav' )->rawParams(
1405 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff
1406 )->escaped() . "</div>" );
1410 * View redirect
1412 * @param $target Title|Array of destination(s) to redirect
1413 * @param $appendSubtitle Boolean [optional]
1414 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1415 * @return string containing HMTL with redirect link
1417 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1418 global $wgStylePath;
1420 if ( !is_array( $target ) ) {
1421 $target = array( $target );
1424 $lang = $this->getTitle()->getPageLanguage();
1425 $imageDir = $lang->getDir();
1427 if ( $appendSubtitle ) {
1428 $out = $this->getContext()->getOutput();
1429 $out->addSubtitle( wfMessage( 'redirectpagesub' )->escaped() );
1432 // the loop prepends the arrow image before the link, so the first case needs to be outside
1435 * @var $title Title
1437 $title = array_shift( $target );
1439 if ( $forceKnown ) {
1440 $link = Linker::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1441 } else {
1442 $link = Linker::link( $title, htmlspecialchars( $title->getFullText() ) );
1445 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1446 $alt = $lang->isRTL() ? '←' : '→';
1447 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1448 foreach ( $target as $rt ) {
1449 $link .= Html::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1450 if ( $forceKnown ) {
1451 $link .= Linker::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1452 } else {
1453 $link .= Linker::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1457 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1458 return '<div class="redirectMsg">' .
1459 Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1460 '<span class="redirectText">' . $link . '</span></div>';
1464 * Handle action=render
1466 public function render() {
1467 $this->getContext()->getOutput()->setArticleBodyOnly( true );
1468 $this->view();
1472 * action=protect handler
1474 public function protect() {
1475 $form = new ProtectionForm( $this );
1476 $form->execute();
1480 * action=unprotect handler (alias)
1482 public function unprotect() {
1483 $this->protect();
1487 * UI entry point for page deletion
1489 public function delete() {
1490 # This code desperately needs to be totally rewritten
1492 $title = $this->getTitle();
1493 $user = $this->getContext()->getUser();
1495 # Check permissions
1496 $permission_errors = $title->getUserPermissionsErrors( 'delete', $user );
1497 if ( count( $permission_errors ) ) {
1498 throw new PermissionsError( 'delete', $permission_errors );
1501 # Read-only check...
1502 if ( wfReadOnly() ) {
1503 throw new ReadOnlyError;
1506 # Better double-check that it hasn't been deleted yet!
1507 $this->mPage->loadPageData( 'fromdbmaster' );
1508 if ( !$this->mPage->exists() ) {
1509 $deleteLogPage = new LogPage( 'delete' );
1510 $outputPage = $this->getContext()->getOutput();
1511 $outputPage->setPageTitle( wfMessage( 'cannotdelete-title', $title->getPrefixedText() ) );
1512 $outputPage->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1513 array( 'cannotdelete', wfEscapeWikiText( $title->getPrefixedText() ) )
1515 $outputPage->addHTML(
1516 Xml::element( 'h2', null, $deleteLogPage->getName()->text() )
1518 LogEventsList::showLogExtract(
1519 $outputPage,
1520 'delete',
1521 $title
1524 return;
1527 $request = $this->getContext()->getRequest();
1528 $deleteReasonList = $request->getText( 'wpDeleteReasonList', 'other' );
1529 $deleteReason = $request->getText( 'wpReason' );
1531 if ( $deleteReasonList == 'other' ) {
1532 $reason = $deleteReason;
1533 } elseif ( $deleteReason != '' ) {
1534 // Entry from drop down menu + additional comment
1535 $colonseparator = wfMessage( 'colon-separator' )->inContentLanguage()->text();
1536 $reason = $deleteReasonList . $colonseparator . $deleteReason;
1537 } else {
1538 $reason = $deleteReasonList;
1541 if ( $request->wasPosted() && $user->matchEditToken( $request->getVal( 'wpEditToken' ),
1542 array( 'delete', $this->getTitle()->getPrefixedText() ) ) )
1544 # Flag to hide all contents of the archived revisions
1545 $suppress = $request->getVal( 'wpSuppress' ) && $user->isAllowed( 'suppressrevision' );
1547 $this->doDelete( $reason, $suppress );
1549 WatchAction::doWatchOrUnwatch( $request->getCheck( 'wpWatch' ), $title, $user );
1551 return;
1554 // Generate deletion reason
1555 $hasHistory = false;
1556 if ( !$reason ) {
1557 try {
1558 $reason = $this->generateReason( $hasHistory );
1559 } catch ( MWException $e ) {
1560 # if a page is horribly broken, we still want to be able to delete it. so be lenient about errors here.
1561 wfDebug( "Error while building auto delete summary: $e" );
1562 $reason = '';
1566 // If the page has a history, insert a warning
1567 if ( $hasHistory ) {
1568 $revisions = $this->mTitle->estimateRevisionCount();
1569 // @todo FIXME: i18n issue/patchwork message
1570 $this->getContext()->getOutput()->addHTML( '<strong class="mw-delete-warning-revisions">' .
1571 wfMessage( 'historywarning' )->numParams( $revisions )->parse() .
1572 wfMessage( 'word-separator' )->plain() . Linker::linkKnown( $title,
1573 wfMessage( 'history' )->escaped(),
1574 array( 'rel' => 'archives' ),
1575 array( 'action' => 'history' ) ) .
1576 '</strong>'
1579 if ( $this->mTitle->isBigDeletion() ) {
1580 global $wgDeleteRevisionsLimit;
1581 $this->getContext()->getOutput()->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1582 array( 'delete-warning-toobig', $this->getContext()->getLanguage()->formatNum( $wgDeleteRevisionsLimit ) ) );
1586 $this->confirmDelete( $reason );
1590 * Output deletion confirmation dialog
1591 * @todo FIXME: Move to another file?
1592 * @param string $reason prefilled reason
1594 public function confirmDelete( $reason ) {
1595 wfDebug( "Article::confirmDelete\n" );
1597 $outputPage = $this->getContext()->getOutput();
1598 $outputPage->setPageTitle( wfMessage( 'delete-confirm', $this->getTitle()->getPrefixedText() ) );
1599 $outputPage->addBacklinkSubtitle( $this->getTitle() );
1600 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1601 $outputPage->addWikiMsg( 'confirmdeletetext' );
1603 wfRunHooks( 'ArticleConfirmDelete', array( $this, $outputPage, &$reason ) );
1605 $user = $this->getContext()->getUser();
1607 if ( $user->isAllowed( 'suppressrevision' ) ) {
1608 $suppress = "<tr id=\"wpDeleteSuppressRow\">
1609 <td></td>
1610 <td class='mw-input'><strong>" .
1611 Xml::checkLabel( wfMessage( 'revdelete-suppress' )->text(),
1612 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
1613 "</strong></td>
1614 </tr>";
1615 } else {
1616 $suppress = '';
1618 $checkWatch = $user->getBoolOption( 'watchdeletion' ) || $user->isWatched( $this->getTitle() );
1620 $form = Xml::openElement( 'form', array( 'method' => 'post',
1621 'action' => $this->getTitle()->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
1622 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
1623 Xml::tags( 'legend', null, wfMessage( 'delete-legend' )->escaped() ) .
1624 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
1625 "<tr id=\"wpDeleteReasonListRow\">
1626 <td class='mw-label'>" .
1627 Xml::label( wfMessage( 'deletecomment' )->text(), 'wpDeleteReasonList' ) .
1628 "</td>
1629 <td class='mw-input'>" .
1630 Xml::listDropDown( 'wpDeleteReasonList',
1631 wfMessage( 'deletereason-dropdown' )->inContentLanguage()->text(),
1632 wfMessage( 'deletereasonotherlist' )->inContentLanguage()->text(), '', 'wpReasonDropDown', 1 ) .
1633 "</td>
1634 </tr>
1635 <tr id=\"wpDeleteReasonRow\">
1636 <td class='mw-label'>" .
1637 Xml::label( wfMessage( 'deleteotherreason' )->text(), 'wpReason' ) .
1638 "</td>
1639 <td class='mw-input'>" .
1640 Html::input( 'wpReason', $reason, 'text', array(
1641 'size' => '60',
1642 'maxlength' => '255',
1643 'tabindex' => '2',
1644 'id' => 'wpReason',
1645 'autofocus'
1646 ) ) .
1647 "</td>
1648 </tr>";
1650 # Disallow watching if user is not logged in
1651 if ( $user->isLoggedIn() ) {
1652 $form .= "
1653 <tr>
1654 <td></td>
1655 <td class='mw-input'>" .
1656 Xml::checkLabel( wfMessage( 'watchthis' )->text(),
1657 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
1658 "</td>
1659 </tr>";
1662 $form .= "
1663 $suppress
1664 <tr>
1665 <td></td>
1666 <td class='mw-submit'>" .
1667 Xml::submitButton( wfMessage( 'deletepage' )->text(),
1668 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
1669 "</td>
1670 </tr>" .
1671 Xml::closeElement( 'table' ) .
1672 Xml::closeElement( 'fieldset' ) .
1673 Html::hidden( 'wpEditToken', $user->getEditToken( array( 'delete', $this->getTitle()->getPrefixedText() ) ) ) .
1674 Xml::closeElement( 'form' );
1676 if ( $user->isAllowed( 'editinterface' ) ) {
1677 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
1678 $link = Linker::link(
1679 $title,
1680 wfMessage( 'delete-edit-reasonlist' )->escaped(),
1681 array(),
1682 array( 'action' => 'edit' )
1684 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
1687 $outputPage->addHTML( $form );
1689 $deleteLogPage = new LogPage( 'delete' );
1690 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1691 LogEventsList::showLogExtract( $outputPage, 'delete',
1692 $this->getTitle()
1697 * Perform a deletion and output success or failure messages
1698 * @param $reason
1699 * @param $suppress bool
1701 public function doDelete( $reason, $suppress = false ) {
1702 $error = '';
1703 $outputPage = $this->getContext()->getOutput();
1704 $status = $this->mPage->doDeleteArticleReal( $reason, $suppress, 0, true, $error );
1705 if ( $status->isGood() ) {
1706 $deleted = $this->getTitle()->getPrefixedText();
1708 $outputPage->setPageTitle( wfMessage( 'actioncomplete' ) );
1709 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1711 $loglink = '[[Special:Log/delete|' . wfMessage( 'deletionlog' )->text() . ']]';
1713 $outputPage->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1714 $outputPage->returnToMain( false );
1715 } else {
1716 $outputPage->setPageTitle( wfMessage( 'cannotdelete-title', $this->getTitle()->getPrefixedText() ) );
1717 if ( $error == '' ) {
1718 $outputPage->addWikiText(
1719 "<div class=\"error mw-error-cannotdelete\">\n" . $status->getWikiText() . "\n</div>"
1721 $deleteLogPage = new LogPage( 'delete' );
1722 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1724 LogEventsList::showLogExtract(
1725 $outputPage,
1726 'delete',
1727 $this->getTitle()
1729 } else {
1730 $outputPage->addHTML( $error );
1735 /* Caching functions */
1738 * checkLastModified returns true if it has taken care of all
1739 * output to the client that is necessary for this request.
1740 * (that is, it has sent a cached version of the page)
1742 * @return boolean true if cached version send, false otherwise
1744 protected function tryFileCache() {
1745 static $called = false;
1747 if ( $called ) {
1748 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1749 return false;
1752 $called = true;
1753 if ( $this->isFileCacheable() ) {
1754 $cache = HTMLFileCache::newFromTitle( $this->getTitle(), 'view' );
1755 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1756 wfDebug( "Article::tryFileCache(): about to load file\n" );
1757 $cache->loadFromFileCache( $this->getContext() );
1758 return true;
1759 } else {
1760 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1761 ob_start( array( &$cache, 'saveToFileCache' ) );
1763 } else {
1764 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1767 return false;
1771 * Check if the page can be cached
1772 * @return bool
1774 public function isFileCacheable() {
1775 $cacheable = false;
1777 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
1778 $cacheable = $this->mPage->getID()
1779 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
1780 // Extension may have reason to disable file caching on some pages.
1781 if ( $cacheable ) {
1782 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
1786 return $cacheable;
1789 /**#@-*/
1792 * Lightweight method to get the parser output for a page, checking the parser cache
1793 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1794 * consider, so it's not appropriate to use there.
1796 * @since 1.16 (r52326) for LiquidThreads
1798 * @param $oldid mixed integer Revision ID or null
1799 * @param $user User The relevant user
1800 * @return ParserOutput or false if the given revision ID is not found
1802 public function getParserOutput( $oldid = null, User $user = null ) {
1803 //XXX: bypasses mParserOptions and thus setParserOptions()
1805 if ( $user === null ) {
1806 $parserOptions = $this->getParserOptions();
1807 } else {
1808 $parserOptions = $this->mPage->makeParserOptions( $user );
1811 return $this->mPage->getParserOutput( $parserOptions, $oldid );
1815 * Override the ParserOptions used to render the primary article wikitext.
1817 * @param ParserOptions $options
1818 * @throws MWException if the parser options where already initialized.
1820 public function setParserOptions( ParserOptions $options ) {
1821 if ( $this->mParserOptions ) {
1822 throw new MWException( "can't change parser options after they have already been set" );
1825 // clone, so if $options is modified later, it doesn't confuse the parser cache.
1826 $this->mParserOptions = clone $options;
1830 * Get parser options suitable for rendering the primary article wikitext
1831 * @return ParserOptions
1833 public function getParserOptions() {
1834 if ( !$this->mParserOptions ) {
1835 $this->mParserOptions = $this->mPage->makeParserOptions( $this->getContext() );
1837 // Clone to allow modifications of the return value without affecting cache
1838 return clone $this->mParserOptions;
1842 * Sets the context this Article is executed in
1844 * @param $context IContextSource
1845 * @since 1.18
1847 public function setContext( $context ) {
1848 $this->mContext = $context;
1852 * Gets the context this Article is executed in
1854 * @return IContextSource
1855 * @since 1.18
1857 public function getContext() {
1858 if ( $this->mContext instanceof IContextSource ) {
1859 return $this->mContext;
1860 } else {
1861 wfDebug( __METHOD__ . " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
1862 return RequestContext::getMain();
1867 * Info about this page
1868 * @deprecated since 1.19
1870 public function info() {
1871 wfDeprecated( __METHOD__, '1.19' );
1872 Action::factory( 'info', $this )->show();
1876 * Mark this particular edit/page as patrolled
1877 * @deprecated since 1.18
1879 public function markpatrolled() {
1880 wfDeprecated( __METHOD__, '1.18' );
1881 Action::factory( 'markpatrolled', $this )->show();
1885 * Handle action=purge
1886 * @deprecated since 1.19
1887 * @return Action|bool|null false if the action is disabled, null if it is not recognised
1889 public function purge() {
1890 return Action::factory( 'purge', $this )->show();
1894 * Handle action=revert
1895 * @deprecated since 1.19
1897 public function revert() {
1898 wfDeprecated( __METHOD__, '1.19' );
1899 Action::factory( 'revert', $this )->show();
1903 * Handle action=rollback
1904 * @deprecated since 1.19
1906 public function rollback() {
1907 wfDeprecated( __METHOD__, '1.19' );
1908 Action::factory( 'rollback', $this )->show();
1912 * User-interface handler for the "watch" action.
1913 * Requires Request to pass a token as of 1.18.
1914 * @deprecated since 1.18
1916 public function watch() {
1917 wfDeprecated( __METHOD__, '1.18' );
1918 Action::factory( 'watch', $this )->show();
1922 * Add this page to the current user's watchlist
1924 * This is safe to be called multiple times
1926 * @return bool true on successful watch operation
1927 * @deprecated since 1.18
1929 public function doWatch() {
1930 wfDeprecated( __METHOD__, '1.18' );
1931 return WatchAction::doWatch( $this->getTitle(), $this->getContext()->getUser() );
1935 * User interface handler for the "unwatch" action.
1936 * Requires Request to pass a token as of 1.18.
1937 * @deprecated since 1.18
1939 public function unwatch() {
1940 wfDeprecated( __METHOD__, '1.18' );
1941 Action::factory( 'unwatch', $this )->show();
1945 * Stop watching a page
1946 * @return bool true on successful unwatch
1947 * @deprecated since 1.18
1949 public function doUnwatch() {
1950 wfDeprecated( __METHOD__, '1.18' );
1951 return WatchAction::doUnwatch( $this->getTitle(), $this->getContext()->getUser() );
1955 * Output a redirect back to the article.
1956 * This is typically used after an edit.
1958 * @deprecated in 1.18; call OutputPage::redirect() directly
1959 * @param $noRedir Boolean: add redirect=no
1960 * @param string $sectionAnchor section to redirect to, including "#"
1961 * @param string $extraQuery extra query params
1963 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1964 wfDeprecated( __METHOD__, '1.18' );
1965 if ( $noRedir ) {
1966 $query = 'redirect=no';
1967 if ( $extraQuery ) {
1968 $query .= "&$extraQuery";
1970 } else {
1971 $query = $extraQuery;
1974 $this->getContext()->getOutput()->redirect( $this->getTitle()->getFullURL( $query ) . $sectionAnchor );
1978 * Use PHP's magic __get handler to handle accessing of
1979 * raw WikiPage fields for backwards compatibility.
1981 * @param string $fname Field name
1983 public function __get( $fname ) {
1984 if ( property_exists( $this->mPage, $fname ) ) {
1985 #wfWarn( "Access to raw $fname field " . __CLASS__ );
1986 return $this->mPage->$fname;
1988 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE );
1992 * Use PHP's magic __set handler to handle setting of
1993 * raw WikiPage fields for backwards compatibility.
1995 * @param string $fname Field name
1996 * @param $fvalue mixed New value
1998 public function __set( $fname, $fvalue ) {
1999 if ( property_exists( $this->mPage, $fname ) ) {
2000 #wfWarn( "Access to raw $fname field of " . __CLASS__ );
2001 $this->mPage->$fname = $fvalue;
2002 // Note: extensions may want to toss on new fields
2003 } elseif ( !in_array( $fname, array( 'mContext', 'mPage' ) ) ) {
2004 $this->mPage->$fname = $fvalue;
2005 } else {
2006 trigger_error( 'Inaccessible property via __set(): ' . $fname, E_USER_NOTICE );
2011 * Use PHP's magic __call handler to transform instance calls to
2012 * WikiPage functions for backwards compatibility.
2014 * @param string $fname Name of called method
2015 * @param array $args Arguments to the method
2016 * @return mixed
2018 public function __call( $fname, $args ) {
2019 if ( is_callable( array( $this->mPage, $fname ) ) ) {
2020 #wfWarn( "Call to " . __CLASS__ . "::$fname; please use WikiPage instead" );
2021 return call_user_func_array( array( $this->mPage, $fname ), $args );
2023 trigger_error( 'Inaccessible function via __call(): ' . $fname, E_USER_ERROR );
2026 // ****** B/C functions to work-around PHP silliness with __call and references ****** //
2029 * @param $limit array
2030 * @param $expiry array
2031 * @param $cascade bool
2032 * @param $reason string
2033 * @param $user User
2034 * @return Status
2036 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
2037 return $this->mPage->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user );
2041 * @param $limit array
2042 * @param $reason string
2043 * @param $cascade int
2044 * @param $expiry array
2045 * @return bool
2047 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2048 return $this->mPage->doUpdateRestrictions(
2049 $limit,
2050 $expiry,
2051 $cascade,
2052 $reason,
2053 $this->getContext()->getUser()
2058 * @param $reason string
2059 * @param $suppress bool
2060 * @param $id int
2061 * @param $commit bool
2062 * @param $error string
2063 * @return bool
2065 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
2066 return $this->mPage->doDeleteArticle( $reason, $suppress, $id, $commit, $error );
2070 * @param $fromP
2071 * @param $summary
2072 * @param $token
2073 * @param $bot
2074 * @param $resultDetails
2075 * @param $user User
2076 * @return array
2078 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails, User $user = null ) {
2079 $user = is_null( $user ) ? $this->getContext()->getUser() : $user;
2080 return $this->mPage->doRollback( $fromP, $summary, $token, $bot, $resultDetails, $user );
2084 * @param $fromP
2085 * @param $summary
2086 * @param $bot
2087 * @param $resultDetails
2088 * @param $guser User
2089 * @return array
2091 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
2092 $guser = is_null( $guser ) ? $this->getContext()->getUser() : $guser;
2093 return $this->mPage->commitRollback( $fromP, $summary, $bot, $resultDetails, $guser );
2097 * @param $hasHistory bool
2098 * @return mixed
2100 public function generateReason( &$hasHistory ) {
2101 $title = $this->mPage->getTitle();
2102 $handler = ContentHandler::getForTitle( $title );
2103 return $handler->getAutoDeleteReason( $title, $hasHistory );
2106 // ****** B/C functions for static methods ( __callStatic is PHP>=5.3 ) ****** //
2109 * @return array
2111 public static function selectFields() {
2112 return WikiPage::selectFields();
2116 * @param $title Title
2118 public static function onArticleCreate( $title ) {
2119 WikiPage::onArticleCreate( $title );
2123 * @param $title Title
2125 public static function onArticleDelete( $title ) {
2126 WikiPage::onArticleDelete( $title );
2130 * @param $title Title
2132 public static function onArticleEdit( $title ) {
2133 WikiPage::onArticleEdit( $title );
2137 * @param $oldtext
2138 * @param $newtext
2139 * @param $flags
2140 * @return string
2141 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
2143 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2144 return WikiPage::getAutosummary( $oldtext, $newtext, $flags );
2146 // ******