8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
19 var $mComment = ''; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
37 var $mTimestamp = ''; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
46 * Constructor and clear the article
47 * @param $title Reference to a Title object.
48 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 function __construct( Title
$title, $oldId = null ) {
51 $this->mTitle
=& $title;
52 $this->mOldId
= $oldId;
56 * Constructor from an article article
57 * @param $id The article ID to load
59 public static function newFromID( $id ) {
60 $t = Title
::newFromID( $id );
62 return $t == null ?
null : new Article( $t );
66 * Tell the page view functions that this view was redirected
67 * from another page on the wiki.
68 * @param $from Title object.
70 function setRedirectedFrom( $from ) {
71 $this->mRedirectedFrom
= $from;
75 * If this page is a redirect, get its target
77 * The target will be fetched from the redirect table if possible.
78 * If this page doesn't have an entry there, call insertRedirect()
79 * @return mixed Title object, or null if this page is not a redirect
81 public function getRedirectTarget() {
82 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
84 if(!is_null($this->mRedirectTarget
))
85 return $this->mRedirectTarget
;
87 # Query the redirect table
88 $dbr = wfGetDB(DB_SLAVE
);
89 $res = $dbr->select('redirect',
90 array('rd_namespace', 'rd_title'),
91 array('rd_from' => $this->getID()),
94 $row = $dbr->fetchObject($res);
96 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
98 # This page doesn't have an entry in the redirect table
99 return $this->mRedirectTarget
= $this->insertRedirect();
103 * Insert an entry for this page into the redirect table.
105 * Don't call this function directly unless you know what you're doing.
106 * @return Title object
108 public function insertRedirect() {
109 $retval = Title
::newFromRedirect($this->getContent());
112 $dbw = wfGetDB(DB_MASTER
);
113 $dbw->replace('redirect', array('rd_from'), array(
114 'rd_from' => $this->getID(),
115 'rd_namespace' => $retval->getNamespace(),
116 'rd_title' => $retval->getDBKey()
122 * Get the Title object this page redirects to
124 * @return mixed false, Title of in-wiki target, or string with URL
126 public function followRedirect() {
127 $text = $this->getContent();
128 return $this->followRedirectText( $text );
132 * Get the Title object this text redirects to
134 * @return mixed false, Title of in-wiki target, or string with URL
136 public function followRedirectText( $text ) {
137 $rt = Title
::newFromRedirect( $text );
138 # process if title object is valid and not special:userlogout
140 if( $rt->getInterwiki() != '' ) {
141 if( $rt->isLocal() ) {
142 // Offsite wikis need an HTTP redirect.
144 // This can be hard to reverse and may produce loops,
145 // so they may be disabled in the site configuration.
147 $source = $this->mTitle
->getFullURL( 'redirect=no' );
148 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
151 if( $rt->getNamespace() == NS_SPECIAL
) {
152 // Gotta handle redirects to special pages differently:
153 // Fill the HTTP response "Location" header and ignore
154 // the rest of the page we're on.
156 // This can be hard to reverse, so they may be disabled.
158 if( $rt->isSpecial( 'Userlogout' ) ) {
161 return $rt->getFullURL();
167 // No or invalid redirect
172 * get the title object of the article
174 function getTitle() {
175 return $this->mTitle
;
183 $this->mDataLoaded
= false;
184 $this->mContentLoaded
= false;
186 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
187 $this->mRedirectedFrom
= null; # Title object if set
188 $this->mRedirectTarget
= null; # Title object if set
190 $this->mTimestamp
= $this->mComment
= '';
191 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
192 $this->mTouched
= '19700101000000';
193 $this->mForUpdate
= false;
194 $this->mIsRedirect
= false;
195 $this->mRevIdFetched
= 0;
196 $this->mRedirectUrl
= false;
197 $this->mLatest
= false;
198 $this->mPreparedEdit
= false;
202 * Note that getContent/loadContent do not follow redirects anymore.
203 * If you need to fetch redirectable content easily, try
204 * the shortcut in Article::followContent()
206 * @todo There are still side-effects in this!
207 * In general, you should use the Revision class, not Article,
208 * to fetch text for purposes other than page views.
210 * @return Return the text of this revision
212 function getContent() {
213 global $wgUser, $wgOut, $wgMessageCache;
215 wfProfileIn( __METHOD__
);
217 if ( 0 == $this->getID() ) {
218 wfProfileOut( __METHOD__
);
219 $wgOut->setRobotPolicy( 'noindex,nofollow' );
221 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
222 $wgMessageCache->loadAllMessages();
223 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
225 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
228 return "<div class='noarticletext'>\n$ret\n</div>";
230 $this->loadContent();
231 wfProfileOut( __METHOD__
);
232 return $this->mContent
;
237 * This function returns the text of a section, specified by a number ($section).
238 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
239 * the first section before any such heading (section 0).
241 * If a section contains subsections, these are also returned.
243 * @param $text String: text to look in
244 * @param $section Integer: section number
245 * @return string text of the requested section
248 function getSection($text,$section) {
250 return $wgParser->getSection( $text, $section );
254 * @return int The oldid of the article that is to be shown, 0 for the
257 function getOldID() {
258 if ( is_null( $this->mOldId
) ) {
259 $this->mOldId
= $this->getOldIDFromRequest();
261 return $this->mOldId
;
265 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
267 * @return int The old id for the request
269 public function getOldIDFromRequest() {
271 $this->mRedirectUrl
= false;
272 $oldid = $wgRequest->getVal( 'oldid' );
273 if ( isset( $oldid ) ) {
274 $oldid = intval( $oldid );
275 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
276 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
280 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
282 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
283 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
301 * Load the revision (including text) into this object
303 function loadContent() {
304 if ( $this->mContentLoaded
) return;
307 $oldid = $this->getOldID();
309 # Pre-fill content with error message so that if something
310 # fails we'll have something telling us what we intended.
311 $this->mOldId
= $oldid;
312 $this->fetchContent( $oldid );
317 * Fetch a page record with the given conditions
318 * @param Database $dbr
319 * @param array $conditions
322 function pageData( $dbr, $conditions ) {
336 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
337 $row = $dbr->selectRow(
343 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
348 * @param Database $dbr
349 * @param Title $title
351 function pageDataFromTitle( $dbr, $title ) {
352 return $this->pageData( $dbr, array(
353 'page_namespace' => $title->getNamespace(),
354 'page_title' => $title->getDBkey() ) );
358 * @param Database $dbr
361 function pageDataFromId( $dbr, $id ) {
362 return $this->pageData( $dbr, array( 'page_id' => $id ) );
366 * Set the general counter, title etc data loaded from
369 * @param object $data
372 function loadPageData( $data = 'fromdb' ) {
373 if ( $data === 'fromdb' ) {
374 $dbr = wfGetDB( DB_MASTER
);
375 $data = $this->pageDataFromId( $dbr, $this->getId() );
378 $lc = LinkCache
::singleton();
380 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
382 $this->mTitle
->mArticleID
= $data->page_id
;
384 # Old-fashioned restrictions.
385 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
387 $this->mCounter
= $data->page_counter
;
388 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
389 $this->mIsRedirect
= $data->page_is_redirect
;
390 $this->mLatest
= $data->page_latest
;
392 if ( is_object( $this->mTitle
) ) {
393 $lc->addBadLinkObj( $this->mTitle
);
395 $this->mTitle
->mArticleID
= 0;
398 $this->mDataLoaded
= true;
402 * Get text of an article from database
403 * Does *NOT* follow redirects.
404 * @param int $oldid 0 for whatever the latest revision is
407 function fetchContent( $oldid = 0 ) {
408 if ( $this->mContentLoaded
) {
409 return $this->mContent
;
412 $dbr = wfGetDB( DB_MASTER
);
414 # Pre-fill content with error message so that if something
415 # fails we'll have something telling us what we intended.
416 $t = $this->mTitle
->getPrefixedText();
417 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
418 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
421 $revision = Revision
::newFromId( $oldid );
422 if( is_null( $revision ) ) {
423 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
426 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
428 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
431 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
432 $this->loadPageData( $data );
434 if( !$this->mDataLoaded
) {
435 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
437 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
440 $this->loadPageData( $data );
442 $revision = Revision
::newFromId( $this->mLatest
);
443 if( is_null( $revision ) ) {
444 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
449 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
450 // We should instead work with the Revision object when we need it...
451 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
453 $this->mUser
= $revision->getUser();
454 $this->mUserText
= $revision->getUserText();
455 $this->mComment
= $revision->getComment();
456 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
458 $this->mRevIdFetched
= $revision->getId();
459 $this->mContentLoaded
= true;
460 $this->mRevision
=& $revision;
462 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
464 return $this->mContent
;
468 * Read/write accessor to select FOR UPDATE
470 * @param $x Mixed: FIXME
472 function forUpdate( $x = NULL ) {
473 return wfSetVar( $this->mForUpdate
, $x );
477 * Get the database which should be used for reads
480 * @deprecated - just call wfGetDB( DB_MASTER ) instead
483 wfDeprecated( __METHOD__
);
484 return wfGetDB( DB_MASTER
);
488 * Get options for all SELECT statements
490 * @param $options Array: an optional options array which'll be appended to
492 * @return Array: options
494 function getSelectOptions( $options = '' ) {
495 if ( $this->mForUpdate
) {
496 if ( is_array( $options ) ) {
497 $options[] = 'FOR UPDATE';
499 $options = 'FOR UPDATE';
506 * @return int Page ID
509 if( $this->mTitle
) {
510 return $this->mTitle
->getArticleID();
517 * @return bool Whether or not the page exists in the database
520 return $this->getId() != 0;
524 * @return int The view count for the page
526 function getCount() {
527 if ( -1 == $this->mCounter
) {
528 $id = $this->getID();
532 $dbr = wfGetDB( DB_SLAVE
);
533 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
534 'Article::getCount', $this->getSelectOptions() );
537 return $this->mCounter
;
541 * Determine whether a page would be suitable for being counted as an
542 * article in the site_stats table based on the title & its content
544 * @param $text String: text to analyze
547 function isCountable( $text ) {
548 global $wgUseCommaCount;
550 $token = $wgUseCommaCount ?
',' : '[[';
552 $this->mTitle
->isContentPage()
553 && !$this->isRedirect( $text )
554 && in_string( $token, $text );
558 * Tests if the article text represents a redirect
560 * @param $text String: FIXME
563 function isRedirect( $text = false ) {
564 if ( $text === false ) {
565 if ( $this->mDataLoaded
)
566 return $this->mIsRedirect
;
568 // Apparently loadPageData was never called
569 $this->loadContent();
570 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
572 $titleObj = Title
::newFromRedirect( $text );
574 return $titleObj !== NULL;
578 * Returns true if the currently-referenced revision is the current edit
579 * to this page (and it exists).
582 function isCurrent() {
583 # If no oldid, this is the current version.
584 if ($this->getOldID() == 0)
587 return $this->exists() &&
588 isset( $this->mRevision
) &&
589 $this->mRevision
->isCurrent();
593 * Loads everything except the text
594 * This isn't necessary for all uses, so it's only done if needed.
597 function loadLastEdit() {
598 if ( -1 != $this->mUser
)
601 # New or non-existent articles have no user information
602 $id = $this->getID();
603 if ( 0 == $id ) return;
605 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
606 if( !is_null( $this->mLastRevision
) ) {
607 $this->mUser
= $this->mLastRevision
->getUser();
608 $this->mUserText
= $this->mLastRevision
->getUserText();
609 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
610 $this->mComment
= $this->mLastRevision
->getComment();
611 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
612 $this->mRevIdFetched
= $this->mLastRevision
->getId();
616 function getTimestamp() {
617 // Check if the field has been filled by ParserCache::get()
618 if ( !$this->mTimestamp
) {
619 $this->loadLastEdit();
621 return wfTimestamp(TS_MW
, $this->mTimestamp
);
625 $this->loadLastEdit();
629 function getUserText() {
630 $this->loadLastEdit();
631 return $this->mUserText
;
634 function getComment() {
635 $this->loadLastEdit();
636 return $this->mComment
;
639 function getMinorEdit() {
640 $this->loadLastEdit();
641 return $this->mMinorEdit
;
644 function getRevIdFetched() {
645 $this->loadLastEdit();
646 return $this->mRevIdFetched
;
650 * @param $limit Integer: default 0.
651 * @param $offset Integer: default 0.
653 function getContributors($limit = 0, $offset = 0) {
654 # XXX: this is expensive; cache this info somewhere.
657 $dbr = wfGetDB( DB_SLAVE
);
658 $revTable = $dbr->tableName( 'revision' );
659 $userTable = $dbr->tableName( 'user' );
660 $user = $this->getUser();
661 $pageId = $this->getId();
663 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
664 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
665 WHERE rev_page = $pageId
666 AND rev_user != $user
667 GROUP BY rev_user, rev_user_text, user_real_name
668 ORDER BY timestamp DESC";
670 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
671 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
673 $sql .= ' '. $this->getSelectOptions();
675 $res = $dbr->query($sql, __METHOD__
);
677 return new UserArrayFromResult( $res );
681 * This is the default action of the script: just view the page of
685 global $wgUser, $wgOut, $wgRequest, $wgContLang;
686 global $wgEnableParserCache, $wgStylePath, $wgParser;
687 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
688 global $wgDefaultRobotPolicy;
689 $sk = $wgUser->getSkin();
691 wfProfileIn( __METHOD__
);
693 $parserCache = ParserCache
::singleton();
694 $ns = $this->mTitle
->getNamespace(); # shortcut
696 # Get variables from query string
697 $oldid = $this->getOldID();
699 # getOldID may want us to redirect somewhere else
700 if ( $this->mRedirectUrl
) {
701 $wgOut->redirect( $this->mRedirectUrl
);
702 wfProfileOut( __METHOD__
);
706 $diff = $wgRequest->getVal( 'diff' );
707 $rcid = $wgRequest->getVal( 'rcid' );
708 $rdfrom = $wgRequest->getVal( 'rdfrom' );
709 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
710 $purge = $wgRequest->getVal( 'action' ) == 'purge';
712 $wgOut->setArticleFlag( true );
714 # Discourage indexing of printable versions, but encourage following
715 if( $wgOut->isPrintable() ) {
716 $policy = 'noindex,follow';
717 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
718 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
719 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
720 # Honour customised robot policies for this namespace
721 $policy = $wgNamespaceRobotPolicies[$ns];
723 $policy = $wgDefaultRobotPolicy;
725 $wgOut->setRobotPolicy( $policy );
727 # If we got diff and oldid in the query, we want to see a
728 # diff page instead of the article.
730 if ( !is_null( $diff ) ) {
731 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
733 $diff = $wgRequest->getVal( 'diff' );
734 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
735 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
736 // DifferenceEngine directly fetched the revision:
737 $this->mRevIdFetched
= $de->mNewid
;
738 $de->showDiffPage( $diffOnly );
740 // Needed to get the page's current revision
741 $this->loadPageData();
742 if( $diff == 0 ||
$diff == $this->mLatest
) {
743 # Run view updates for current revision only
744 $this->viewUpdates();
746 wfProfileOut( __METHOD__
);
750 if ( empty( $oldid ) && $this->checkTouched() ) {
751 $wgOut->setETag($parserCache->getETag($this, $wgUser));
753 if( $wgOut->checkLastModified( $this->mTouched
) ){
754 wfProfileOut( __METHOD__
);
756 } else if ( $this->tryFileCache() ) {
757 # tell wgOut that output is taken care of
759 $this->viewUpdates();
760 wfProfileOut( __METHOD__
);
765 # Should the parser cache be used?
766 $pcache = $this->useParserCache( $oldid );
767 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
768 if ( $wgUser->getOption( 'stubthreshold' ) ) {
769 wfIncrStats( 'pcache_miss_stub' );
772 $wasRedirected = false;
773 if ( isset( $this->mRedirectedFrom
) ) {
774 // This is an internally redirected page view.
775 // We'll need a backlink to the source page for navigation.
776 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
777 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
778 $s = wfMsg( 'redirectedfrom', $redir );
779 $wgOut->setSubtitle( $s );
781 // Set the fragment if one was specified in the redirect
782 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
783 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
784 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
786 $wasRedirected = true;
788 } elseif ( !empty( $rdfrom ) ) {
789 // This is an externally redirected view, from some other wiki.
790 // If it was reported from a trusted site, supply a backlink.
791 global $wgRedirectSources;
792 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
793 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
794 $s = wfMsg( 'redirectedfrom', $redir );
795 $wgOut->setSubtitle( $s );
796 $wasRedirected = true;
801 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
803 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
804 // Ensure that UI elements requiring revision ID have
805 // the correct version information.
806 $wgOut->setRevisionId( $this->mLatest
);
810 # Fetch content and check for errors
811 if ( !$outputDone ) {
812 # If the article does not exist and was deleted, show the log
813 if ($this->getID() == 0) {
814 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
815 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
816 $count = $pager->getNumRows();
819 $wgOut->addHtml( '<div class="mw-warning-with-logexcerpt">' );
820 $wgOut->addWikiMsg( 'deleted-notice' );
822 $loglist->beginLogEventsList() .
824 $loglist->endLogEventsList()
827 $wgOut->addHtml( $wgUser->getSkin()->link(
828 SpecialPage
::getTitleFor( 'Log' ),
829 wfMsgHtml( 'deletelog-fulllog' ),
833 'page' => $this->mTitle
->getPrefixedText() ) ) );
835 $wgOut->addHtml( '</div>' );
838 $text = $this->getContent();
839 if ( $text === false ) {
840 # Failed to load, replace text with error message
841 $t = $this->mTitle
->getPrefixedText();
843 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
844 $text = wfMsg( 'missing-article', $t, $d );
846 $text = wfMsg( 'noarticletext' );
850 # Another whitelist check in case oldid is altering the title
851 if ( !$this->mTitle
->userCanRead() ) {
852 $wgOut->loginToUse();
854 wfProfileOut( __METHOD__
);
858 # We're looking at an old revision
859 if ( !empty( $oldid ) ) {
860 $wgOut->setRobotPolicy( 'noindex,nofollow' );
861 if( is_null( $this->mRevision
) ) {
862 // FIXME: This would be a nice place to load the 'no such page' text.
864 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
865 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
866 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
867 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
868 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
869 wfProfileOut( __METHOD__
);
872 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
873 // and we are allowed to see...
879 $wgOut->setRevisionId( $this->getRevIdFetched() );
881 // Pages containing custom CSS or JavaScript get special treatment
882 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
883 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
884 // Give hooks a chance to customise the output
885 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
886 // Wrap the whole lot in a <pre> and don't parse
888 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
889 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
890 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
891 $wgOut->addHtml( "\n</pre>\n" );
893 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
894 # Don't append the subtitle if this was an old revision
895 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
896 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
897 $wgOut->addParserOutputNoText( $parseout );
898 } else if ( $pcache ) {
899 # Display content and save to parser cache
900 $this->outputWikiText( $text );
902 # Display content, don't attempt to save to parser cache
903 # Don't show section-edit links on old revisions... this way lies madness.
904 if( !$this->isCurrent() ) {
905 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
907 # Display content and don't save to parser cache
908 # With timing hack -- TS 2006-07-26
910 $this->outputWikiText( $text, false );
915 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
916 $this->mTitle
->getPrefixedDBkey()));
919 if( !$this->isCurrent() ) {
920 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
924 /* title may have been set from the cache */
925 $t = $wgOut->getPageTitle();
927 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
929 # For the main page, overwrite the <title> element with the con-
930 # tents of 'pagetitle-view-mainpage' instead of the default (if
932 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
933 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
934 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
938 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
939 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
940 $wgOut->addWikiMsg('anontalkpagetext');
943 # If we have been passed an &rcid= parameter, we want to give the user a
944 # chance to mark this new article as patrolled.
945 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
947 "<div class='patrollink'>" .
948 wfMsgHtml( 'markaspatrolledlink',
949 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
950 "action=markpatrolled&rcid=$rcid" )
957 if ($wgUseTrackbacks)
958 $this->addTrackbacks();
960 $this->viewUpdates();
961 wfProfileOut( __METHOD__
);
965 * Should the parser cache be used?
967 protected function useParserCache( $oldid ) {
968 global $wgUser, $wgEnableParserCache;
970 return $wgEnableParserCache
971 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
974 && !$this->mTitle
->isCssOrJsPage()
975 && !$this->mTitle
->isCssJsSubpage();
980 * @param Title $target Title of destination to redirect
981 * @param Bool $appendSubtitle Object[optional]
982 * @param Bool $forceKnown Should the image be shown as a bluelink regardless of existence?
984 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
985 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
988 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
989 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
991 if( $appendSubtitle ) {
992 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
994 $sk = $wgUser->getSkin();
996 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
998 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1000 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1001 '<span class="redirectText">'.$link.'</span>';
1005 function addTrackbacks() {
1006 global $wgOut, $wgUser;
1008 $dbr = wfGetDB(DB_SLAVE
);
1009 $tbs = $dbr->select(
1010 /* FROM */ 'trackbacks',
1011 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1012 /* WHERE */ array('tb_page' => $this->getID())
1015 if (!$dbr->numrows($tbs))
1019 while ($o = $dbr->fetchObject($tbs)) {
1021 if ($wgUser->isAllowed( 'trackback' )) {
1022 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
1023 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1024 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1027 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1034 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1037 function deletetrackback() {
1038 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1040 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
1041 $wgOut->addWikiMsg( 'sessionfailure' );
1045 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1047 if (count($permission_errors)>0)
1049 $wgOut->showPermissionsErrorPage( $permission_errors );
1053 $db = wfGetDB(DB_MASTER
);
1054 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1055 $wgTitle->invalidateCache();
1056 $wgOut->addWikiMsg('trackbackdeleteok');
1062 $wgOut->setArticleBodyOnly(true);
1067 * Handle action=purge
1070 global $wgUser, $wgRequest, $wgOut;
1072 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1073 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1078 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1079 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1080 $form = "<form method=\"post\" action=\"$action\">\n" .
1081 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1083 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1084 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1085 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1086 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1087 $wgOut->addHTML( $top . $form . $bottom );
1092 * Perform the actions of a page purging
1094 function doPurge() {
1096 // Invalidate the cache
1097 $this->mTitle
->invalidateCache();
1099 if ( $wgUseSquid ) {
1100 // Commit the transaction before the purge is sent
1101 $dbw = wfGetDB( DB_MASTER
);
1102 $dbw->immediateCommit();
1105 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1106 $update->doUpdate();
1108 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1109 global $wgMessageCache;
1110 if ( $this->getID() == 0 ) {
1113 $text = $this->getContent();
1115 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1120 * Insert a new empty page record for this article.
1121 * This *must* be followed up by creating a revision
1122 * and running $this->updateToLatest( $rev_id );
1123 * or else the record will be left in a funky state.
1124 * Best if all done inside a transaction.
1126 * @param Database $dbw
1127 * @return int The newly created page_id key, or false if the title already existed
1130 function insertOn( $dbw ) {
1131 wfProfileIn( __METHOD__
);
1133 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1134 $dbw->insert( 'page', array(
1135 'page_id' => $page_id,
1136 'page_namespace' => $this->mTitle
->getNamespace(),
1137 'page_title' => $this->mTitle
->getDBkey(),
1138 'page_counter' => 0,
1139 'page_restrictions' => '',
1140 'page_is_redirect' => 0, # Will set this shortly...
1142 'page_random' => wfRandom(),
1143 'page_touched' => $dbw->timestamp(),
1144 'page_latest' => 0, # Fill this in shortly...
1145 'page_len' => 0, # Fill this in shortly...
1146 ), __METHOD__
, 'IGNORE' );
1148 $affected = $dbw->affectedRows();
1150 $newid = $dbw->insertId();
1151 $this->mTitle
->resetArticleId( $newid );
1153 wfProfileOut( __METHOD__
);
1154 return $affected ?
$newid : false;
1158 * Update the page record to point to a newly saved revision.
1160 * @param Database $dbw
1161 * @param Revision $revision For ID number, and text used to set
1162 length and redirect status fields
1163 * @param int $lastRevision If given, will not overwrite the page field
1164 * when different from the currently set value.
1165 * Giving 0 indicates the new page flag should
1167 * @param bool $lastRevIsRedirect If given, will optimize adding and
1168 * removing rows in redirect table.
1169 * @return bool true on success, false on failure
1172 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1173 wfProfileIn( __METHOD__
);
1175 $text = $revision->getText();
1176 $rt = Title
::newFromRedirect( $text );
1178 $conditions = array( 'page_id' => $this->getId() );
1179 if( !is_null( $lastRevision ) ) {
1180 # An extra check against threads stepping on each other
1181 $conditions['page_latest'] = $lastRevision;
1184 $dbw->update( 'page',
1186 'page_latest' => $revision->getId(),
1187 'page_touched' => $dbw->timestamp(),
1188 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1189 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1190 'page_len' => strlen( $text ),
1195 $result = $dbw->affectedRows() != 0;
1198 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1201 wfProfileOut( __METHOD__
);
1206 * Add row to the redirect table if this is a redirect, remove otherwise.
1208 * @param Database $dbw
1209 * @param $redirectTitle a title object pointing to the redirect target,
1210 * or NULL if this is not a redirect
1211 * @param bool $lastRevIsRedirect If given, will optimize adding and
1212 * removing rows in redirect table.
1213 * @return bool true on success, false on failure
1216 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1218 // Always update redirects (target link might have changed)
1219 // Update/Insert if we don't know if the last revision was a redirect or not
1220 // Delete if changing from redirect to non-redirect
1221 $isRedirect = !is_null($redirectTitle);
1222 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1224 wfProfileIn( __METHOD__
);
1228 // This title is a redirect, Add/Update row in the redirect table
1229 $set = array( /* SET */
1230 'rd_namespace' => $redirectTitle->getNamespace(),
1231 'rd_title' => $redirectTitle->getDBkey(),
1232 'rd_from' => $this->getId(),
1235 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1237 // This is not a redirect, remove row from redirect table
1238 $where = array( 'rd_from' => $this->getId() );
1239 $dbw->delete( 'redirect', $where, __METHOD__
);
1242 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1243 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1244 wfProfileOut( __METHOD__
);
1245 return ( $dbw->affectedRows() != 0 );
1252 * If the given revision is newer than the currently set page_latest,
1253 * update the page record. Otherwise, do nothing.
1255 * @param Database $dbw
1256 * @param Revision $revision
1258 function updateIfNewerOn( &$dbw, $revision ) {
1259 wfProfileIn( __METHOD__
);
1261 $row = $dbw->selectRow(
1262 array( 'revision', 'page' ),
1263 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1265 'page_id' => $this->getId(),
1266 'page_latest=rev_id' ),
1269 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1270 wfProfileOut( __METHOD__
);
1273 $prev = $row->rev_id
;
1274 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1276 # No or missing previous revision; mark the page as new
1278 $lastRevIsRedirect = null;
1281 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1282 wfProfileOut( __METHOD__
);
1287 * @return string Complete article text, or null if error
1289 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1290 wfProfileIn( __METHOD__
);
1292 if( $section == '' ) {
1293 // Whole-page edit; let the text through unmolested.
1295 if( is_null( $edittime ) ) {
1296 $rev = Revision
::newFromTitle( $this->mTitle
);
1298 $dbw = wfGetDB( DB_MASTER
);
1299 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1301 if( is_null( $rev ) ) {
1302 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1303 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1306 $oldtext = $rev->getText();
1308 if( $section == 'new' ) {
1309 # Inserting a new section
1310 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1311 $text = strlen( trim( $oldtext ) ) > 0
1312 ?
"{$oldtext}\n\n{$subject}{$text}"
1313 : "{$subject}{$text}";
1315 # Replacing an existing section; roll out the big guns
1317 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1322 wfProfileOut( __METHOD__
);
1327 * @deprecated use Article::doEdit()
1329 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1330 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1331 ( $isminor ? EDIT_MINOR
: 0 ) |
1332 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1333 ( $bot ? EDIT_FORCE_BOT
: 0 );
1335 # If this is a comment, add the summary as headline
1336 if ( $comment && $summary != "" ) {
1337 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1340 $this->doEdit( $text, $summary, $flags );
1342 $dbw = wfGetDB( DB_MASTER
);
1344 if (!$this->mTitle
->userIsWatching()) {
1350 if ( $this->mTitle
->userIsWatching() ) {
1356 $this->doRedirect( $this->isRedirect( $text ) );
1360 * @deprecated use Article::doEdit()
1362 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1363 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1364 ( $minor ? EDIT_MINOR
: 0 ) |
1365 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1367 $status = $this->doEdit( $text, $summary, $flags );
1368 if ( !$status->isOK() ) {
1372 $dbw = wfGetDB( DB_MASTER
);
1374 if (!$this->mTitle
->userIsWatching()) {
1380 if ( $this->mTitle
->userIsWatching() ) {
1387 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1388 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1390 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1397 * Change an existing article or create a new article. Updates RC and all necessary caches,
1398 * optionally via the deferred update array.
1400 * $wgUser must be set before calling this function.
1402 * @param string $text New text
1403 * @param string $summary Edit summary
1404 * @param integer $flags bitfield:
1406 * Article is known or assumed to be non-existent, create a new one
1408 * Article is known or assumed to be pre-existing, update it
1410 * Mark this edit minor, if the user is allowed to do so
1412 * Do not log the change in recentchanges
1414 * Mark the edit a "bot" edit regardless of user rights
1415 * EDIT_DEFER_UPDATES
1416 * Defer some of the updates until the end of index.php
1418 * Fill in blank summaries with generated text where possible
1420 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1421 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1422 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1423 * edit-already-exists error will be returned. These two conditions are also possible with
1424 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1426 * @param $baseRevId, the revision ID this edit was based off, if any
1428 * @return Status object. Possible errors:
1429 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1430 * edit-gone-missing: In update mode, but the article didn't exist
1431 * edit-conflict: In update mode, the article changed unexpectedly
1432 * edit-no-change: Warning that the text was the same as before
1433 * edit-already-exists: In creation mode, but the article already exists
1435 * Extensions may define additional errors.
1437 * $return->value will contain an associative array with members as follows:
1438 * new: Boolean indicating if the function attempted to create a new article
1439 * revision: The revision object for the inserted revision, or null
1441 * Compatibility note: this function previously returned a boolean value indicating success/failure
1443 function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1444 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1446 # Low-level sanity check
1447 if( $this->mTitle
->getText() == '' ) {
1448 throw new MWException( 'Something is trying to edit an article with an empty title' );
1451 wfProfileIn( __METHOD__
);
1453 if ($user == null) {
1456 $status = Status
::newGood( array() );
1458 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1459 $this->loadPageData();
1461 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1462 $aid = $this->mTitle
->getArticleID();
1464 $flags |
= EDIT_UPDATE
;
1470 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text,
1471 &$summary, $flags & EDIT_MINOR
,
1472 null, null, &$flags, &$status ) ) )
1474 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1475 wfProfileOut( __METHOD__
);
1476 if ( $status->isOK() ) {
1477 $status->fatal( 'edit-hook-aborted');
1482 # Silently ignore EDIT_MINOR if not allowed
1483 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1484 $bot = $flags & EDIT_FORCE_BOT
;
1486 $oldtext = $this->getContent();
1487 $oldsize = strlen( $oldtext );
1489 # Provide autosummaries if one is not provided and autosummaries are enabled.
1490 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1491 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1494 $editInfo = $this->prepareTextForEdit( $text );
1495 $text = $editInfo->pst
;
1496 $newsize = strlen( $text );
1498 $dbw = wfGetDB( DB_MASTER
);
1499 $now = wfTimestampNow();
1501 if ( $flags & EDIT_UPDATE
) {
1502 # Update article, but only if changed.
1503 $status->value
['new'] = false;
1505 # Make sure the revision is either completely inserted or not inserted at all
1506 if( !$wgDBtransactions ) {
1507 $userAbort = ignore_user_abort( true );
1512 $changed = ( strcmp( $text, $oldtext ) != 0 );
1515 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1516 - (int)$this->isCountable( $oldtext );
1517 $this->mTotalAdjustment
= 0;
1519 if ( !$this->mLatest
) {
1520 # Article gone missing
1521 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1522 $status->fatal( 'edit-gone-missing' );
1523 wfProfileOut( __METHOD__
);
1527 $revision = new Revision( array(
1528 'page' => $this->getId(),
1529 'comment' => $summary,
1530 'minor_edit' => $isminor,
1532 'parent_id' => $this->mLatest
,
1533 'user' => $user->getId(),
1534 'user_text' => $user->getName(),
1538 $revisionId = $revision->insertOn( $dbw );
1542 # Note that we use $this->mLatest instead of fetching a value from the master DB
1543 # during the course of this function. This makes sure that EditPage can detect
1544 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1545 # before this function is called. A previous function used a separate query, this
1546 # creates a window where concurrent edits can cause an ignored edit conflict.
1547 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1550 /* Belated edit conflict! Run away!! */
1551 $status->fatal( 'edit-conflict' );
1552 # Delete the invalid revision if the DB is not transactional
1553 if ( !$wgDBtransactions ) {
1554 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1559 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1561 # Update recentchanges
1562 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1563 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1564 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1567 # Mark as patrolled if the user can do so
1568 if( $GLOBALS['wgUseRCPatrol'] && $user->isAllowed( 'autopatrol' ) ) {
1569 RecentChange
::markPatrolled( $rc, true );
1572 $user->incEditCount();
1576 $status->warning( 'edit-no-change' );
1578 // Keep the same revision ID, but do some updates on it
1579 $revisionId = $this->getRevIdFetched();
1580 // Update page_touched, this is usually implicit in the page update
1581 // Other cache updates are done in onArticleEdit()
1582 $this->mTitle
->invalidateCache();
1585 if( !$wgDBtransactions ) {
1586 ignore_user_abort( $userAbort );
1588 // Now that ignore_user_abort is restored, we can respond to fatal errors
1589 if ( !$status->isOK() ) {
1590 wfProfileOut( __METHOD__
);
1594 # Invalidate cache of this article and all pages using this article
1595 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1596 Article
::onArticleEdit( $this->mTitle
, 'skiptransclusions' );
1597 # Update links tables, site stats, etc.
1598 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1600 # Create new article
1601 $status->value
['new'] = true;
1603 # Set statistics members
1604 # We work out if it's countable after PST to avoid counter drift
1605 # when articles are created with {{subst:}}
1606 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1607 $this->mTotalAdjustment
= 1;
1611 # Add the page record; stake our claim on this title!
1612 # This will return false if the article already exists
1613 $newid = $this->insertOn( $dbw );
1615 if ( $newid === false ) {
1617 $status->fatal( 'edit-already-exists' );
1618 wfProfileOut( __METHOD__
);
1622 # Save the revision text...
1623 $revision = new Revision( array(
1625 'comment' => $summary,
1626 'minor_edit' => $isminor,
1628 'user' => $user->getId(),
1629 'user_text' => $user->getName(),
1631 $revisionId = $revision->insertOn( $dbw );
1633 $this->mTitle
->resetArticleID( $newid );
1635 # Update the page record with revision data
1636 $this->updateRevisionOn( $dbw, $revision, 0 );
1638 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1640 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1641 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1642 '', strlen( $text ), $revisionId );
1643 # Mark as patrolled if the user can
1644 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $user->isAllowed( 'autopatrol' ) ) {
1645 RecentChange
::markPatrolled( $rc, true );
1648 $user->incEditCount();
1651 # Update links, etc.
1652 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1655 Article
::onArticleCreate( $this->mTitle
);
1657 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1658 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1661 # Do updates right now unless deferral was requested
1662 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1666 // Return the new revision (or null) to the caller
1667 $status->value
['revision'] = $revision;
1669 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1670 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status ) );
1672 wfProfileOut( __METHOD__
);
1677 * @deprecated wrapper for doRedirect
1679 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1680 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1684 * Output a redirect back to the article.
1685 * This is typically used after an edit.
1687 * @param boolean $noRedir Add redirect=no
1688 * @param string $sectionAnchor section to redirect to, including "#"
1689 * @param string $extraQuery, extra query params
1691 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1694 $query = 'redirect=no';
1696 $query .= "&$query";
1698 $query = $extraQuery;
1700 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1704 * Mark this particular edit/page as patrolled
1706 function markpatrolled() {
1707 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1708 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1710 # If we haven't been given an rc_id value, we can't do anything
1711 $rcid = (int) $wgRequest->getVal('rcid');
1712 $rc = RecentChange
::newFromId($rcid);
1713 if ( is_null($rc) ) {
1714 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1718 #It would be nice to see where the user had actually come from, but for now just guess
1719 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1720 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1722 $dbw = wfGetDB( DB_MASTER
);
1723 $errors = $rc->doMarkPatrolled();
1725 if ( in_array(array('rcpatroldisabled'), $errors) ) {
1726 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1730 if ( in_array(array('hookaborted'), $errors) ) {
1731 // The hook itself has handled any output
1735 if ( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1736 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1737 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1738 $wgOut->returnToMain( false, $return );
1742 if ( !empty($errors) ) {
1743 $wgOut->showPermissionsErrorPage( $errors );
1748 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1749 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1750 $wgOut->returnToMain( false, $return );
1754 * User-interface handler for the "watch" action
1759 global $wgUser, $wgOut;
1761 if ( $wgUser->isAnon() ) {
1762 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1765 if ( wfReadOnly() ) {
1766 $wgOut->readOnlyPage();
1770 if( $this->doWatch() ) {
1771 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1772 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1774 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1777 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1781 * Add this page to $wgUser's watchlist
1782 * @return bool true on successful watch operation
1784 function doWatch() {
1786 if( $wgUser->isAnon() ) {
1790 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1791 $wgUser->addWatch( $this->mTitle
);
1793 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1800 * User interface handler for the "unwatch" action.
1802 function unwatch() {
1804 global $wgUser, $wgOut;
1806 if ( $wgUser->isAnon() ) {
1807 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1810 if ( wfReadOnly() ) {
1811 $wgOut->readOnlyPage();
1815 if( $this->doUnwatch() ) {
1816 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1817 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1819 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1822 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1826 * Stop watching a page
1827 * @return bool true on successful unwatch
1829 function doUnwatch() {
1831 if( $wgUser->isAnon() ) {
1835 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1836 $wgUser->removeWatch( $this->mTitle
);
1838 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1845 * action=protect handler
1847 function protect() {
1848 $form = new ProtectionForm( $this );
1853 * action=unprotect handler (alias)
1855 function unprotect() {
1860 * Update the article's restriction field, and leave a log entry.
1862 * @param array $limit set of restriction keys
1863 * @param string $reason
1864 * @return bool true on success
1866 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = array() ) {
1867 global $wgUser, $wgRestrictionTypes, $wgContLang;
1869 $id = $this->mTitle
->getArticleID();
1870 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1878 // Take this opportunity to purge out expired restrictions
1879 Title
::purgeExpiredRestrictions();
1881 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1882 # we expect a single selection, but the schema allows otherwise.
1884 $updated = Article
::flattenRestrictions( $limit );
1886 foreach( $wgRestrictionTypes as $action ) {
1887 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1888 $changed = ($changed ||
($this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action]) );
1891 $current = Article
::flattenRestrictions( $current );
1893 $changed = ($changed ||
( $current != $updated ) );
1894 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1895 $protect = ( $updated != '' );
1897 # If nothing's changed, do nothing
1899 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1901 $dbw = wfGetDB( DB_MASTER
);
1903 # Prepare a null revision to be added to the history
1904 $modified = $current != '' && $protect;
1906 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1908 $comment_type = 'unprotectedarticle';
1910 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1912 # Only restrictions with the 'protect' right can cascade...
1913 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1914 foreach( $limit as $action => $restriction ) {
1915 # FIXME: can $restriction be an array or what? (same as fixme above)
1916 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1921 $cascade_description = '';
1923 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1927 $comment .= ": $reason";
1929 $editComment = $comment;
1930 $encodedExpiry = array();
1931 $protect_description = '';
1932 foreach( $limit as $action => $restrictions ) {
1933 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
1934 if( $restrictions != '' ) {
1935 $protect_description .= "[$action=$restrictions] (";
1936 if( $encodedExpiry[$action] != 'infinity' ) {
1937 $protect_description .= wfMsgForContent( 'protect-expiring',
1938 $wgContLang->timeanddate( $expiry[$action], false, false ) );
1940 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1942 $protect_description .= ') ';
1945 $protect_description = trim($protect_description);
1947 if( $protect_description && $protect )
1948 $editComment .= " ($protect_description)";
1950 $editComment .= "$cascade_description";
1951 # Update restrictions table
1952 foreach( $limit as $action => $restrictions ) {
1953 if ($restrictions != '' ) {
1954 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1955 array( 'pr_page' => $id,
1956 'pr_type' => $action,
1957 'pr_level' => $restrictions,
1958 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
1959 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
1961 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1962 'pr_type' => $action ), __METHOD__
);
1966 # Insert a null revision
1967 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1968 $nullRevId = $nullRevision->insertOn( $dbw );
1970 $latest = $this->getLatest();
1971 # Update page record
1972 $dbw->update( 'page',
1974 'page_touched' => $dbw->timestamp(),
1975 'page_restrictions' => '',
1976 'page_latest' => $nullRevId
1977 ), array( /* WHERE */
1979 ), 'Article::protect'
1982 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest) );
1983 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1985 # Update the protection log
1986 $log = new LogPage( 'protect' );
1988 $params = array($protect_description,$cascade ?
'cascade' : '');
1989 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
1991 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1995 } # End "changed" check
2001 * Take an array of page restrictions and flatten it to a string
2002 * suitable for insertion into the page_restrictions field.
2003 * @param array $limit
2007 function flattenRestrictions( $limit ) {
2008 if( !is_array( $limit ) ) {
2009 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2013 foreach( $limit as $action => $restrictions ) {
2014 if( $restrictions != '' ) {
2015 $bits[] = "$action=$restrictions";
2018 return implode( ':', $bits );
2022 * Auto-generates a deletion reason
2023 * @param bool &$hasHistory Whether the page has a history
2025 public function generateReason( &$hasHistory ) {
2027 $dbw = wfGetDB( DB_MASTER
);
2028 // Get the last revision
2029 $rev = Revision
::newFromTitle( $this->mTitle
);
2030 if( is_null( $rev ) )
2033 // Get the article's contents
2034 $contents = $rev->getText();
2036 // If the page is blank, use the text from the previous revision,
2037 // which can only be blank if there's a move/import/protect dummy revision involved
2038 if( $contents == '' ) {
2039 $prev = $rev->getPrevious();
2041 $contents = $prev->getText();
2046 // Find out if there was only one contributor
2047 // Only scan the last 20 revisions
2049 $res = $dbw->select( 'revision', 'rev_user_text',
2050 array( 'rev_page' => $this->getID() ), __METHOD__
,
2051 array( 'LIMIT' => $limit )
2053 if( $res === false )
2054 // This page has no revisions, which is very weird
2056 if( $res->numRows() > 1 )
2059 $hasHistory = false;
2060 $row = $dbw->fetchObject( $res );
2061 $onlyAuthor = $row->rev_user_text
;
2062 // Try to find a second contributor
2063 foreach( $res as $row ) {
2064 if( $row->rev_user_text
!= $onlyAuthor ) {
2065 $onlyAuthor = false;
2069 $dbw->freeResult( $res );
2071 // Generate the summary with a '$1' placeholder
2073 // The current revision is blank and the one before is also
2074 // blank. It's just not our lucky day
2075 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2078 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2080 $reason = wfMsgForContent( 'excontent', '$1' );
2083 // Replace newlines with spaces to prevent uglyness
2084 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2085 // Calculate the maximum amount of chars to get
2086 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2087 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2088 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2089 // Remove possible unfinished links
2090 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2091 // Now replace the '$1' placeholder
2092 $reason = str_replace( '$1', $contents, $reason );
2098 * UI entry point for page deletion
2101 global $wgUser, $wgOut, $wgRequest;
2103 $confirm = $wgRequest->wasPosted() &&
2104 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2106 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2107 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2109 $reason = $this->DeleteReasonList
;
2111 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2112 // Entry from drop down menu + additional comment
2113 $reason .= ': ' . $this->DeleteReason
;
2114 } elseif ( $reason == 'other' ) {
2115 $reason = $this->DeleteReason
;
2117 # Flag to hide all contents of the archived revisions
2118 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2120 # This code desperately needs to be totally rewritten
2122 # Read-only check...
2123 if ( wfReadOnly() ) {
2124 $wgOut->readOnlyPage();
2129 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2131 if (count($permission_errors)>0) {
2132 $wgOut->showPermissionsErrorPage( $permission_errors );
2136 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2138 # Better double-check that it hasn't been deleted yet!
2139 $dbw = wfGetDB( DB_MASTER
);
2140 $conds = $this->mTitle
->pageCond();
2141 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2142 if ( $latest === false ) {
2143 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2147 # Hack for big sites
2148 $bigHistory = $this->isBigDeletion();
2149 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2150 global $wgLang, $wgDeleteRevisionsLimit;
2151 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2152 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2157 $this->doDelete( $reason, $suppress );
2158 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2160 } elseif( $this->mTitle
->userIsWatching() ) {
2166 // Generate deletion reason
2167 $hasHistory = false;
2168 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2170 // If the page has a history, insert a warning
2171 if( $hasHistory && !$confirm ) {
2172 $skin=$wgUser->getSkin();
2173 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2175 global $wgLang, $wgDeleteRevisionsLimit;
2176 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2177 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2181 return $this->confirmDelete( $reason );
2185 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2187 function isBigDeletion() {
2188 global $wgDeleteRevisionsLimit;
2189 if( $wgDeleteRevisionsLimit ) {
2190 $revCount = $this->estimateRevisionCount();
2191 return $revCount > $wgDeleteRevisionsLimit;
2197 * @return int approximate revision count
2199 function estimateRevisionCount() {
2200 $dbr = wfGetDB( DB_SLAVE
);
2201 // For an exact count...
2202 //return $dbr->selectField( 'revision', 'COUNT(*)',
2203 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2204 return $dbr->estimateRowCount( 'revision', '*',
2205 array( 'rev_page' => $this->getId() ), __METHOD__
);
2209 * Get the last N authors
2210 * @param int $num Number of revisions to get
2211 * @param string $revLatest The latest rev_id, selected from the master (optional)
2212 * @return array Array of authors, duplicates not removed
2214 function getLastNAuthors( $num, $revLatest = 0 ) {
2215 wfProfileIn( __METHOD__
);
2217 // First try the slave
2218 // If that doesn't have the latest revision, try the master
2220 $db = wfGetDB( DB_SLAVE
);
2222 $res = $db->select( array( 'page', 'revision' ),
2223 array( 'rev_id', 'rev_user_text' ),
2225 'page_namespace' => $this->mTitle
->getNamespace(),
2226 'page_title' => $this->mTitle
->getDBkey(),
2227 'rev_page = page_id'
2228 ), __METHOD__
, $this->getSelectOptions( array(
2229 'ORDER BY' => 'rev_timestamp DESC',
2234 wfProfileOut( __METHOD__
);
2237 $row = $db->fetchObject( $res );
2238 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2239 $db = wfGetDB( DB_MASTER
);
2244 } while ( $continue );
2246 $authors = array( $row->rev_user_text
);
2247 while ( $row = $db->fetchObject( $res ) ) {
2248 $authors[] = $row->rev_user_text
;
2250 wfProfileOut( __METHOD__
);
2255 * Output deletion confirmation dialog
2256 * @param $reason string Prefilled reason
2258 function confirmDelete( $reason ) {
2259 global $wgOut, $wgUser;
2261 wfDebug( "Article::confirmDelete\n" );
2263 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2264 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2265 $wgOut->addWikiMsg( 'confirmdeletetext' );
2267 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2268 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2270 <td class='mw-input'>" .
2271 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2272 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2278 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2280 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2281 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2282 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2283 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2284 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2285 "<tr id=\"wpDeleteReasonListRow\">
2286 <td class='mw-label'>" .
2287 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2289 <td class='mw-input'>" .
2290 Xml
::listDropDown( 'wpDeleteReasonList',
2291 wfMsgForContent( 'deletereason-dropdown' ),
2292 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2295 <tr id=\"wpDeleteReasonRow\">
2296 <td class='mw-label'>" .
2297 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2299 <td class='mw-input'>" .
2300 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2301 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2306 <td class='mw-input'>" .
2307 Xml
::checkLabel( wfMsg( 'watchthis' ),
2308 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2314 <td class='mw-submit'>" .
2315 Xml
::submitButton( wfMsg( 'deletepage' ),
2316 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2319 Xml
::closeElement( 'table' ) .
2320 Xml
::closeElement( 'fieldset' ) .
2321 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2322 Xml
::closeElement( 'form' );
2324 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2325 $skin = $wgUser->getSkin();
2326 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2327 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2330 $wgOut->addHTML( $form );
2331 $this->showLogExtract( $wgOut );
2336 * Show relevant lines from the deletion log
2338 function showLogExtract( $out ) {
2339 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2340 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2345 * Perform a deletion and output success or failure messages
2347 function doDelete( $reason, $suppress = false ) {
2348 global $wgOut, $wgUser;
2349 wfDebug( __METHOD__
."\n" );
2351 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2355 if ( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2356 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2357 $deleted = $this->mTitle
->getPrefixedText();
2359 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2360 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2362 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2364 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2365 $wgOut->returnToMain( false );
2366 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2369 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2371 $wgOut->showFatalError( $error );
2377 * Back-end article deletion
2378 * Deletes the article with database consistency, writes logs, purges caches
2381 function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2382 global $wgUseSquid, $wgDeferredUpdateList;
2383 global $wgUseTrackbacks;
2385 wfDebug( __METHOD__
."\n" );
2387 $dbw = wfGetDB( DB_MASTER
);
2388 $ns = $this->mTitle
->getNamespace();
2389 $t = $this->mTitle
->getDBkey();
2390 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2392 if ( $t == '' ||
$id == 0 ) {
2396 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2397 array_push( $wgDeferredUpdateList, $u );
2399 // Bitfields to further suppress the content
2402 // This should be 15...
2403 $bitfield |
= Revision
::DELETED_TEXT
;
2404 $bitfield |
= Revision
::DELETED_COMMENT
;
2405 $bitfield |
= Revision
::DELETED_USER
;
2406 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2408 $bitfield = 'rev_deleted';
2412 // For now, shunt the revision data into the archive table.
2413 // Text is *not* removed from the text table; bulk storage
2414 // is left intact to avoid breaking block-compression or
2415 // immutable storage schemes.
2417 // For backwards compatibility, note that some older archive
2418 // table entries will have ar_text and ar_flags fields still.
2420 // In the future, we may keep revisions and mark them with
2421 // the rev_deleted field, which is reserved for this purpose.
2422 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2424 'ar_namespace' => 'page_namespace',
2425 'ar_title' => 'page_title',
2426 'ar_comment' => 'rev_comment',
2427 'ar_user' => 'rev_user',
2428 'ar_user_text' => 'rev_user_text',
2429 'ar_timestamp' => 'rev_timestamp',
2430 'ar_minor_edit' => 'rev_minor_edit',
2431 'ar_rev_id' => 'rev_id',
2432 'ar_text_id' => 'rev_text_id',
2433 'ar_text' => '\'\'', // Be explicit to appease
2434 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2435 'ar_len' => 'rev_len',
2436 'ar_page_id' => 'page_id',
2437 'ar_deleted' => $bitfield
2440 'page_id = rev_page'
2444 # Delete restrictions for it
2445 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2447 # Now that it's safely backed up, delete it
2448 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2449 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2455 # If using cascading deletes, we can skip some explicit deletes
2456 if ( !$dbw->cascadingDeletes() ) {
2457 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2459 if ($wgUseTrackbacks)
2460 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2462 # Delete outgoing links
2463 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2464 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2465 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2466 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2467 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2468 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2469 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2472 # If using cleanup triggers, we can skip some manual deletes
2473 if ( !$dbw->cleanupTriggers() ) {
2474 # Clean up recentchanges entries...
2475 $dbw->delete( 'recentchanges',
2476 array( 'rc_type != '.RC_LOG
,
2477 'rc_namespace' => $this->mTitle
->getNamespace(),
2478 'rc_title' => $this->mTitle
->getDBKey() ),
2480 $dbw->delete( 'recentchanges',
2481 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2486 Article
::onArticleDelete( $this->mTitle
);
2488 # Fix category table counts
2490 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2491 foreach( $res as $row ) {
2492 $cats []= $row->cl_to
;
2494 $this->updateCategoryCounts( array(), $cats );
2496 # Clear the cached article id so the interface doesn't act like we exist
2497 $this->mTitle
->resetArticleID( 0 );
2498 $this->mTitle
->mArticleID
= 0;
2500 # Log the deletion, if the page was suppressed, log it at Oversight instead
2501 $logtype = $suppress ?
'suppress' : 'delete';
2502 $log = new LogPage( $logtype );
2504 # Make sure logging got through
2505 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2513 * Roll back the most recent consecutive set of edits to a page
2514 * from the same user; fails if there are no eligible edits to
2515 * roll back to, e.g. user is the sole contributor. This function
2516 * performs permissions checks on $wgUser, then calls commitRollback()
2517 * to do the dirty work
2519 * @param string $fromP - Name of the user whose edits to rollback.
2520 * @param string $summary - Custom summary. Set to default summary if empty.
2521 * @param string $token - Rollback token.
2522 * @param bool $bot - If true, mark all reverted edits as bot.
2524 * @param array $resultDetails contains result-specific array of additional values
2525 * 'alreadyrolled' : 'current' (rev)
2526 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2528 * @return array of errors, each error formatted as
2529 * array(messagekey, param1, param2, ...).
2530 * On success, the array is empty. This array can also be passed to
2531 * OutputPage::showPermissionsErrorPage().
2533 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2535 $resultDetails = null;
2538 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2539 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2540 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2541 $errors[] = array( 'sessionfailure' );
2543 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2544 $errors[] = array( 'actionthrottledtext' );
2546 # If there were errors, bail out now
2550 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2554 * Backend implementation of doRollback(), please refer there for parameter
2555 * and return value documentation
2557 * NOTE: This function does NOT check ANY permissions, it just commits the
2558 * rollback to the DB Therefore, you should only call this function direct-
2559 * ly if you want to use custom permissions checks. If you don't, use
2560 * doRollback() instead.
2562 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2563 global $wgUseRCPatrol, $wgUser, $wgLang;
2564 $dbw = wfGetDB( DB_MASTER
);
2566 if( wfReadOnly() ) {
2567 return array( array( 'readonlytext' ) );
2570 # Get the last editor
2571 $current = Revision
::newFromTitle( $this->mTitle
);
2572 if( is_null( $current ) ) {
2573 # Something wrong... no page?
2574 return array(array('notanarticle'));
2577 $from = str_replace( '_', ' ', $fromP );
2578 if( $from != $current->getUserText() ) {
2579 $resultDetails = array( 'current' => $current );
2580 return array(array('alreadyrolled',
2581 htmlspecialchars($this->mTitle
->getPrefixedText()),
2582 htmlspecialchars($fromP),
2583 htmlspecialchars($current->getUserText())
2587 # Get the last edit not by this guy
2588 $user = intval( $current->getUser() );
2589 $user_text = $dbw->addQuotes( $current->getUserText() );
2590 $s = $dbw->selectRow( 'revision',
2591 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2592 array( 'rev_page' => $current->getPage(),
2593 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2595 array( 'USE INDEX' => 'page_timestamp',
2596 'ORDER BY' => 'rev_timestamp DESC' )
2598 if( $s === false ) {
2599 # No one else ever edited this page
2600 return array(array('cantrollback'));
2601 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2602 # Only admins can see this text
2603 return array(array('notvisiblerev'));
2607 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2608 # Mark all reverted edits as bot
2611 if ( $wgUseRCPatrol ) {
2612 # Mark all reverted edits as patrolled
2613 $set['rc_patrolled'] = 1;
2617 $dbw->update( 'recentchanges', $set,
2619 'rc_cur_id' => $current->getPage(),
2620 'rc_user_text' => $current->getUserText(),
2621 "rc_timestamp > '{$s->rev_timestamp}'",
2626 # Generate the edit summary if necessary
2627 $target = Revision
::newFromId( $s->rev_id
);
2628 if( empty( $summary ) ){
2629 $summary = wfMsgForContent( 'revertpage' );
2632 # Allow the custom summary to use the same args as the default message
2634 $target->getUserText(), $from, $s->rev_id
,
2635 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2636 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2638 $summary = wfMsgReplaceArgs( $summary, $args );
2641 $flags = EDIT_UPDATE
;
2643 if( $wgUser->isAllowed('minoredit') )
2644 $flags |
= EDIT_MINOR
;
2646 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2647 $flags |
= EDIT_FORCE_BOT
;
2648 # Actually store the edit
2649 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2650 if ( !empty( $status->value
['revision'] ) ) {
2651 $revId = $status->value
['revision']->getId();
2656 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2658 $resultDetails = array(
2659 'summary' => $summary,
2660 'current' => $current,
2661 'target' => $target,
2668 * User interface for rollback operations
2670 function rollback() {
2671 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2674 $result = $this->doRollback(
2675 $wgRequest->getVal( 'from' ),
2676 $wgRequest->getText( 'summary' ),
2677 $wgRequest->getVal( 'token' ),
2678 $wgRequest->getBool( 'bot' ),
2682 if( in_array( array( 'blocked' ), $result ) ) {
2683 $wgOut->blockedPage();
2686 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2687 $wgOut->rateLimited();
2690 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2691 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2692 $errArray = $result[0];
2693 $errMsg = array_shift( $errArray );
2694 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2695 if( isset( $details['current'] ) ){
2696 $current = $details['current'];
2697 if( $current->getComment() != '' ) {
2698 $wgOut->addWikiMsgArray( 'editcomment', array(
2699 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2704 # Display permissions errors before read-only message -- there's no
2705 # point in misleading the user into thinking the inability to rollback
2706 # is only temporary.
2707 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2708 # array_diff is completely broken for arrays of arrays, sigh. Re-
2709 # move any 'readonlytext' error manually.
2711 foreach( $result as $error ) {
2712 if( $error != array( 'readonlytext' ) ) {
2716 $wgOut->showPermissionsErrorPage( $out );
2719 if( $result == array( array('readonlytext') ) ) {
2720 $wgOut->readOnlyPage();
2724 $current = $details['current'];
2725 $target = $details['target'];
2726 $newId = $details['newid'];
2727 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2728 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2729 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2730 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2731 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2732 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2733 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2734 $wgOut->returnToMain( false, $this->mTitle
);
2736 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2737 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2738 $de->showDiff( '', '' );
2744 * Do standard deferred updates after page view
2747 function viewUpdates() {
2748 global $wgDeferredUpdateList, $wgUser;
2750 if ( 0 != $this->getID() ) {
2751 # Don't update page view counters on views from bot users (bug 14044)
2752 global $wgDisableCounters;
2753 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2754 Article
::incViewCount( $this->getID() );
2755 $u = new SiteStatsUpdate( 1, 0, 0 );
2756 array_push( $wgDeferredUpdateList, $u );
2760 # Update newtalk / watchlist notification status
2761 $wgUser->clearNotification( $this->mTitle
);
2765 * Prepare text which is about to be saved.
2766 * Returns a stdclass with source, pst and output members
2768 function prepareTextForEdit( $text, $revid=null ) {
2769 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2771 return $this->mPreparedEdit
;
2774 $edit = (object)array();
2775 $edit->revid
= $revid;
2776 $edit->newText
= $text;
2777 $edit->pst
= $this->preSaveTransform( $text );
2778 $options = new ParserOptions
;
2779 $options->setTidy( true );
2780 $options->enableLimitReport();
2781 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2782 $edit->oldText
= $this->getContent();
2783 $this->mPreparedEdit
= $edit;
2788 * Do standard deferred updates after page edit.
2789 * Update links tables, site stats, search index and message cache.
2790 * Purges pages that include this page if the text was changed here.
2791 * Every 100th edit, prune the recent changes table.
2794 * @param $text New text of the article
2795 * @param $summary Edit summary
2796 * @param $minoredit Minor edit
2797 * @param $timestamp_of_pagechange Timestamp associated with the page change
2798 * @param $newid rev_id value of the new revision
2799 * @param $changed Whether or not the content actually changed
2801 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2802 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2804 wfProfileIn( __METHOD__
);
2807 # Be careful not to double-PST: $text is usually already PST-ed once
2808 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2809 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2810 $editInfo = $this->prepareTextForEdit( $text, $newid );
2812 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2813 $editInfo = $this->mPreparedEdit
;
2816 # Save it to the parser cache
2817 if ( $wgEnableParserCache ) {
2818 $parserCache = ParserCache
::singleton();
2819 $parserCache->save( $editInfo->output
, $this, $wgUser );
2822 # Update the links tables
2823 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
, false );
2824 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2827 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2829 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2830 if ( 0 == mt_rand( 0, 99 ) ) {
2831 // Flush old entries from the `recentchanges` table; we do this on
2832 // random requests so as to avoid an increase in writes for no good reason
2834 $dbw = wfGetDB( DB_MASTER
);
2835 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2836 $recentchanges = $dbw->tableName( 'recentchanges' );
2837 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2838 $dbw->query( $sql );
2842 $id = $this->getID();
2843 $title = $this->mTitle
->getPrefixedDBkey();
2844 $shortTitle = $this->mTitle
->getDBkey();
2847 wfProfileOut( __METHOD__
);
2851 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2852 array_push( $wgDeferredUpdateList, $u );
2853 $u = new SearchUpdate( $id, $title, $text );
2854 array_push( $wgDeferredUpdateList, $u );
2856 # If this is another user's talk page, update newtalk
2857 # Don't do this if $changed = false otherwise some idiot can null-edit a
2858 # load of user talk pages and piss people off, nor if it's a minor edit
2859 # by a properly-flagged bot.
2860 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2861 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2862 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2863 $other = User
::newFromName( $shortTitle, false );
2865 wfDebug( __METHOD__
.": invalid username\n" );
2866 } elseif( User
::isIP( $shortTitle ) ) {
2867 // An anonymous user
2868 $other->setNewtalk( true );
2869 } elseif( $other->isLoggedIn() ) {
2870 $other->setNewtalk( true );
2872 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2877 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2878 $wgMessageCache->replace( $shortTitle, $text );
2881 wfProfileOut( __METHOD__
);
2885 * Perform article updates on a special page creation.
2887 * @param Revision $rev
2889 * @todo This is a shitty interface function. Kill it and replace the
2890 * other shitty functions like editUpdates and such so it's not needed
2893 function createUpdates( $rev ) {
2894 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2895 $this->mTotalAdjustment
= 1;
2896 $this->editUpdates( $rev->getText(), $rev->getComment(),
2897 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2901 * Generate the navigation links when browsing through an article revisions
2902 * It shows the information as:
2903 * Revision as of \<date\>; view current revision
2904 * \<- Previous version | Next Version -\>
2907 * @param string $oldid Revision ID of this article revision
2909 function setOldSubtitle( $oldid=0 ) {
2910 global $wgLang, $wgOut, $wgUser;
2912 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2916 $revision = Revision
::newFromId( $oldid );
2918 $current = ( $oldid == $this->mLatest
);
2919 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2920 $sk = $wgUser->getSkin();
2922 ?
wfMsg( 'currentrevisionlink' )
2923 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2926 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2927 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2929 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2930 : wfMsg( 'previousrevision' );
2932 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2934 $nextlink = $current
2935 ?
wfMsg( 'nextrevision' )
2936 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2937 $nextdiff = $current
2939 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2942 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2943 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2944 if( $revision->isCurrent() ) {
2945 // We don't handle top deleted edits too well
2946 $cdel = wfMsgHtml('rev-delundel');
2947 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2948 // If revision was hidden from sysops
2949 $cdel = wfMsgHtml('rev-delundel');
2951 $cdel = $sk->makeKnownLinkObj( $revdel,
2952 wfMsgHtml('rev-delundel'),
2953 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2954 '&oldid=' . urlencode( $oldid ) );
2955 // Bolden oversighted content
2956 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2957 $cdel = "<strong>$cdel</strong>";
2959 $cdel = "(<small>$cdel</small>) ";
2961 # Show user links if allowed to see them. Normally they
2962 # are hidden regardless, but since we can already see the text here...
2963 $userlinks = $sk->revUserTools( $revision, false );
2965 $m = wfMsg( 'revision-info-current' );
2966 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2967 ?
'revision-info-current'
2970 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks, $revision->getID() ) . "</div>\n" .
2972 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff,
2973 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2974 $wgOut->setSubtitle( $r );
2978 * This function is called right before saving the wikitext,
2979 * so we can do things like signatures and links-in-context.
2981 * @param string $text
2983 function preSaveTransform( $text ) {
2984 global $wgParser, $wgUser;
2985 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2988 /* Caching functions */
2991 * checkLastModified returns true if it has taken care of all
2992 * output to the client that is necessary for this request.
2993 * (that is, it has sent a cached version of the page)
2995 function tryFileCache() {
2996 static $called = false;
2998 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3002 if( $this->isFileCacheable() ) {
3003 $touched = $this->mTouched
;
3004 $cache = new HTMLFileCache( $this->mTitle
);
3005 if( $cache->isFileCacheGood( $touched ) ) {
3006 wfDebug( "Article::tryFileCache(): about to load file\n" );
3007 $cache->loadFromFileCache();
3010 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3011 ob_start( array(&$cache, 'saveToFileCache' ) );
3014 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3020 * Check if the page can be cached
3023 function isFileCacheable() {
3024 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
3025 // Get all query values
3026 $queryVals = $wgRequest->getValues();
3027 foreach( $queryVals as $query => $val ) {
3028 if( $query == 'title' ||
($query == 'action' && $val == 'view') ) {
3029 // Normal page view in query form
3034 // Check for non-standard user language; this covers uselang,
3035 // and extensions for auto-detecting user language.
3036 $ulang = $wgLang->getCode();
3037 $clang = $wgContLang->getCode();
3039 $cacheable = $wgUseFileCache
3040 && (!$wgShowIPinHeader)
3041 && ($this->getID() > 0)
3042 && ($wgUser->isAnon())
3043 && (!$wgUser->getNewtalk())
3044 && (!$this->mRedirectedFrom
)
3045 && ($ulang === $clang);
3046 // Extension may have reason to disable file caching on some pages.
3048 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3054 * Loads page_touched and returns a value indicating if it should be used
3057 function checkTouched() {
3058 if( !$this->mDataLoaded
) {
3059 $this->loadPageData();
3061 return !$this->mIsRedirect
;
3065 * Get the page_touched field
3067 function getTouched() {
3068 # Ensure that page data has been loaded
3069 if( !$this->mDataLoaded
) {
3070 $this->loadPageData();
3072 return $this->mTouched
;
3076 * Get the page_latest field
3078 function getLatest() {
3079 if ( !$this->mDataLoaded
) {
3080 $this->loadPageData();
3082 return $this->mLatest
;
3086 * Edit an article without doing all that other stuff
3087 * The article must already exist; link tables etc
3088 * are not updated, caches are not flushed.
3090 * @param string $text text submitted
3091 * @param string $comment comment submitted
3092 * @param bool $minor whereas it's a minor modification
3094 function quickEdit( $text, $comment = '', $minor = 0 ) {
3095 wfProfileIn( __METHOD__
);
3097 $dbw = wfGetDB( DB_MASTER
);
3098 $revision = new Revision( array(
3099 'page' => $this->getId(),
3101 'comment' => $comment,
3102 'minor_edit' => $minor ?
1 : 0,
3104 $revision->insertOn( $dbw );
3105 $this->updateRevisionOn( $dbw, $revision );
3107 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3109 wfProfileOut( __METHOD__
);
3113 * Used to increment the view counter
3116 * @param integer $id article id
3118 function incViewCount( $id ) {
3119 $id = intval( $id );
3120 global $wgHitcounterUpdateFreq, $wgDBtype;
3122 $dbw = wfGetDB( DB_MASTER
);
3123 $pageTable = $dbw->tableName( 'page' );
3124 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3125 $acchitsTable = $dbw->tableName( 'acchits' );
3127 if( $wgHitcounterUpdateFreq <= 1 ) {
3128 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3132 # Not important enough to warrant an error page in case of failure
3133 $oldignore = $dbw->ignoreErrors( true );
3135 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3137 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3138 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3139 # Most of the time (or on SQL errors), skip row count check
3140 $dbw->ignoreErrors( $oldignore );
3144 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3145 $row = $dbw->fetchObject( $res );
3146 $rown = intval( $row->n
);
3147 if( $rown >= $wgHitcounterUpdateFreq ){
3148 wfProfileIn( 'Article::incViewCount-collect' );
3149 $old_user_abort = ignore_user_abort( true );
3151 if ($wgDBtype == 'mysql')
3152 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3153 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3154 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3155 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3157 $dbw->query("DELETE FROM $hitcounterTable");
3158 if ($wgDBtype == 'mysql') {
3159 $dbw->query('UNLOCK TABLES');
3160 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3161 'WHERE page_id = hc_id');
3164 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3165 "FROM $acchitsTable WHERE page_id = hc_id");
3167 $dbw->query("DROP TABLE $acchitsTable");
3169 ignore_user_abort( $old_user_abort );
3170 wfProfileOut( 'Article::incViewCount-collect' );
3172 $dbw->ignoreErrors( $oldignore );
3176 * The onArticle*() functions are supposed to be a kind of hooks
3177 * which should be called whenever any of the specified actions
3180 * This is a good place to put code to clear caches, for instance.
3182 * This is called on page move and undelete, as well as edit
3184 * @param $title_obj a title object
3187 public static function onArticleCreate( $title ) {
3188 # Update existence markers on article/talk tabs...
3189 if ( $title->isTalkPage() ) {
3190 $other = $title->getSubjectPage();
3192 $other = $title->getTalkPage();
3194 $other->invalidateCache();
3195 $other->purgeSquid();
3197 $title->touchLinks();
3198 $title->purgeSquid();
3199 $title->deleteTitleProtection();
3202 public static function onArticleDelete( $title ) {
3203 global $wgUseFileCache, $wgMessageCache;
3204 # Update existence markers on article/talk tabs...
3205 if( $title->isTalkPage() ) {
3206 $other = $title->getSubjectPage();
3208 $other = $title->getTalkPage();
3210 $other->invalidateCache();
3211 $other->purgeSquid();
3213 $title->touchLinks();
3214 $title->purgeSquid();
3217 if ( $wgUseFileCache ) {
3218 $cm = new HTMLFileCache( $title );
3219 @unlink
( $cm->fileCacheName() );
3223 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3224 $wgMessageCache->replace( $title->getDBkey(), false );
3227 if( $title->getNamespace() == NS_IMAGE
) {
3228 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3229 $update->doUpdate();
3232 if( $title->getNamespace() == NS_USER_TALK
) {
3233 $user = User
::newFromName( $title->getText(), false );
3234 $user->setNewtalk( false );
3239 * Purge caches on page update etc
3241 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3242 global $wgDeferredUpdateList, $wgUseFileCache;
3244 // Invalidate caches of articles which include this page
3245 if( $transclusions !== 'skiptransclusions' )
3246 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3248 // Invalidate the caches of all pages which redirect here
3249 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3251 # Purge squid for this page only
3252 $title->purgeSquid();
3254 # Clear file cache for this page only
3255 if ( $wgUseFileCache ) {
3256 $cm = new HTMLFileCache( $title );
3257 @unlink
( $cm->fileCacheName() );
3264 * Overriden by ImagePage class, only present here to avoid a fatal error
3265 * Called for ?action=revert
3267 public function revert(){
3269 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3273 * Info about this page
3274 * Called for ?action=info when $wgAllowPageInfo is on.
3279 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3281 if ( !$wgAllowPageInfo ) {
3282 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3286 $page = $this->mTitle
->getSubjectPage();
3288 $wgOut->setPagetitle( $page->getPrefixedText() );
3289 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3290 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3292 if( !$this->mTitle
->exists() ) {
3293 $wgOut->addHtml( '<div class="noarticletext">' );
3294 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3295 // This doesn't quite make sense; the user is asking for
3296 // information about the _page_, not the message... -- RC
3297 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3299 $msg = $wgUser->isLoggedIn()
3301 : 'noarticletextanon';
3302 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3304 $wgOut->addHtml( '</div>' );
3306 $dbr = wfGetDB( DB_SLAVE
);
3308 'wl_title' => $page->getDBkey(),
3309 'wl_namespace' => $page->getNamespace() );
3310 $numwatchers = $dbr->selectField(
3315 $this->getSelectOptions() );
3317 $pageInfo = $this->pageCountInfo( $page );
3318 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3320 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3321 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3323 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3325 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3327 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3329 $wgOut->addHTML( '</ul>' );
3335 * Return the total number of edits and number of unique editors
3336 * on a given page. If page does not exist, returns false.
3338 * @param Title $title
3342 function pageCountInfo( $title ) {
3343 $id = $title->getArticleId();
3348 $dbr = wfGetDB( DB_SLAVE
);
3350 $rev_clause = array( 'rev_page' => $id );
3352 $edits = $dbr->selectField(
3357 $this->getSelectOptions() );
3359 $authors = $dbr->selectField(
3361 'COUNT(DISTINCT rev_user_text)',
3364 $this->getSelectOptions() );
3366 return array( 'edits' => $edits, 'authors' => $authors );
3370 * Return a list of templates used by this article.
3371 * Uses the templatelinks table
3373 * @return array Array of Title objects
3375 public function getUsedTemplates() {
3377 $id = $this->mTitle
->getArticleID();
3382 $dbr = wfGetDB( DB_SLAVE
);
3383 $res = $dbr->select( array( 'templatelinks' ),
3384 array( 'tl_namespace', 'tl_title' ),
3385 array( 'tl_from' => $id ),
3387 if( false !== $res ) {
3388 foreach( $res as $row ) {
3389 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3392 $dbr->freeResult( $res );
3397 * Returns a list of hidden categories this page is a member of.
3398 * Uses the page_props and categorylinks tables.
3400 * @return array Array of Title objects
3402 public function getHiddenCategories() {
3404 $id = $this->mTitle
->getArticleID();
3409 $dbr = wfGetDB( DB_SLAVE
);
3410 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3412 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3413 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3415 if ( false !== $res ) {
3416 foreach( $res as $row ) {
3417 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3420 $dbr->freeResult( $res );
3425 * Return an applicable autosummary if one exists for the given edit.
3426 * @param string $oldtext The previous text of the page.
3427 * @param string $newtext The submitted text of the page.
3428 * @param bitmask $flags A bitmask of flags submitted for the edit.
3429 * @return string An appropriate autosummary, or an empty string.
3431 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3432 # Decide what kind of autosummary is needed.
3434 # Redirect autosummaries
3435 $rt = Title
::newFromRedirect( $newtext );
3436 if( is_object( $rt ) ) {
3437 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3440 # New page autosummaries
3441 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3442 # If they're making a new article, give its text, truncated, in the summary.
3444 $truncatedtext = $wgContLang->truncate(
3445 str_replace("\n", ' ', $newtext),
3446 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3448 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3451 # Blanking autosummaries
3452 if( $oldtext != '' && $newtext == '' ) {
3453 return wfMsgForContent('autosumm-blank');
3454 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3455 # Removing more than 90% of the article
3457 $truncatedtext = $wgContLang->truncate(
3459 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3462 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3465 # If we reach this point, there's no applicable autosummary for our case, so our
3466 # autosummary is empty.
3471 * Add the primary page-view wikitext to the output buffer
3472 * Saves the text into the parser cache if possible.
3473 * Updates templatelinks if it is out of date.
3475 * @param string $text
3476 * @param bool $cache
3478 public function outputWikiText( $text, $cache = true ) {
3479 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3481 $popts = $wgOut->parserOptions();
3482 $popts->setTidy(true);
3483 $popts->enableLimitReport();
3484 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3485 $popts, true, true, $this->getRevIdFetched() );
3486 $popts->setTidy(false);
3487 $popts->enableLimitReport( false );
3488 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3489 $parserCache = ParserCache
::singleton();
3490 $parserCache->save( $parserOutput, $this, $wgUser );
3492 // Make sure file cache is not used on uncacheable content.
3493 // Output that has magic words in it can still use the parser cache
3494 // (if enabled), though it will generally expire sooner.
3495 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3496 $wgUseFileCache = false;
3499 if ( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3500 // templatelinks table may have become out of sync,
3501 // especially if using variable-based transclusions.
3502 // For paranoia, check if things have changed and if
3503 // so apply updates to the database. This will ensure
3504 // that cascaded protections apply as soon as the changes
3507 # Get templates from templatelinks
3508 $id = $this->mTitle
->getArticleID();
3510 $tlTemplates = array();
3512 $dbr = wfGetDB( DB_SLAVE
);
3513 $res = $dbr->select( array( 'templatelinks' ),
3514 array( 'tl_namespace', 'tl_title' ),
3515 array( 'tl_from' => $id ),
3520 if ( false !== $res ) {
3521 foreach( $res as $row ) {
3522 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3526 # Get templates from parser output.
3527 $poTemplates_allns = $parserOutput->getTemplates();
3529 $poTemplates = array ();
3530 foreach ( $poTemplates_allns as $ns_templates ) {
3531 $poTemplates = array_merge( $poTemplates, $ns_templates );
3535 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3537 if ( count( $templates_diff ) > 0 ) {
3538 # Whee, link updates time.
3539 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3544 $wgOut->addParserOutput( $parserOutput );
3548 * Update all the appropriate counts in the category table, given that
3549 * we've added the categories $added and deleted the categories $deleted.
3551 * @param $added array The names of categories that were added
3552 * @param $deleted array The names of categories that were deleted
3555 public function updateCategoryCounts( $added, $deleted ) {
3556 $ns = $this->mTitle
->getNamespace();
3557 $dbw = wfGetDB( DB_MASTER
);
3559 # First make sure the rows exist. If one of the "deleted" ones didn't
3560 # exist, we might legitimately not create it, but it's simpler to just
3561 # create it and then give it a negative value, since the value is bogus
3564 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3565 $insertCats = array_merge( $added, $deleted );
3566 if( !$insertCats ) {
3567 # Okay, nothing to do
3570 $insertRows = array();
3571 foreach( $insertCats as $cat ) {
3572 $insertRows[] = array( 'cat_title' => $cat );
3574 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3576 $addFields = array( 'cat_pages = cat_pages + 1' );
3577 $removeFields = array( 'cat_pages = cat_pages - 1' );
3578 if( $ns == NS_CATEGORY
) {
3579 $addFields[] = 'cat_subcats = cat_subcats + 1';
3580 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3581 } elseif( $ns == NS_IMAGE
) {
3582 $addFields[] = 'cat_files = cat_files + 1';
3583 $removeFields[] = 'cat_files = cat_files - 1';
3590 array( 'cat_title' => $added ),
3598 array( 'cat_title' => $deleted ),