8 * Class for viewing MediaWiki article and history.
10 * This maintains WikiPage functions for backwards compatibility.
12 * @TODO: move and rewrite code to an Action class
14 * See design.txt for an overview.
15 * Note: edit user interface and cache support functions have been
16 * moved to separate EditPage and HTMLFileCache classes.
18 * @internal documentation reviewed 15 Mar 2010
20 class Article
extends Page
{
36 var $mContentLoaded = false; // !<
42 var $mRedirectedFrom = null;
45 * @var mixed: boolean false or URL string
47 var $mRedirectUrl = false; // !<
48 var $mRevIdFetched = 0; // !<
53 var $mRevision = null;
63 * Constructor and clear the article
64 * @param $title Title Reference to a Title object.
65 * @param $oldId Integer revision ID, null to fetch from request, zero for current
67 public function __construct( Title
$title, $oldId = null ) {
68 $this->mOldId
= $oldId;
69 $this->mPage
= $this->newPage( $title );
72 protected function newPage( Title
$title ) {
73 return new WikiPage( $title );
77 * Constructor from a page id
78 * @param $id Int article ID to load
80 public static function newFromID( $id ) {
81 $t = Title
::newFromID( $id );
82 # @todo FIXME: Doesn't inherit right
83 return $t == null ?
null : new self( $t );
84 # return $t == null ? null : new static( $t ); // PHP 5.3
88 * Create an Article object of the appropriate class for the given page.
91 * @param $context RequestContext
92 * @return Article object
94 public static function newFromTitle( $title, RequestContext
$context ) {
95 if ( NS_MEDIA
== $title->getNamespace() ) {
96 // FIXME: where should this go?
97 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
101 wfRunHooks( 'ArticleFromTitle', array( &$title, &$page ) );
103 switch( $title->getNamespace() ) {
105 $page = new ImagePage( $title );
108 $page = new CategoryPage( $title );
111 $page = new Article( $title );
114 $page->setContext( $context );
120 * Tell the page view functions that this view was redirected
121 * from another page on the wiki.
122 * @param $from Title object.
124 public function setRedirectedFrom( Title
$from ) {
125 $this->mRedirectedFrom
= $from;
129 * Get the Title object this text redirects to
131 * @param $text string article content containing redirect info
132 * @return mixed false, Title of in-wiki target, or string with URL
133 * @deprecated since 1.17
135 public function followRedirectText( $text ) {
136 // recurse through to only get the final target
137 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
141 * Get the title object of the article
142 * @return Title object of this page
144 public function getTitle() {
145 return $this->mPage
->getTitle();
150 * @todo FIXME: Shouldn't this be public?
153 public function clear() {
154 $this->mContentLoaded
= false;
156 $this->mRedirectedFrom
= null; # Title object if set
157 $this->mRevIdFetched
= 0;
158 $this->mRedirectUrl
= false;
160 $this->mPage
->clear();
164 * Note that getContent/loadContent do not follow redirects anymore.
165 * If you need to fetch redirectable content easily, try
166 * the shortcut in Article::followRedirect()
168 * This function has side effects! Do not use this function if you
169 * only want the real revision text if any.
171 * @return Return the text of this revision
173 public function getContent() {
176 wfProfileIn( __METHOD__
);
178 if ( $this->mPage
->getID() === 0 ) {
179 # If this is a MediaWiki:x message, then load the messages
180 # and return the message value for x.
181 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI
) {
182 $text = $this->getTitle()->getDefaultMessageText();
183 if ( $text === false ) {
187 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
189 wfProfileOut( __METHOD__
);
193 $this->loadContent();
194 wfProfileOut( __METHOD__
);
196 return $this->mContent
;
201 * @return int The oldid of the article that is to be shown, 0 for the
204 public function getOldID() {
205 if ( is_null( $this->mOldId
) ) {
206 $this->mOldId
= $this->getOldIDFromRequest();
209 return $this->mOldId
;
213 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
215 * @return int The old id for the request
217 public function getOldIDFromRequest() {
220 $this->mRedirectUrl
= false;
222 $oldid = $wgRequest->getVal( 'oldid' );
224 if ( isset( $oldid ) ) {
225 $oldid = intval( $oldid );
226 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
227 $nextid = $this->getTitle()->getNextRevisionID( $oldid );
231 $this->mRedirectUrl
= $this->getTitle()->getFullURL( 'redirect=no' );
233 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
234 $previd = $this->getTitle()->getPreviousRevisionID( $oldid );
249 * Load the revision (including text) into this object
251 function loadContent() {
252 if ( $this->mContentLoaded
) {
256 wfProfileIn( __METHOD__
);
258 $this->fetchContent( $this->getOldID() );
260 wfProfileOut( __METHOD__
);
264 * Get text of an article from database
265 * Does *NOT* follow redirects.
267 * @param $oldid Int: 0 for whatever the latest revision is
268 * @return mixed string containing article contents, or false if null
270 function fetchContent( $oldid = 0 ) {
271 if ( $this->mContentLoaded
) {
272 return $this->mContent
;
275 # Pre-fill content with error message so that if something
276 # fails we'll have something telling us what we intended.
277 $t = $this->getTitle()->getPrefixedText();
278 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
279 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
282 $revision = Revision
::newFromId( $oldid );
284 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
287 // Revision title doesn't match the page title given?
288 if ( $this->mPage
->getID() != $revision->getPage() ) {
289 $function = array( get_class( $this->mPage
), 'newFromID' );
290 $this->mPage
= call_user_func( $function, $revision->getPage() );
291 if ( !$this->mPage
->getId() ) {
292 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
297 if ( $this->mPage
->getLatest() === false ) {
298 wfDebug( __METHOD__
. " failed to find page data for title " . $this->getTitle()->getPrefixedText() . "\n" );
302 $revision = $this->mPage
->getRevision();
304 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id " . $this->mPage
->getLatest() . "\n" );
309 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
310 // We should instead work with the Revision object when we need it...
311 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
313 $this->mRevIdFetched
= $revision->getId();
314 $this->mContentLoaded
= true;
315 $this->mRevision
=& $revision;
317 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
319 return $this->mContent
;
324 * @deprecated since 1.18
326 public function forUpdate() {
327 wfDeprecated( __METHOD__
);
331 * Returns true if the currently-referenced revision is the current edit
332 * to this page (and it exists).
335 public function isCurrent() {
336 # If no oldid, this is the current version.
337 if ( $this->getOldID() == 0 ) {
341 return $this->mPage
->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
345 * Use this to fetch the rev ID used on page views
347 * @return int revision ID of last article revision
349 public function getRevIdFetched() {
350 if ( $this->mRevIdFetched
) {
351 return $this->mRevIdFetched
;
353 return $this->mPage
->getLatest();
358 * This is the default action of the index.php entry point: just view the
359 * page of the given title.
361 public function view() {
362 global $wgUser, $wgOut, $wgRequest, $wgParser;
363 global $wgUseFileCache, $wgUseETag;
365 wfProfileIn( __METHOD__
);
367 # Get variables from query string
368 $oldid = $this->getOldID();
370 # getOldID may want us to redirect somewhere else
371 if ( $this->mRedirectUrl
) {
372 $wgOut->redirect( $this->mRedirectUrl
);
373 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
374 wfProfileOut( __METHOD__
);
379 $wgOut->setArticleFlag( true );
380 # Set page title (may be overridden by DISPLAYTITLE)
381 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
383 # If we got diff in the query, we want to see a diff page instead of the article.
384 if ( $wgRequest->getCheck( 'diff' ) ) {
385 wfDebug( __METHOD__
. ": showing diff page\n" );
386 $this->showDiffPage();
387 wfProfileOut( __METHOD__
);
392 # Allow frames by default
393 $wgOut->allowClickjacking();
395 $parserCache = ParserCache
::singleton();
397 $parserOptions = $this->mPage
->getParserOptions();
398 # Render printable version, use printable version cache
399 if ( $wgOut->isPrintable() ) {
400 $parserOptions->setIsPrintable( true );
401 $parserOptions->setEditSection( false );
402 } elseif ( $wgUseETag && !$this->getTitle()->quickUserCan( 'edit' ) ) {
403 $parserOptions->setEditSection( false );
406 # Try client and file cache
407 if ( $oldid === 0 && $this->mPage
->checkTouched() ) {
409 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
412 # Is it client cached?
413 if ( $wgOut->checkLastModified( $this->mPage
->getTouched() ) ) {
414 wfDebug( __METHOD__
. ": done 304\n" );
415 wfProfileOut( __METHOD__
);
419 } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
420 wfDebug( __METHOD__
. ": done file cache\n" );
421 # tell wgOut that output is taken care of
423 $this->mPage
->viewUpdates();
424 wfProfileOut( __METHOD__
);
430 if ( !$wgUseETag && !$this->getTitle()->quickUserCan( 'edit' ) ) {
431 $parserOptions->setEditSection( false );
434 # Should the parser cache be used?
435 $useParserCache = $this->useParserCache( $oldid );
436 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
437 if ( $wgUser->getStubThreshold() ) {
438 wfIncrStats( 'pcache_miss_stub' );
441 $wasRedirected = $this->showRedirectedFromHeader();
442 $this->showNamespaceHeader();
444 # Iterate through the possible ways of constructing the output text.
445 # Keep going until $outputDone is set, or we run out of things to do.
448 $this->mParserOutput
= false;
450 while ( !$outputDone && ++
$pass ) {
453 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
456 # Try the parser cache
457 if ( $useParserCache ) {
458 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
460 if ( $this->mParserOutput
!== false ) {
461 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
462 $wgOut->addParserOutput( $this->mParserOutput
);
463 # Ensure that UI elements requiring revision ID have
464 # the correct version information.
465 $wgOut->setRevisionId( $this->mPage
->getLatest() );
467 # Preload timestamp to avoid a DB hit
468 if ( isset( $this->mParserOutput
->mTimestamp
) ) {
469 $this->mPage
->setTimestamp( $this->mParserOutput
->mTimestamp
);
475 $text = $this->getContent();
476 if ( $text === false ||
$this->mPage
->getID() == 0 ) {
477 wfDebug( __METHOD__
. ": showing missing article\n" );
478 $this->showMissingArticle();
479 wfProfileOut( __METHOD__
);
483 # Another whitelist check in case oldid is altering the title
484 if ( !$this->getTitle()->userCanRead() ) {
485 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
486 $wgOut->loginToUse();
489 wfProfileOut( __METHOD__
);
493 # Are we looking at an old revision
494 if ( $oldid && !is_null( $this->mRevision
) ) {
495 $this->setOldSubtitle( $oldid );
497 if ( !$this->showDeletedRevisionHeader() ) {
498 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
499 wfProfileOut( __METHOD__
);
503 # If this "old" version is the current, then try the parser cache...
504 if ( $oldid === $this->mPage
->getLatest() && $this->useParserCache( false ) ) {
505 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
506 if ( $this->mParserOutput
) {
507 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
508 $wgOut->addParserOutput( $this->mParserOutput
);
509 $wgOut->setRevisionId( $this->mPage
->getLatest() );
516 # Ensure that UI elements requiring revision ID have
517 # the correct version information.
518 $wgOut->setRevisionId( $this->getRevIdFetched() );
520 # Pages containing custom CSS or JavaScript get special treatment
521 if ( $this->getTitle()->isCssOrJsPage() ||
$this->getTitle()->isCssJsSubpage() ) {
522 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
523 $this->showCssOrJsPage();
526 $rt = Title
::newFromRedirectArray( $text );
528 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
529 # Viewing a redirect page (e.g. with parameter redirect=no)
530 # Don't append the subtitle if this was an old revision
531 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
532 # Parse just to get categories, displaytitle, etc.
533 $this->mParserOutput
= $wgParser->parse( $text, $this->getTitle(), $parserOptions );
534 $wgOut->addParserOutputNoText( $this->mParserOutput
);
540 # Run the parse, protected by a pool counter
541 wfDebug( __METHOD__
. ": doing uncached parse\n" );
543 $key = $parserCache->getKey( $this, $parserOptions );
544 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
546 if ( !$poolArticleView->execute() ) {
547 # Connection or timeout error
548 wfProfileOut( __METHOD__
);
554 # Should be unreachable, but just in case...
560 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
561 if ( $this->mParserOutput
) {
562 $titleText = $this->mParserOutput
->getTitleText();
564 if ( strval( $titleText ) !== '' ) {
565 $wgOut->setPageTitle( $titleText );
569 # For the main page, overwrite the <title> element with the con-
570 # tents of 'pagetitle-view-mainpage' instead of the default (if
572 # This message always exists because it is in the i18n files
573 if ( $this->getTitle()->equals( Title
::newMainPage() ) ) {
574 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
575 if ( !$msg->isDisabled() ) {
576 $wgOut->setHTMLTitle( $msg->title( $this->getTitle() )->text() );
580 # Now that we've filled $this->mParserOutput, we know whether
581 # there are any __NOINDEX__ tags on the page
582 $policy = $this->getRobotPolicy( 'view' );
583 $wgOut->setIndexPolicy( $policy['index'] );
584 $wgOut->setFollowPolicy( $policy['follow'] );
586 $this->showViewFooter();
587 $this->mPage
->viewUpdates();
588 wfProfileOut( __METHOD__
);
592 * Show a diff page according to current request variables. For use within
593 * Article::view() only, other callers should use the DifferenceEngine class.
595 public function showDiffPage() {
596 global $wgRequest, $wgUser;
598 $diff = $wgRequest->getVal( 'diff' );
599 $rcid = $wgRequest->getVal( 'rcid' );
600 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
601 $purge = $wgRequest->getVal( 'action' ) == 'purge';
602 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
603 $oldid = $this->getOldID();
605 $de = new DifferenceEngine( $this->getTitle(), $oldid, $diff, $rcid, $purge, $unhide );
606 // DifferenceEngine directly fetched the revision:
607 $this->mRevIdFetched
= $de->mNewid
;
608 $de->showDiffPage( $diffOnly );
610 if ( $diff == 0 ||
$diff == $this->mPage
->getLatest() ) {
611 # Run view updates for current revision only
612 $this->mPage
->viewUpdates();
617 * Show a page view for a page formatted as CSS or JavaScript. To be called by
618 * Article::view() only.
620 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
623 protected function showCssOrJsPage() {
626 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
628 // Give hooks a chance to customise the output
629 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->getTitle(), $wgOut ) ) ) {
630 // Wrap the whole lot in a <pre> and don't parse
632 preg_match( '!\.(css|js)$!u', $this->getTitle()->getText(), $m );
633 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
634 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
635 $wgOut->addHTML( "\n</pre>\n" );
640 * Get the robot policy to be used for the current view
641 * @param $action String the action= GET parameter
642 * @return Array the policy that should be set
643 * TODO: actions other than 'view'
645 public function getRobotPolicy( $action ) {
646 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
647 global $wgDefaultRobotPolicy, $wgRequest;
649 $ns = $this->getTitle()->getNamespace();
651 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
652 # Don't index user and user talk pages for blocked users (bug 11443)
653 if ( !$this->getTitle()->isSubpage() ) {
654 if ( Block
::newFromTarget( null, $this->getTitle()->getText() ) instanceof Block
) {
656 'index' => 'noindex',
657 'follow' => 'nofollow'
663 if ( $this->mPage
->getID() === 0 ||
$this->getOldID() ) {
664 # Non-articles (special pages etc), and old revisions
666 'index' => 'noindex',
667 'follow' => 'nofollow'
669 } elseif ( $wgOut->isPrintable() ) {
670 # Discourage indexing of printable versions, but encourage following
672 'index' => 'noindex',
675 } elseif ( $wgRequest->getInt( 'curid' ) ) {
676 # For ?curid=x urls, disallow indexing
678 'index' => 'noindex',
683 # Otherwise, construct the policy based on the various config variables.
684 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
686 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
687 # Honour customised robot policies for this namespace
688 $policy = array_merge(
690 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
693 if ( $this->getTitle()->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
694 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
695 # a final sanity check that we have really got the parser output.
696 $policy = array_merge(
698 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
702 if ( isset( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] ) ) {
703 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
704 $policy = array_merge(
706 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] )
714 * Converts a String robot policy into an associative array, to allow
715 * merging of several policies using array_merge().
716 * @param $policy Mixed, returns empty array on null/false/'', transparent
717 * to already-converted arrays, converts String.
718 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
720 public static function formatRobotPolicy( $policy ) {
721 if ( is_array( $policy ) ) {
723 } elseif ( !$policy ) {
727 $policy = explode( ',', $policy );
728 $policy = array_map( 'trim', $policy );
731 foreach ( $policy as $var ) {
732 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
733 $arr['index'] = $var;
734 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
735 $arr['follow'] = $var;
743 * If this request is a redirect view, send "redirected from" subtitle to
744 * $wgOut. Returns true if the header was needed, false if this is not a
745 * redirect view. Handles both local and remote redirects.
749 public function showRedirectedFromHeader() {
750 global $wgOut, $wgRequest, $wgRedirectSources;
752 $rdfrom = $wgRequest->getVal( 'rdfrom' );
754 if ( isset( $this->mRedirectedFrom
) ) {
755 // This is an internally redirected page view.
756 // We'll need a backlink to the source page for navigation.
757 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
758 $redir = Linker
::link(
759 $this->mRedirectedFrom
,
762 array( 'redirect' => 'no' ),
763 array( 'known', 'noclasses' )
766 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
767 $wgOut->setSubtitle( $s );
769 // Set the fragment if one was specified in the redirect
770 if ( strval( $this->getTitle()->getFragment() ) != '' ) {
771 $fragment = Xml
::escapeJsString( $this->getTitle()->getFragmentForURL() );
772 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
775 // Add a <link rel="canonical"> tag
776 $wgOut->addLink( array( 'rel' => 'canonical',
777 'href' => $this->getTitle()->getLocalURL() )
782 } elseif ( $rdfrom ) {
783 // This is an externally redirected view, from some other wiki.
784 // If it was reported from a trusted site, supply a backlink.
785 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
786 $redir = Linker
::makeExternalLink( $rdfrom, $rdfrom );
787 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
788 $wgOut->setSubtitle( $s );
798 * Show a header specific to the namespace currently being viewed, like
799 * [[MediaWiki:Talkpagetext]]. For Article::view().
801 public function showNamespaceHeader() {
804 if ( $this->getTitle()->isTalkPage() ) {
805 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
806 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
812 * Show the footer section of an ordinary page view
814 public function showViewFooter() {
815 global $wgOut, $wgUseTrackbacks;
817 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
818 if ( $this->getTitle()->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->getTitle()->getText() ) ) {
819 $wgOut->addWikiMsg( 'anontalkpagetext' );
822 # If we have been passed an &rcid= parameter, we want to give the user a
823 # chance to mark this new article as patrolled.
824 $this->showPatrolFooter();
827 if ( $wgUseTrackbacks ) {
828 $this->addTrackbacks();
831 wfRunHooks( 'ArticleViewFooter', array( $this ) );
836 * If patrol is possible, output a patrol UI box. This is called from the
837 * footer section of ordinary page views. If patrol is not possible or not
838 * desired, does nothing.
840 public function showPatrolFooter() {
841 global $wgOut, $wgRequest, $wgUser;
843 $rcid = $wgRequest->getVal( 'rcid' );
845 if ( !$rcid ||
!$this->getTitle()->quickUserCan( 'patrol' ) ) {
849 $token = $wgUser->editToken( $rcid );
850 $wgOut->preventClickjacking();
853 "<div class='patrollink'>" .
855 'markaspatrolledlink',
858 wfMsgHtml( 'markaspatrolledtext' ),
861 'action' => 'markpatrolled',
865 array( 'known', 'noclasses' )
873 * Show the error text for a missing article. For articles in the MediaWiki
874 * namespace, show the default message text. To be called from Article::view().
876 public function showMissingArticle() {
877 global $wgOut, $wgRequest, $wgUser;
879 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
880 if ( $this->getTitle()->getNamespace() == NS_USER ||
$this->getTitle()->getNamespace() == NS_USER_TALK
) {
881 $parts = explode( '/', $this->getTitle()->getText() );
882 $rootPart = $parts[0];
883 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
884 $ip = User
::isIP( $rootPart );
886 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
887 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
888 array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
889 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
890 LogEventsList
::showLogExtract(
893 $user->getUserPage()->getPrefixedText(),
897 'showIfEmpty' => false,
899 'blocked-notice-logextract',
900 $user->getName() # Support GENDER in notice
907 wfRunHooks( 'ShowMissingArticle', array( $this ) );
909 # Show delete and move logs
910 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->getTitle()->getPrefixedText(), '',
912 'conds' => array( "log_action != 'revision'" ),
913 'showIfEmpty' => false,
914 'msgKey' => array( 'moveddeleted-notice' ) )
918 $oldid = $this->getOldID();
920 $text = wfMsgNoTrans( 'missing-article',
921 $this->getTitle()->getPrefixedText(),
922 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
923 } elseif ( $this->getTitle()->getNamespace() === NS_MEDIAWIKI
) {
924 // Use the default message text
925 $text = $this->getTitle()->getDefaultMessageText();
927 $createErrors = $this->getTitle()->getUserPermissionsErrors( 'create', $wgUser );
928 $editErrors = $this->getTitle()->getUserPermissionsErrors( 'edit', $wgUser );
929 $errors = array_merge( $createErrors, $editErrors );
931 if ( !count( $errors ) ) {
932 $text = wfMsgNoTrans( 'noarticletext' );
934 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
937 $text = "<div class='noarticletext'>\n$text\n</div>";
939 if ( !$this->mPage
->hasViewableContent() ) {
940 // If there's no backing content, send a 404 Not Found
941 // for better machine handling of broken links.
942 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
945 $wgOut->addWikiText( $text );
949 * If the revision requested for view is deleted, check permissions.
950 * Send either an error message or a warning header to $wgOut.
952 * @return boolean true if the view is allowed, false if not.
954 public function showDeletedRevisionHeader() {
955 global $wgOut, $wgRequest;
957 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
962 // If the user is not allowed to see it...
963 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
964 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
965 'rev-deleted-text-permission' );
968 // If the user needs to confirm that they want to see it...
969 } elseif ( $wgRequest->getInt( 'unhide' ) != 1 ) {
970 # Give explanation and add a link to view the revision...
971 $oldid = intval( $this->getOldID() );
972 $link = $this->getTitle()->getFullUrl( "oldid={$oldid}&unhide=1" );
973 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
974 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
975 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
976 array( $msg, $link ) );
979 // We are allowed to see...
981 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
982 'rev-suppressed-text-view' : 'rev-deleted-text-view';
983 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
990 * Execute the uncached parse for action=view
992 public function doViewParse() {
995 $oldid = $this->getOldID();
996 $parserOptions = $this->mPage
->getParserOptions();
998 # Render printable version, use printable version cache
999 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1001 # Don't show section-edit links on old revisions... this way lies madness.
1002 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->getTitle()->quickUserCan( 'edit' ) ) {
1003 $parserOptions->setEditSection( false );
1006 $useParserCache = $this->useParserCache( $oldid );
1007 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1013 * Try to fetch an expired entry from the parser cache. If it is present,
1014 * output it and return true. If it is not present, output nothing and
1015 * return false. This is used as a callback function for
1016 * PoolCounter::executeProtected().
1020 public function tryDirtyCache() {
1022 $parserCache = ParserCache
::singleton();
1023 $options = $this->mPage
->getParserOptions();
1025 if ( $wgOut->isPrintable() ) {
1026 $options->setIsPrintable( true );
1027 $options->setEditSection( false );
1030 $output = $parserCache->getDirty( $this, $options );
1033 wfDebug( __METHOD__
. ": sending dirty output\n" );
1034 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1035 $wgOut->setSquidMaxage( 0 );
1036 $this->mParserOutput
= $output;
1037 $wgOut->addParserOutput( $output );
1038 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1042 wfDebugLog( 'dirty', "dirty missing\n" );
1043 wfDebug( __METHOD__
. ": no dirty cache\n" );
1052 * @param $target Title|Array of destination(s) to redirect
1053 * @param $appendSubtitle Boolean [optional]
1054 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1055 * @return string containing HMTL with redirect link
1057 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1058 global $wgOut, $wgStylePath;
1060 if ( !is_array( $target ) ) {
1061 $target = array( $target );
1064 $imageDir = wfUILang()->getDir();
1066 if ( $appendSubtitle ) {
1067 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1070 // the loop prepends the arrow image before the link, so the first case needs to be outside
1071 $title = array_shift( $target );
1073 if ( $forceKnown ) {
1074 $link = Linker
::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1076 $link = Linker
::link( $title, htmlspecialchars( $title->getFullText() ) );
1079 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1080 $alt = wfUILang()->isRTL() ?
'←' : '→';
1081 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1082 foreach ( $target as $rt ) {
1083 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1084 if ( $forceKnown ) {
1085 $link .= Linker
::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1087 $link .= Linker
::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1091 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1092 return '<div class="redirectMsg">' .
1093 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1094 '<span class="redirectText">' . $link . '</span></div>';
1098 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1100 public function addTrackbacks() {
1103 $dbr = wfGetDB( DB_SLAVE
);
1104 $tbs = $dbr->select( 'trackbacks',
1105 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1106 array( 'tb_page' => $this->mPage
->getID() )
1109 if ( !$dbr->numRows( $tbs ) ) {
1113 $wgOut->preventClickjacking();
1116 foreach ( $tbs as $o ) {
1119 if ( $this->getContext()->getUser()->isAllowed( 'trackback' ) ) {
1120 $delurl = $this->getTitle()->getFullURL( "action=deletetrackback&tbid=" .
1121 $o->tb_id
. "&token=" . urlencode( $this->getContext()->getUser()->editToken() ) );
1122 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1126 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1134 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1138 * Removes trackback record for current article from trackbacks table
1139 * @deprecated since 1.19
1141 public function deletetrackback() {
1142 return Action
::factory( 'deletetrackback', $this )->show();
1146 * Handle action=render
1149 public function render() {
1152 $wgOut->setArticleBodyOnly( true );
1157 * Handle action=purge
1159 public function purge() {
1160 return Action
::factory( 'purge', $this )->show();
1164 * Mark this particular edit/page as patrolled
1165 * @deprecated since 1.19
1167 public function markpatrolled() {
1168 Action
::factory( 'markpatrolled', $this )->show();
1172 * User-interface handler for the "watch" action.
1173 * Requires Request to pass a token as of 1.19.
1174 * @deprecated since 1.18
1176 public function watch() {
1177 Action
::factory( 'watch', $this )->show();
1181 * Add this page to $wgUser's watchlist
1183 * This is safe to be called multiple times
1185 * @return bool true on successful watch operation
1186 * @deprecated since 1.18
1188 public function doWatch() {
1190 return WatchAction
::doWatch( $this->getTitle(), $wgUser );
1194 * User interface handler for the "unwatch" action.
1195 * Requires Request to pass a token as of 1.19.
1196 * @deprecated since 1.18
1198 public function unwatch() {
1199 Action
::factory( 'unwatch', $this )->show();
1203 * Stop watching a page
1204 * @return bool true on successful unwatch
1205 * @deprecated since 1.18
1207 public function doUnwatch() {
1209 return WatchAction
::doUnwatch( $this->getTitle(), $wgUser );
1213 * action=protect handler
1215 public function protect() {
1216 $form = new ProtectionForm( $this );
1221 * action=unprotect handler (alias)
1223 public function unprotect() {
1228 * Info about this page
1229 * Called for ?action=info when $wgAllowPageInfo is on.
1231 public function info() {
1232 Action
::factory( 'info', $this )->show();
1236 * Overriden by ImagePage class, only present here to avoid a fatal error
1237 * Called for ?action=revert
1239 public function revert() {
1240 Action
::factory( 'revert', $this )->show();
1244 * Output a redirect back to the article.
1245 * This is typically used after an edit.
1247 * @deprecated in 1.19; call $wgOut->redirect() directly
1248 * @param $noRedir Boolean: add redirect=no
1249 * @param $sectionAnchor String: section to redirect to, including "#"
1250 * @param $extraQuery String: extra query params
1252 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1253 wfDeprecated( __METHOD__
);
1257 $query = 'redirect=no';
1259 $query .= "&$extraQuery";
1261 $query = $extraQuery;
1264 $wgOut->redirect( $this->getTitle()->getFullURL( $query ) . $sectionAnchor );
1268 * Auto-generates a deletion reason
1270 * @param &$hasHistory Boolean: whether the page has a history
1271 * @return mixed String containing deletion reason or empty string, or boolean false
1272 * if no revision occurred
1274 public function generateReason( &$hasHistory ) {
1277 $dbw = wfGetDB( DB_MASTER
);
1278 // Get the last revision
1279 $rev = Revision
::newFromTitle( $this->getTitle() );
1281 if ( is_null( $rev ) ) {
1285 // Get the article's contents
1286 $contents = $rev->getText();
1289 // If the page is blank, use the text from the previous revision,
1290 // which can only be blank if there's a move/import/protect dummy revision involved
1291 if ( $contents == '' ) {
1292 $prev = $rev->getPrevious();
1295 $contents = $prev->getText();
1300 // Find out if there was only one contributor
1301 // Only scan the last 20 revisions
1302 $res = $dbw->select( 'revision', 'rev_user_text',
1303 array( 'rev_page' => $this->mPage
->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
1305 array( 'LIMIT' => 20 )
1308 if ( $res === false ) {
1309 // This page has no revisions, which is very weird
1313 $hasHistory = ( $res->numRows() > 1 );
1314 $row = $dbw->fetchObject( $res );
1316 if ( $row ) { // $row is false if the only contributor is hidden
1317 $onlyAuthor = $row->rev_user_text
;
1318 // Try to find a second contributor
1319 foreach ( $res as $row ) {
1320 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
1321 $onlyAuthor = false;
1326 $onlyAuthor = false;
1329 // Generate the summary with a '$1' placeholder
1331 // The current revision is blank and the one before is also
1332 // blank. It's just not our lucky day
1333 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
1335 if ( $onlyAuthor ) {
1336 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
1338 $reason = wfMsgForContent( 'excontent', '$1' );
1342 if ( $reason == '-' ) {
1343 // Allow these UI messages to be blanked out cleanly
1347 // Replace newlines with spaces to prevent uglyness
1348 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
1349 // Calculate the maximum amount of chars to get
1350 // Max content length = max comment length - length of the comment (excl. $1)
1351 $maxLength = 255 - ( strlen( $reason ) - 2 );
1352 $contents = $wgContLang->truncate( $contents, $maxLength );
1353 // Remove possible unfinished links
1354 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1355 // Now replace the '$1' placeholder
1356 $reason = str_replace( '$1', $contents, $reason );
1363 * UI entry point for page deletion
1365 public function delete() {
1366 global $wgOut, $wgRequest;
1368 $confirm = $wgRequest->wasPosted() &&
1369 $this->getContext()->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1371 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1372 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1374 $reason = $this->DeleteReasonList
;
1376 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
1377 // Entry from drop down menu + additional comment
1378 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
1379 } elseif ( $reason == 'other' ) {
1380 $reason = $this->DeleteReason
;
1383 # Flag to hide all contents of the archived revisions
1384 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $this->getContext()->getUser()->isAllowed( 'suppressrevision' );
1386 # This code desperately needs to be totally rewritten
1388 # Read-only check...
1389 if ( wfReadOnly() ) {
1390 $wgOut->readOnlyPage();
1396 $permission_errors = $this->getTitle()->getUserPermissionsErrors( 'delete', $this->getContext()->getUser() );
1398 if ( count( $permission_errors ) > 0 ) {
1399 $wgOut->showPermissionsErrorPage( $permission_errors );
1404 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->getTitle()->getPrefixedText() ) );
1406 # Better double-check that it hasn't been deleted yet!
1407 $dbw = wfGetDB( DB_MASTER
);
1408 $conds = $this->getTitle()->pageCond();
1409 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1410 if ( $latest === false ) {
1411 $wgOut->showFatalError(
1414 array( 'class' => 'error mw-error-cannotdelete' ),
1415 wfMsgExt( 'cannotdelete', array( 'parse' ),
1416 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) )
1419 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
1420 LogEventsList
::showLogExtract(
1423 $this->getTitle()->getPrefixedText()
1429 # Hack for big sites
1430 $bigHistory = $this->mPage
->isBigDeletion();
1431 if ( $bigHistory && !$this->getTitle()->userCan( 'bigdelete' ) ) {
1432 global $wgLang, $wgDeleteRevisionsLimit;
1434 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1435 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1441 $this->doDelete( $reason, $suppress );
1443 if ( $wgRequest->getCheck( 'wpWatch' ) && $this->getContext()->getUser()->isLoggedIn() ) {
1445 } elseif ( $this->getTitle()->userIsWatching() ) {
1452 // Generate deletion reason
1453 $hasHistory = false;
1455 $reason = $this->generateReason( $hasHistory );
1458 // If the page has a history, insert a warning
1459 if ( $hasHistory && !$confirm ) {
1462 $revisions = $this->mPage
->estimateRevisionCount();
1463 // @todo FIXME: i18n issue/patchwork message
1464 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
1465 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
1466 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->getTitle(),
1467 wfMsgHtml( 'history' ),
1468 array( 'rel' => 'archives' ),
1469 array( 'action' => 'history' ) ) .
1473 if ( $bigHistory ) {
1474 global $wgDeleteRevisionsLimit;
1475 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1476 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1480 return $this->confirmDelete( $reason );
1484 * Output deletion confirmation dialog
1485 * @todo FIXME: Move to another file?
1486 * @param $reason String: prefilled reason
1488 public function confirmDelete( $reason ) {
1491 wfDebug( "Article::confirmDelete\n" );
1493 $deleteBackLink = Linker
::linkKnown( $this->getTitle() );
1494 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
1495 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1496 $wgOut->addWikiMsg( 'confirmdeletetext' );
1498 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
1500 if ( $this->getContext()->getUser()->isAllowed( 'suppressrevision' ) ) {
1501 $suppress = "<tr id=\"wpDeleteSuppressRow\">
1503 <td class='mw-input'><strong>" .
1504 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
1505 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
1511 $checkWatch = $this->getContext()->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->getTitle()->userIsWatching();
1513 $form = Xml
::openElement( 'form', array( 'method' => 'post',
1514 'action' => $this->getTitle()->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
1515 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
1516 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
1517 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
1518 "<tr id=\"wpDeleteReasonListRow\">
1519 <td class='mw-label'>" .
1520 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
1522 <td class='mw-input'>" .
1523 Xml
::listDropDown( 'wpDeleteReasonList',
1524 wfMsgForContent( 'deletereason-dropdown' ),
1525 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
1528 <tr id=\"wpDeleteReasonRow\">
1529 <td class='mw-label'>" .
1530 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
1532 <td class='mw-input'>" .
1533 Html
::input( 'wpReason', $reason, 'text', array(
1535 'maxlength' => '255',
1543 # Disallow watching if user is not logged in
1544 if ( $this->getContext()->getUser()->isLoggedIn() ) {
1548 <td class='mw-input'>" .
1549 Xml
::checkLabel( wfMsg( 'watchthis' ),
1550 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
1559 <td class='mw-submit'>" .
1560 Xml
::submitButton( wfMsg( 'deletepage' ),
1561 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
1564 Xml
::closeElement( 'table' ) .
1565 Xml
::closeElement( 'fieldset' ) .
1566 Html
::hidden( 'wpEditToken', $this->getContext()->getUser()->editToken() ) .
1567 Xml
::closeElement( 'form' );
1569 if ( $this->getContext()->getUser()->isAllowed( 'editinterface' ) ) {
1570 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
1571 $link = Linker
::link(
1573 wfMsgHtml( 'delete-edit-reasonlist' ),
1575 array( 'action' => 'edit' )
1577 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
1580 $wgOut->addHTML( $form );
1581 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
1582 LogEventsList
::showLogExtract( $wgOut, 'delete',
1583 $this->getTitle()->getPrefixedText()
1588 * Perform a deletion and output success or failure messages
1590 public function doDelete( $reason, $suppress = false ) {
1593 $id = $this->getTitle()->getArticleID( Title
::GAID_FOR_UPDATE
);
1596 if ( $this->mPage
->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
1597 $deleted = $this->getTitle()->getPrefixedText();
1599 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1600 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1602 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
1604 $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1605 $wgOut->returnToMain( false );
1607 if ( $error == '' ) {
1608 $wgOut->showFatalError(
1611 array( 'class' => 'error mw-error-cannotdelete' ),
1612 wfMsgExt( 'cannotdelete', array( 'parse' ),
1613 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) )
1617 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
1619 LogEventsList
::showLogExtract(
1622 $this->getTitle()->getPrefixedText()
1625 $wgOut->showFatalError( $error );
1631 * User interface for rollback operations
1633 public function rollback() {
1634 global $wgUser, $wgOut, $wgRequest;
1638 $result = $this->mPage
->doRollback(
1639 $wgRequest->getVal( 'from' ),
1640 $wgRequest->getText( 'summary' ),
1641 $wgRequest->getVal( 'token' ),
1642 $wgRequest->getBool( 'bot' ),
1646 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
1647 $wgOut->rateLimited();
1651 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
1652 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1653 $errArray = $result[0];
1654 $errMsg = array_shift( $errArray );
1655 $wgOut->addWikiMsgArray( $errMsg, $errArray );
1657 if ( isset( $details['current'] ) ) {
1658 $current = $details['current'];
1660 if ( $current->getComment() != '' ) {
1661 $wgOut->addWikiMsgArray( 'editcomment', array(
1662 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
1669 # Display permissions errors before read-only message -- there's no
1670 # point in misleading the user into thinking the inability to rollback
1671 # is only temporary.
1672 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
1673 # array_diff is completely broken for arrays of arrays, sigh.
1674 # Remove any 'readonlytext' error manually.
1676 foreach ( $result as $error ) {
1677 if ( $error != array( 'readonlytext' ) ) {
1681 $wgOut->showPermissionsErrorPage( $out );
1686 if ( $result == array( array( 'readonlytext' ) ) ) {
1687 $wgOut->readOnlyPage();
1692 $current = $details['current'];
1693 $target = $details['target'];
1694 $newId = $details['newid'];
1695 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
1696 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1698 if ( $current->getUserText() === '' ) {
1699 $old = wfMsg( 'rev-deleted-user' );
1701 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
1702 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
1705 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
1706 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
1707 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
1708 $wgOut->returnToMain( false, $this->getTitle() );
1710 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
1711 $de = new DifferenceEngine( $this->getTitle(), $current->getId(), $newId, false, true );
1712 $de->showDiff( '', '' );
1717 * Generate the navigation links when browsing through an article revisions
1718 * It shows the information as:
1719 * Revision as of \<date\>; view current revision
1720 * \<- Previous version | Next Version -\>
1722 * @param $oldid String: revision ID of this article revision
1724 public function setOldSubtitle( $oldid = 0 ) {
1725 global $wgLang, $wgOut, $wgUser, $wgRequest;
1727 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
1731 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1733 # Cascade unhide param in links for easy deletion browsing
1734 $extraParams = array();
1735 if ( $wgRequest->getVal( 'unhide' ) ) {
1736 $extraParams['unhide'] = 1;
1739 $revision = Revision
::newFromId( $oldid );
1740 $timestamp = $revision->getTimestamp();
1742 $current = ( $oldid == $this->mPage
->getLatest() );
1743 $td = $wgLang->timeanddate( $timestamp, true );
1744 $tddate = $wgLang->date( $timestamp, true );
1745 $tdtime = $wgLang->time( $timestamp, true );
1748 ?
wfMsgHtml( 'currentrevisionlink' )
1751 wfMsgHtml( 'currentrevisionlink' ),
1754 array( 'known', 'noclasses' )
1757 ?
wfMsgHtml( 'diff' )
1760 wfMsgHtml( 'diff' ),
1766 array( 'known', 'noclasses' )
1768 $prev = $this->getTitle()->getPreviousRevisionID( $oldid ) ;
1772 wfMsgHtml( 'previousrevision' ),
1775 'direction' => 'prev',
1778 array( 'known', 'noclasses' )
1780 : wfMsgHtml( 'previousrevision' );
1784 wfMsgHtml( 'diff' ),
1790 array( 'known', 'noclasses' )
1792 : wfMsgHtml( 'diff' );
1793 $nextlink = $current
1794 ?
wfMsgHtml( 'nextrevision' )
1797 wfMsgHtml( 'nextrevision' ),
1800 'direction' => 'next',
1803 array( 'known', 'noclasses' )
1805 $nextdiff = $current
1806 ?
wfMsgHtml( 'diff' )
1809 wfMsgHtml( 'diff' ),
1815 array( 'known', 'noclasses' )
1820 // User can delete revisions or view deleted revisions...
1821 $canHide = $wgUser->isAllowed( 'deleterevision' );
1822 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
1823 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
1824 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
1827 'type' => 'revision',
1828 'target' => $this->getTitle()->getPrefixedDbkey(),
1831 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
1836 # Show user links if allowed to see them. If hidden, then show them only if requested...
1837 $userlinks = Linker
::revUserTools( $revision, !$unhide );
1839 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
1840 ?
'revision-info-current'
1843 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
1846 array( 'parseinline', 'replaceafter' ),
1852 $revision->getUser()
1855 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
1856 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
1858 $wgOut->addHTML( $r );
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 boolean true if cached version send, false otherwise
1870 protected function tryFileCache() {
1871 static $called = false;
1874 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1879 if ( $this->isFileCacheable() ) {
1880 $cache = new HTMLFileCache( $this->getTitle() );
1881 if ( $cache->isFileCacheGood( $this->mPage
->getTouched() ) ) {
1882 wfDebug( "Article::tryFileCache(): about to load file\n" );
1883 $cache->loadFromFileCache();
1886 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1887 ob_start( array( &$cache, 'saveToFileCache' ) );
1890 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1897 * Check if the page can be cached
1900 public function isFileCacheable() {
1903 if ( HTMLFileCache
::useFileCache() ) {
1904 $cacheable = $this->mPage
->getID() && !$this->mRedirectedFrom
&& !$this->getTitle()->isRedirect();
1905 // Extension may have reason to disable file caching on some pages.
1907 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
1917 * Add the primary page-view wikitext to the output buffer
1918 * Saves the text into the parser cache if possible.
1919 * Updates templatelinks if it is out of date.
1921 * @param $text String
1922 * @param $cache Boolean
1923 * @param $parserOptions mixed ParserOptions object, or boolean false
1925 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
1928 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
1930 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
1932 $wgOut->addParserOutput( $this->mParserOutput
);
1936 * Lightweight method to get the parser output for a page, checking the parser cache
1937 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1938 * consider, so it's not appropriate to use there.
1940 * @since 1.16 (r52326) for LiquidThreads
1942 * @param $oldid mixed integer Revision ID or null
1943 * @param $user User The relevant user
1944 * @return ParserOutput or false if the given revsion ID is not found
1946 public function getParserOutput( $oldid = null, User
$user = null ) {
1947 global $wgEnableParserCache, $wgUser;
1948 $user = is_null( $user ) ?
$wgUser : $user;
1950 // Should the parser cache be used?
1951 $useParserCache = $wgEnableParserCache &&
1952 $user->getStubThreshold() == 0 &&
1953 $this->mPage
->exists() &&
1956 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1958 if ( $user->getStubThreshold() ) {
1959 wfIncrStats( 'pcache_miss_stub' );
1962 if ( $useParserCache ) {
1963 $parserOutput = ParserCache
::singleton()->get( $this, $this->mPage
->getParserOptions() );
1964 if ( $parserOutput !== false ) {
1965 return $parserOutput;
1969 // Cache miss; parse and output it.
1970 if ( $oldid === null ) {
1971 $text = $this->mPage
->getRawText();
1973 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
1974 if ( $rev === null ) {
1977 $text = $rev->getText();
1980 return $this->getOutputFromWikitext( $text, $useParserCache );
1984 * This does all the heavy lifting for outputWikitext, except it returns the parser
1985 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
1986 * say, embedding thread pages within a discussion system (LiquidThreads)
1988 * @param $text string
1989 * @param $cache boolean
1990 * @param $parserOptions parsing options, defaults to false
1991 * @return string containing parsed output
1993 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
1994 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
1996 if ( !$parserOptions ) {
1997 $parserOptions = $this->mPage
->getParserOptions();
2001 $this->mParserOutput
= $wgParser->parse( $text, $this->getTitle(),
2002 $parserOptions, true, true, $this->getRevIdFetched() );
2007 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2008 $this->getTitle()->getPrefixedDBkey() ) );
2011 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
2012 $parserCache = ParserCache
::singleton();
2013 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
2016 // Make sure file cache is not used on uncacheable content.
2017 // Output that has magic words in it can still use the parser cache
2018 // (if enabled), though it will generally expire sooner.
2019 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
2020 $wgUseFileCache = false;
2023 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
2025 return $this->mParserOutput
;
2029 * Updates cascading protections
2031 * @param $parserOutput ParserOutput object, or boolean false
2033 protected function doCascadeProtectionUpdates( $parserOutput ) {
2034 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->getTitle()->areRestrictionsCascading() ) {
2038 // templatelinks table may have become out of sync,
2039 // especially if using variable-based transclusions.
2040 // For paranoia, check if things have changed and if
2041 // so apply updates to the database. This will ensure
2042 // that cascaded protections apply as soon as the changes
2045 # Get templates from templatelinks
2046 $id = $this->getTitle()->getArticleID();
2048 $tlTemplates = array();
2050 $dbr = wfGetDB( DB_SLAVE
);
2051 $res = $dbr->select( array( 'templatelinks' ),
2052 array( 'tl_namespace', 'tl_title' ),
2053 array( 'tl_from' => $id ),
2057 foreach ( $res as $row ) {
2058 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2061 # Get templates from parser output.
2062 $poTemplates = array();
2063 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2064 foreach ( $templates as $dbk => $id ) {
2065 $poTemplates["$ns:$dbk"] = true;
2070 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2072 if ( count( $templates_diff ) > 0 ) {
2073 # Whee, link updates time.
2074 $u = new LinksUpdate( $this->getTitle(), $parserOutput, false );
2080 * Sets the context this Article is executed in
2082 * @param $context RequestContext
2085 public function setContext( $context ) {
2086 $this->mContext
= $context;
2090 * Gets the context this Article is executed in
2092 * @return RequestContext
2095 public function getContext() {
2096 if ( $this->mContext
instanceof RequestContext
) {
2097 return $this->mContext
;
2099 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
2100 return RequestContext
::getMain();
2105 * Use PHP's magic __get handler to handle accessing of
2106 * raw WikiPage fields for backwards compatibility.
2108 * @param $fname String Field name
2110 public function __get( $fname ) {
2111 if ( property_exists( $this->mPage
, $fname ) ) {
2112 #wfWarn( "Access to raw $fname field " . __CLASS__ );
2113 return $this->mPage
->$fname;
2115 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE
);
2119 * Use PHP's magic __set handler to handle setting of
2120 * raw WikiPage fields for backwards compatibility.
2122 * @param $fname String Field name
2123 * @param $fvalue mixed New value
2124 * @param $args Array Arguments to the method
2126 public function __set( $fname, $fvalue ) {
2127 if ( property_exists( $this->mPage
, $fname ) ) {
2128 #wfWarn( "Access to raw $fname field of " . __CLASS__ );
2129 $this->mPage
->$fname = $fvalue;
2130 // Note: extensions may want to toss on new fields
2131 } elseif ( !in_array( $fname, array( 'mContext', 'mPage' ) ) ) {
2132 $this->mPage
->$fname = $fvalue;
2134 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE
);
2139 * Use PHP's magic __call handler to transform instance calls to
2140 * WikiPage functions for backwards compatibility.
2142 * @param $fname String Name of called method
2143 * @param $args Array Arguments to the method
2145 public function __call( $fname, $args ) {
2146 if ( is_callable( array( $this->mPage
, $fname ) ) ) {
2147 #wfWarn( "Call to " . __CLASS__ . "::$fname; please use WikiPage instead" );
2148 return call_user_func_array( array( $this->mPage
, $fname ), $args );
2150 trigger_error( 'Inaccessible function via __call(): ' . $fname, E_USER_ERROR
);
2153 // ****** B/C functions to work-around PHP silliness with __call and references ****** //
2154 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2155 return $this->mPage
->updateRestrictions( $limit, $reason, $cascade, $expiry );
2158 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
2159 return $this->mPage
->doDeleteArticle( $reason, $suppress, $id, $commit, $error );
2162 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2163 return $this->mPage
->doRollback( $fromP, $summary, $token, $bot, $resultDetails );
2166 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
2167 return $this->mPage
->commitRollback( $fromP, $summary, $bot, $resultDetails );
2170 // ****** B/C functions for static methods ( __callStatic is PHP>=5.3 ) ****** //
2171 public static function selectFields() {
2172 return WikiPage
::selectFields();
2175 public static function onArticleCreate( $title ) {
2176 return WikiPage
::onArticleCreate( $title );
2179 public static function onArticleDelete( $title ) {
2180 return WikiPage
::onArticleDelete( $title );
2183 public static function onArticleEdit( $title ) {
2184 return WikiPage
::onArticleEdit( $title );
2187 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2188 return WikiPage
::getAutosummary( $oldtext, $newtext, $flags );
2193 class PoolWorkArticleView
extends PoolCounterWork
{
2200 function __construct( $article, $key, $useParserCache, $parserOptions ) {
2201 parent
::__construct( 'ArticleView', $key );
2202 $this->mArticle
= $article;
2203 $this->cacheable
= $useParserCache;
2204 $this->parserOptions
= $parserOptions;
2208 return $this->mArticle
->doViewParse();
2211 function getCachedWork() {
2214 $parserCache = ParserCache
::singleton();
2215 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
2217 if ( $this->mArticle
->mParserOutput
!== false ) {
2218 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
2219 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
2220 # Ensure that UI elements requiring revision ID have
2221 # the correct version information.
2222 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
2228 function fallback() {
2229 return $this->mArticle
->tryDirtyCache();
2233 * @param $status Status
2235 function error( $status ) {
2238 $wgOut->clearHTML(); // for release() errors
2239 $wgOut->enableClientCache( false );
2240 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2242 $errortext = $status->getWikiText( false, 'view-pool-error' );
2243 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );