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 public 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 );
61 return $t == null ?
null : new Article( $t );
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
69 public function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom
= $from;
74 * If this page is a redirect, get its target
76 * The target will be fetched from the redirect table if possible.
77 * If this page doesn't have an entry there, call insertRedirect()
78 * @return mixed Title object, or null if this page is not a redirect
80 public function getRedirectTarget() {
81 if( !$this->mTitle ||
!$this->mTitle
->isRedirect() )
83 if( !is_null($this->mRedirectTarget
) )
84 return $this->mRedirectTarget
;
85 # Query the redirect table
86 $dbr = wfGetDB( DB_SLAVE
);
87 $res = $dbr->select( 'redirect',
88 array('rd_namespace', 'rd_title'),
89 array('rd_from' => $this->getID()),
92 if( $row = $dbr->fetchObject($res) ) {
93 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
95 # This page doesn't have an entry in the redirect table
96 return $this->mRedirectTarget
= $this->insertRedirect();
100 * Insert an entry for this page into the redirect table.
102 * Don't call this function directly unless you know what you're doing.
103 * @return Title object
105 public function insertRedirect() {
106 $retval = Title
::newFromRedirect( $this->getContent() );
110 $dbw = wfGetDB( DB_MASTER
);
111 $dbw->replace( 'redirect', array('rd_from'),
113 'rd_from' => $this->getID(),
114 'rd_namespace' => $retval->getNamespace(),
115 'rd_title' => $retval->getDBKey()
123 * Get the Title object this page redirects to
125 * @return mixed false, Title of in-wiki target, or string with URL
127 public function followRedirect() {
128 $text = $this->getContent();
129 return $this->followRedirectText( $text );
133 * Get the Title object this text redirects to
135 * @return mixed false, Title of in-wiki target, or string with URL
137 public function followRedirectText( $text ) {
138 $rt = Title
::newFromRedirect( $text );
139 # process if title object is valid and not special:userlogout
141 if( $rt->getInterwiki() != '' ) {
142 if( $rt->isLocal() ) {
143 // Offsite wikis need an HTTP redirect.
145 // This can be hard to reverse and may produce loops,
146 // 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.
157 if( $rt->isSpecial( 'Userlogout' ) ) {
160 return $rt->getFullURL();
166 // No or invalid redirect
171 * get the title object of the article
173 public function getTitle() {
174 return $this->mTitle
;
181 public function clear() {
182 $this->mDataLoaded
= false;
183 $this->mContentLoaded
= false;
185 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
186 $this->mRedirectedFrom
= null; # Title object if set
187 $this->mRedirectTarget
= null; # Title object if set
189 $this->mTimestamp
= $this->mComment
= '';
190 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
191 $this->mTouched
= '19700101000000';
192 $this->mForUpdate
= false;
193 $this->mIsRedirect
= false;
194 $this->mRevIdFetched
= 0;
195 $this->mRedirectUrl
= false;
196 $this->mLatest
= false;
197 $this->mPreparedEdit
= false;
201 * Note that getContent/loadContent do not follow redirects anymore.
202 * If you need to fetch redirectable content easily, try
203 * the shortcut in Article::followContent()
205 * @return Return the text of this revision
207 public function getContent() {
208 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
209 wfProfileIn( __METHOD__
);
210 if( $this->getID() === 0 ) {
211 # If this is a MediaWiki:x message, then load the messages
212 # and return the message value for x.
213 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
214 # If this is a system message, get the default text.
215 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
216 $wgMessageCache->loadAllMessages( $lang );
217 $text = wfMsgGetKey( $message, false, $lang, false );
218 if( wfEmptyMsg( $message, $text ) )
221 $text = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
223 wfProfileOut( __METHOD__
);
226 $this->loadContent();
227 wfProfileOut( __METHOD__
);
228 return $this->mContent
;
233 * This function returns the text of a section, specified by a number ($section).
234 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
235 * the first section before any such heading (section 0).
237 * If a section contains subsections, these are also returned.
239 * @param $text String: text to look in
240 * @param $section Integer: section number
241 * @return string text of the requested section
244 public function getSection( $text, $section ) {
246 return $wgParser->getSection( $text, $section );
250 * @return int The oldid of the article that is to be shown, 0 for the
253 public function getOldID() {
254 if( is_null( $this->mOldId
) ) {
255 $this->mOldId
= $this->getOldIDFromRequest();
257 return $this->mOldId
;
261 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
263 * @return int The old id for the request
265 public function getOldIDFromRequest() {
267 $this->mRedirectUrl
= false;
268 $oldid = $wgRequest->getVal( 'oldid' );
269 if( isset( $oldid ) ) {
270 $oldid = intval( $oldid );
271 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
272 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
276 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
278 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
279 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
292 * Load the revision (including text) into this object
294 function loadContent() {
295 if( $this->mContentLoaded
) return;
296 wfProfileIn( __METHOD__
);
298 $oldid = $this->getOldID();
299 # Pre-fill content with error message so that if something
300 # fails we'll have something telling us what we intended.
301 $this->mOldId
= $oldid;
302 $this->fetchContent( $oldid );
303 wfProfileOut( __METHOD__
);
308 * Fetch a page record with the given conditions
309 * @param $dbr Database object
310 * @param $conditions Array
312 protected function pageData( $dbr, $conditions ) {
326 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
327 $row = $dbr->selectRow(
333 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
338 * @param $dbr Database object
339 * @param $title Title object
341 public function pageDataFromTitle( $dbr, $title ) {
342 return $this->pageData( $dbr, array(
343 'page_namespace' => $title->getNamespace(),
344 'page_title' => $title->getDBkey() ) );
348 * @param $dbr Database
351 protected function pageDataFromId( $dbr, $id ) {
352 return $this->pageData( $dbr, array( 'page_id' => $id ) );
356 * Set the general counter, title etc data loaded from
359 * @param $data Database row object or "fromdb"
361 public function loadPageData( $data = 'fromdb' ) {
362 if( $data === 'fromdb' ) {
363 $dbr = wfGetDB( DB_MASTER
);
364 $data = $this->pageDataFromId( $dbr, $this->getId() );
367 $lc = LinkCache
::singleton();
369 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
371 $this->mTitle
->mArticleID
= $data->page_id
;
373 # Old-fashioned restrictions
374 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
376 $this->mCounter
= $data->page_counter
;
377 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
378 $this->mIsRedirect
= $data->page_is_redirect
;
379 $this->mLatest
= $data->page_latest
;
381 if( is_object( $this->mTitle
) ) {
382 $lc->addBadLinkObj( $this->mTitle
);
384 $this->mTitle
->mArticleID
= 0;
387 $this->mDataLoaded
= true;
391 * Get text of an article from database
392 * Does *NOT* follow redirects.
393 * @param $oldid Int: 0 for whatever the latest revision is
396 function fetchContent( $oldid = 0 ) {
397 if( $this->mContentLoaded
) {
398 return $this->mContent
;
401 $dbr = wfGetDB( DB_MASTER
);
403 # Pre-fill content with error message so that if something
404 # fails we'll have something telling us what we intended.
405 $t = $this->mTitle
->getPrefixedText();
406 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
407 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
410 $revision = Revision
::newFromId( $oldid );
411 if( is_null( $revision ) ) {
412 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
415 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
417 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
420 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
421 $this->loadPageData( $data );
423 if( !$this->mDataLoaded
) {
424 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
426 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
429 $this->loadPageData( $data );
431 $revision = Revision
::newFromId( $this->mLatest
);
432 if( is_null( $revision ) ) {
433 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
438 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
439 // We should instead work with the Revision object when we need it...
440 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
442 $this->mUser
= $revision->getUser();
443 $this->mUserText
= $revision->getUserText();
444 $this->mComment
= $revision->getComment();
445 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
447 $this->mRevIdFetched
= $revision->getId();
448 $this->mContentLoaded
= true;
449 $this->mRevision
=& $revision;
451 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
453 return $this->mContent
;
457 * Read/write accessor to select FOR UPDATE
459 * @param $x Mixed: FIXME
461 public function forUpdate( $x = NULL ) {
462 return wfSetVar( $this->mForUpdate
, $x );
466 * Get the database which should be used for reads
469 * @deprecated - just call wfGetDB( DB_MASTER ) instead
472 wfDeprecated( __METHOD__
);
473 return wfGetDB( DB_MASTER
);
477 * Get options for all SELECT statements
479 * @param $options Array: an optional options array which'll be appended to
481 * @return Array: options
483 protected function getSelectOptions( $options = '' ) {
484 if( $this->mForUpdate
) {
485 if( is_array( $options ) ) {
486 $options[] = 'FOR UPDATE';
488 $options = 'FOR UPDATE';
495 * @return int Page ID
497 public function getID() {
498 if( $this->mTitle
) {
499 return $this->mTitle
->getArticleID();
506 * @return bool Whether or not the page exists in the database
508 public function exists() {
509 return $this->getId() > 0;
513 * Check if this page is something we're going to be showing
514 * some sort of sensible content for. If we return false, page
515 * views (plain action=view) will return an HTTP 404 response,
516 * so spiders and robots can know they're following a bad link.
520 public function hasViewableContent() {
521 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
525 * @return int The view count for the page
527 public function getCount() {
528 if( -1 == $this->mCounter
) {
529 $id = $this->getID();
533 $dbr = wfGetDB( DB_SLAVE
);
534 $this->mCounter
= $dbr->selectField( 'page',
536 array( 'page_id' => $id ),
538 $this->getSelectOptions()
542 return $this->mCounter
;
546 * Determine whether a page would be suitable for being counted as an
547 * article in the site_stats table based on the title & its content
549 * @param $text String: text to analyze
552 public function isCountable( $text ) {
553 global $wgUseCommaCount;
555 $token = $wgUseCommaCount ?
',' : '[[';
556 return $this->mTitle
->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
560 * Tests if the article text represents a redirect
562 * @param $text String: FIXME
565 public function isRedirect( $text = false ) {
566 if( $text === false ) {
567 if( $this->mDataLoaded
) {
568 return $this->mIsRedirect
;
570 // Apparently loadPageData was never called
571 $this->loadContent();
572 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
574 $titleObj = Title
::newFromRedirect( $text );
576 return $titleObj !== NULL;
580 * Returns true if the currently-referenced revision is the current edit
581 * to this page (and it exists).
584 public function isCurrent() {
585 # If no oldid, this is the current version.
586 if( $this->getOldID() == 0 ) {
589 return $this->exists() && isset($this->mRevision
) && $this->mRevision
->isCurrent();
593 * Loads everything except the text
594 * This isn't necessary for all uses, so it's only done if needed.
596 protected function loadLastEdit() {
597 if( -1 != $this->mUser
)
600 # New or non-existent articles have no user information
601 $id = $this->getID();
602 if( 0 == $id ) return;
604 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
605 if( !is_null( $this->mLastRevision
) ) {
606 $this->mUser
= $this->mLastRevision
->getUser();
607 $this->mUserText
= $this->mLastRevision
->getUserText();
608 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
609 $this->mComment
= $this->mLastRevision
->getComment();
610 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
611 $this->mRevIdFetched
= $this->mLastRevision
->getId();
615 public function getTimestamp() {
616 // Check if the field has been filled by ParserCache::get()
617 if( !$this->mTimestamp
) {
618 $this->loadLastEdit();
620 return wfTimestamp(TS_MW
, $this->mTimestamp
);
623 public function getUser() {
624 $this->loadLastEdit();
628 public function getUserText() {
629 $this->loadLastEdit();
630 return $this->mUserText
;
633 public function getComment() {
634 $this->loadLastEdit();
635 return $this->mComment
;
638 public function getMinorEdit() {
639 $this->loadLastEdit();
640 return $this->mMinorEdit
;
643 /* Use this to fetch the rev ID used on page views */
644 public function getRevIdFetched() {
645 $this->loadLastEdit();
646 return $this->mRevIdFetched
;
650 * @param $limit Integer: default 0.
651 * @param $offset Integer: default 0.
653 public 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
684 public function view() {
685 global $wgUser, $wgOut, $wgRequest, $wgContLang;
686 global $wgEnableParserCache, $wgStylePath, $wgParser;
687 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
688 global $wgDefaultRobotPolicy;
690 wfProfileIn( __METHOD__
);
692 # Get variables from query string
693 $oldid = $this->getOldID();
696 if( $oldid === 0 && $this->checkTouched() ) {
699 $parserCache = ParserCache
::singleton();
700 $wgOut->setETag( $parserCache->getETag($this,$wgUser) );
702 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
703 wfProfileOut( __METHOD__
);
705 } else if( $this->tryFileCache() ) {
706 # tell wgOut that output is taken care of
708 $this->viewUpdates();
709 wfProfileOut( __METHOD__
);
714 $ns = $this->mTitle
->getNamespace(); # shortcut
715 $sk = $wgUser->getSkin();
717 # getOldID may want us to redirect somewhere else
718 if( $this->mRedirectUrl
) {
719 $wgOut->redirect( $this->mRedirectUrl
);
720 wfProfileOut( __METHOD__
);
724 $diff = $wgRequest->getVal( 'diff' );
725 $rcid = $wgRequest->getVal( 'rcid' );
726 $rdfrom = $wgRequest->getVal( 'rdfrom' );
727 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
728 $purge = $wgRequest->getVal( 'action' ) == 'purge';
731 $wgOut->setArticleFlag( true );
733 # Discourage indexing of printable versions, but encourage following
734 if( $wgOut->isPrintable() ) {
735 $policy = 'noindex,follow';
736 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
737 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
738 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
739 # Honour customised robot policies for this namespace
740 $policy = $wgNamespaceRobotPolicies[$ns];
742 $policy = $wgDefaultRobotPolicy;
744 $wgOut->setRobotPolicy( $policy );
746 # If we got diff and oldid in the query, we want to see a
747 # diff page instead of the article.
749 if( !is_null( $diff ) ) {
750 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
752 $diff = $wgRequest->getVal( 'diff' );
753 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
754 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
755 // DifferenceEngine directly fetched the revision:
756 $this->mRevIdFetched
= $de->mNewid
;
757 $de->showDiffPage( $diffOnly );
759 // Needed to get the page's current revision
760 $this->loadPageData();
761 if( $diff == 0 ||
$diff == $this->mLatest
) {
762 # Run view updates for current revision only
763 $this->viewUpdates();
765 wfProfileOut( __METHOD__
);
769 # Should the parser cache be used?
770 $pcache = $this->useParserCache( $oldid );
771 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
772 if( $wgUser->getOption( 'stubthreshold' ) ) {
773 wfIncrStats( 'pcache_miss_stub' );
776 $wasRedirected = false;
777 if( isset( $this->mRedirectedFrom
) ) {
778 // This is an internally redirected page view.
779 // We'll need a backlink to the source page for navigation.
780 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
781 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
782 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
783 $wgOut->setSubtitle( $s );
785 // Set the fragment if one was specified in the redirect
786 if( strval( $this->mTitle
->getFragment() ) != '' ) {
787 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
788 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
790 $wasRedirected = true;
792 } elseif( !empty( $rdfrom ) ) {
793 // This is an externally redirected view, from some other wiki.
794 // If it was reported from a trusted site, supply a backlink.
795 global $wgRedirectSources;
796 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
797 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
798 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
799 $wgOut->setSubtitle( $s );
800 $wasRedirected = true;
805 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
806 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
807 // Ensure that UI elements requiring revision ID have
808 // the correct version information.
809 $wgOut->setRevisionId( $this->mLatest
);
812 # Fetch content and check for errors
814 # If the article does not exist and was deleted, show the log
815 if( $this->getID() == 0 ) {
816 $this->showDeletionLog();
818 $text = $this->getContent();
819 if( $text === false ) {
820 # Failed to load, replace text with error message
821 $t = $this->mTitle
->getPrefixedText();
823 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
824 $text = wfMsg( 'missing-article', $t, $d );
826 $text = wfMsg( 'noarticletext' );
831 if( $this->getID() === 0 ) {
832 $wgOut->setRobotPolicy( 'noindex,nofollow' );
833 $text = "<div class='noarticletext'>\n$text\n</div>";
834 if( !$this->hasViewableContent() ) {
835 // If there's no backing content, send a 404 Not Found
836 // for better machine handling of broken links.
842 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
845 # Another whitelist check in case oldid is altering the title
846 if( !$this->mTitle
->userCanRead() ) {
847 $wgOut->loginToUse();
850 wfProfileOut( __METHOD__
);
854 # We're looking at an old revision
855 if( !empty( $oldid ) ) {
856 $wgOut->setRobotPolicy( 'noindex,nofollow' );
857 if( is_null( $this->mRevision
) ) {
858 // FIXME: This would be a nice place to load the 'no such page' text.
860 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
861 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
862 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
863 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
864 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
865 wfProfileOut( __METHOD__
);
868 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
869 // and we are allowed to see...
875 $wgOut->setRevisionId( $this->getRevIdFetched() );
877 // Pages containing custom CSS or JavaScript get special treatment
878 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
879 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
880 // Give hooks a chance to customise the output
881 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
882 // Wrap the whole lot in a <pre> and don't parse
884 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
885 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
886 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
887 $wgOut->addHTML( "\n</pre>\n" );
889 } else if( $rt = Title
::newFromRedirect( $text ) ) {
890 # Don't append the subtitle if this was an old revision
891 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
892 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
893 $wgOut->addParserOutputNoText( $parseout );
894 } else if( $pcache ) {
895 # Display content and save to parser cache
896 $this->outputWikiText( $text );
898 # Display content, don't attempt to save to parser cache
899 # Don't show section-edit links on old revisions... this way lies madness.
900 if( !$this->isCurrent() ) {
901 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
903 # Display content and don't save to parser cache
904 # With timing hack -- TS 2006-07-26
906 $this->outputWikiText( $text, false );
911 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
912 $this->mTitle
->getPrefixedDBkey()));
915 if( !$this->isCurrent() ) {
916 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
920 /* title may have been set from the cache */
921 $t = $wgOut->getPageTitle();
923 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
925 # For the main page, overwrite the <title> element with the con-
926 # tents of 'pagetitle-view-mainpage' instead of the default (if
928 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
929 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
930 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
934 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
935 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
936 $wgOut->addWikiMsg('anontalkpagetext');
939 # If we have been passed an &rcid= parameter, we want to give the user a
940 # chance to mark this new article as patrolled.
941 if( !empty($rcid) && $this->mTitle
->exists() && $this->mTitle
->userCan('patrol') ) {
943 "<div class='patrollink'>" .
944 wfMsgHtml( 'markaspatrolledlink',
945 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
946 "action=markpatrolled&rcid=$rcid" )
953 if( $wgUseTrackbacks ) {
954 $this->addTrackbacks();
957 $this->viewUpdates();
958 wfProfileOut( __METHOD__
);
961 protected function showDeletionLog() {
962 global $wgUser, $wgOut;
963 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
964 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
965 if( $pager->getNumRows() > 0 ) {
967 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
968 $wgOut->addWikiMsg( 'deleted-notice' );
970 $loglist->beginLogEventsList() .
972 $loglist->endLogEventsList()
974 if( $pager->getNumRows() > 10 ) {
975 $wgOut->addHTML( $wgUser->getSkin()->link(
976 SpecialPage
::getTitleFor( 'Log' ),
977 wfMsgHtml( 'deletelog-fulllog' ),
979 array( 'type' => 'delete', 'page' => $this->mTitle
->getPrefixedText() )
982 $wgOut->addHTML( '</div>' );
987 * Should the parser cache be used?
989 protected function useParserCache( $oldid ) {
990 global $wgUser, $wgEnableParserCache;
992 return $wgEnableParserCache
993 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
996 && !$this->mTitle
->isCssOrJsPage()
997 && !$this->mTitle
->isCssJsSubpage();
1002 * @param $target Title object of destination to redirect
1003 * @param $appendSubtitle Boolean [optional]
1004 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1006 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1007 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1009 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1010 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
1012 if( $appendSubtitle ) {
1013 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1015 $sk = $wgUser->getSkin();
1017 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1019 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1021 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1022 '<span class="redirectText">'.$link.'</span>';
1026 public function addTrackbacks() {
1027 global $wgOut, $wgUser;
1028 $dbr = wfGetDB( DB_SLAVE
);
1029 $tbs = $dbr->select( 'trackbacks',
1030 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1031 array('tb_page' => $this->getID() )
1033 if( !$dbr->numRows($tbs) ) return;
1036 while( $o = $dbr->fetchObject($tbs) ) {
1038 if( $wgUser->isAllowed( 'trackback' ) ) {
1039 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1040 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1041 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1044 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1051 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1052 $this->mTitle
->invalidateCache();
1055 public function deletetrackback() {
1056 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1057 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1058 $wgOut->addWikiMsg( 'sessionfailure' );
1062 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1063 if( count($permission_errors) ) {
1064 $wgOut->showPermissionsErrorPage( $permission_errors );
1068 $db = wfGetDB( DB_MASTER
);
1069 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1071 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1072 $this->mTitle
->invalidateCache();
1075 public function render() {
1077 $wgOut->setArticleBodyOnly(true);
1082 * Handle action=purge
1084 public function purge() {
1085 global $wgUser, $wgRequest, $wgOut;
1086 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1087 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1092 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1093 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1094 $form = "<form method=\"post\" action=\"$action\">\n" .
1095 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1097 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1098 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1099 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1100 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1101 $wgOut->addHTML( $top . $form . $bottom );
1106 * Perform the actions of a page purging
1108 public function doPurge() {
1110 // Invalidate the cache
1111 $this->mTitle
->invalidateCache();
1114 // Commit the transaction before the purge is sent
1115 $dbw = wfGetDB( DB_MASTER
);
1116 $dbw->immediateCommit();
1119 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1120 $update->doUpdate();
1122 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1123 global $wgMessageCache;
1124 if( $this->getID() == 0 ) {
1127 $text = $this->getContent();
1129 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1134 * Insert a new empty page record for this article.
1135 * This *must* be followed up by creating a revision
1136 * and running $this->updateToLatest( $rev_id );
1137 * or else the record will be left in a funky state.
1138 * Best if all done inside a transaction.
1140 * @param $dbw Database
1141 * @return int The newly created page_id key, or false if the title already existed
1144 public function insertOn( $dbw ) {
1145 wfProfileIn( __METHOD__
);
1147 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1148 $dbw->insert( 'page', array(
1149 'page_id' => $page_id,
1150 'page_namespace' => $this->mTitle
->getNamespace(),
1151 'page_title' => $this->mTitle
->getDBkey(),
1152 'page_counter' => 0,
1153 'page_restrictions' => '',
1154 'page_is_redirect' => 0, # Will set this shortly...
1156 'page_random' => wfRandom(),
1157 'page_touched' => $dbw->timestamp(),
1158 'page_latest' => 0, # Fill this in shortly...
1159 'page_len' => 0, # Fill this in shortly...
1160 ), __METHOD__
, 'IGNORE' );
1162 $affected = $dbw->affectedRows();
1164 $newid = $dbw->insertId();
1165 $this->mTitle
->resetArticleId( $newid );
1167 wfProfileOut( __METHOD__
);
1168 return $affected ?
$newid : false;
1172 * Update the page record to point to a newly saved revision.
1174 * @param $dbw Database object
1175 * @param $revision Revision: For ID number, and text used to set
1176 length and redirect status fields
1177 * @param $lastRevision Integer: if given, will not overwrite the page field
1178 * when different from the currently set value.
1179 * Giving 0 indicates the new page flag should be set
1181 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1182 * removing rows in redirect table.
1183 * @return bool true on success, false on failure
1186 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1187 wfProfileIn( __METHOD__
);
1189 $text = $revision->getText();
1190 $rt = Title
::newFromRedirect( $text );
1192 $conditions = array( 'page_id' => $this->getId() );
1193 if( !is_null( $lastRevision ) ) {
1194 # An extra check against threads stepping on each other
1195 $conditions['page_latest'] = $lastRevision;
1198 $dbw->update( 'page',
1200 'page_latest' => $revision->getId(),
1201 'page_touched' => $dbw->timestamp(),
1202 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1203 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1204 'page_len' => strlen( $text ),
1209 $result = $dbw->affectedRows() != 0;
1211 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1214 wfProfileOut( __METHOD__
);
1219 * Add row to the redirect table if this is a redirect, remove otherwise.
1221 * @param $dbw Database
1222 * @param $redirectTitle a title object pointing to the redirect target,
1223 * or NULL if this is not a redirect
1224 * @param $lastRevIsRedirect If given, will optimize adding and
1225 * removing rows in redirect table.
1226 * @return bool true on success, false on failure
1229 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1230 // Always update redirects (target link might have changed)
1231 // Update/Insert if we don't know if the last revision was a redirect or not
1232 // Delete if changing from redirect to non-redirect
1233 $isRedirect = !is_null($redirectTitle);
1234 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1235 wfProfileIn( __METHOD__
);
1237 // This title is a redirect, Add/Update row in the redirect table
1238 $set = array( /* SET */
1239 'rd_namespace' => $redirectTitle->getNamespace(),
1240 'rd_title' => $redirectTitle->getDBkey(),
1241 'rd_from' => $this->getId(),
1243 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1245 // This is not a redirect, remove row from redirect table
1246 $where = array( 'rd_from' => $this->getId() );
1247 $dbw->delete( 'redirect', $where, __METHOD__
);
1249 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1250 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1252 wfProfileOut( __METHOD__
);
1253 return ( $dbw->affectedRows() != 0 );
1259 * If the given revision is newer than the currently set page_latest,
1260 * update the page record. Otherwise, do nothing.
1262 * @param $dbw Database object
1263 * @param $revision Revision object
1265 public function updateIfNewerOn( &$dbw, $revision ) {
1266 wfProfileIn( __METHOD__
);
1267 $row = $dbw->selectRow(
1268 array( 'revision', 'page' ),
1269 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1271 'page_id' => $this->getId(),
1272 'page_latest=rev_id' ),
1275 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1276 wfProfileOut( __METHOD__
);
1279 $prev = $row->rev_id
;
1280 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1282 # No or missing previous revision; mark the page as new
1284 $lastRevIsRedirect = null;
1286 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1287 wfProfileOut( __METHOD__
);
1292 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1293 * @return string Complete article text, or null if error
1295 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1296 wfProfileIn( __METHOD__
);
1297 if( strval( $section ) == '' ) {
1298 // Whole-page edit; let the whole text through
1300 if( is_null($edittime) ) {
1301 $rev = Revision
::newFromTitle( $this->mTitle
);
1303 $dbw = wfGetDB( DB_MASTER
);
1304 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1307 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1308 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1311 $oldtext = $rev->getText();
1313 if( $section == 'new' ) {
1314 # Inserting a new section
1315 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1316 $text = strlen( trim( $oldtext ) ) > 0
1317 ?
"{$oldtext}\n\n{$subject}{$text}"
1318 : "{$subject}{$text}";
1320 # Replacing an existing section; roll out the big guns
1322 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1325 wfProfileOut( __METHOD__
);
1330 * @deprecated use Article::doEdit()
1332 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1333 wfDeprecated( __METHOD__
);
1334 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1335 ( $isminor ? EDIT_MINOR
: 0 ) |
1336 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1337 ( $bot ? EDIT_FORCE_BOT
: 0 );
1339 # If this is a comment, add the summary as headline
1340 if( $comment && $summary != "" ) {
1341 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1344 $this->doEdit( $text, $summary, $flags );
1346 $dbw = wfGetDB( DB_MASTER
);
1348 if(!$this->mTitle
->userIsWatching()) {
1354 if( $this->mTitle
->userIsWatching() ) {
1360 $this->doRedirect( $this->isRedirect( $text ) );
1364 * @deprecated use Article::doEdit()
1366 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1367 wfDeprecated( __METHOD__
);
1368 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1369 ( $minor ? EDIT_MINOR
: 0 ) |
1370 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1372 $status = $this->doEdit( $text, $summary, $flags );
1373 if( !$status->isOK() ) {
1377 $dbw = wfGetDB( DB_MASTER
);
1379 if(!$this->mTitle
->userIsWatching()) {
1385 if( $this->mTitle
->userIsWatching() ) {
1392 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1393 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1395 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1402 * Change an existing article or create a new article. Updates RC and all necessary caches,
1403 * optionally via the deferred update array.
1405 * $wgUser must be set before calling this function.
1407 * @param $text String: new text
1408 * @param $summary String: edit summary
1409 * @param $flags Integer bitfield:
1411 * Article is known or assumed to be non-existent, create a new one
1413 * Article is known or assumed to be pre-existing, update it
1415 * Mark this edit minor, if the user is allowed to do so
1417 * Do not log the change in recentchanges
1419 * Mark the edit a "bot" edit regardless of user rights
1420 * EDIT_DEFER_UPDATES
1421 * Defer some of the updates until the end of index.php
1423 * Fill in blank summaries with generated text where possible
1425 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1426 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1427 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1428 * edit-already-exists error will be returned. These two conditions are also possible with
1429 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1431 * @param $baseRevId the revision ID this edit was based off, if any
1432 * @param $user Optional user object, $wgUser will be used if not passed
1434 * @return Status object. Possible errors:
1435 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1436 * edit-gone-missing: In update mode, but the article didn't exist
1437 * edit-conflict: In update mode, the article changed unexpectedly
1438 * edit-no-change: Warning that the text was the same as before
1439 * edit-already-exists: In creation mode, but the article already exists
1441 * Extensions may define additional errors.
1443 * $return->value will contain an associative array with members as follows:
1444 * new: Boolean indicating if the function attempted to create a new article
1445 * revision: The revision object for the inserted revision, or null
1447 * Compatibility note: this function previously returned a boolean value indicating success/failure
1449 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1450 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1452 # Low-level sanity check
1453 if( $this->mTitle
->getText() == '' ) {
1454 throw new MWException( 'Something is trying to edit an article with an empty title' );
1457 wfProfileIn( __METHOD__
);
1459 $user = is_null($user) ?
$wgUser : $user;
1460 $status = Status
::newGood( array() );
1462 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1463 $this->loadPageData();
1465 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1466 $aid = $this->mTitle
->getArticleID();
1468 $flags |
= EDIT_UPDATE
;
1474 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1475 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1477 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1478 wfProfileOut( __METHOD__
);
1479 if( $status->isOK() ) {
1480 $status->fatal( 'edit-hook-aborted');
1485 # Silently ignore EDIT_MINOR if not allowed
1486 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1487 $bot = $flags & EDIT_FORCE_BOT
;
1489 $oldtext = $this->getContent();
1490 $oldsize = strlen( $oldtext );
1492 # Provide autosummaries if one is not provided and autosummaries are enabled.
1493 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1494 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1497 $editInfo = $this->prepareTextForEdit( $text );
1498 $text = $editInfo->pst
;
1499 $newsize = strlen( $text );
1501 $dbw = wfGetDB( DB_MASTER
);
1502 $now = wfTimestampNow();
1504 if( $flags & EDIT_UPDATE
) {
1505 # Update article, but only if changed.
1506 $status->value
['new'] = false;
1507 # Make sure the revision is either completely inserted or not inserted at all
1508 if( !$wgDBtransactions ) {
1509 $userAbort = ignore_user_abort( true );
1514 $changed = ( strcmp( $text, $oldtext ) != 0 );
1517 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1518 - (int)$this->isCountable( $oldtext );
1519 $this->mTotalAdjustment
= 0;
1521 if( !$this->mLatest
) {
1522 # Article gone missing
1523 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1524 $status->fatal( 'edit-gone-missing' );
1525 wfProfileOut( __METHOD__
);
1529 $revision = new Revision( array(
1530 'page' => $this->getId(),
1531 'comment' => $summary,
1532 'minor_edit' => $isminor,
1534 'parent_id' => $this->mLatest
,
1535 'user' => $user->getId(),
1536 'user_text' => $user->getName(),
1540 $revisionId = $revision->insertOn( $dbw );
1544 # Note that we use $this->mLatest instead of fetching a value from the master DB
1545 # during the course of this function. This makes sure that EditPage can detect
1546 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1547 # before this function is called. A previous function used a separate query, this
1548 # creates a window where concurrent edits can cause an ignored edit conflict.
1549 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1552 /* Belated edit conflict! Run away!! */
1553 $status->fatal( 'edit-conflict' );
1554 # Delete the invalid revision if the DB is not transactional
1555 if( !$wgDBtransactions ) {
1556 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1561 global $wgUseRCPatrol;
1562 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1563 # Update recentchanges
1564 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1565 # Mark as patrolled if the user can do so
1566 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan('autopatrol');
1567 # Add RC row to the DB
1568 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1569 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1570 $revisionId, $patrolled
1572 # Log auto-patrolled edits
1574 PatrolLog
::record( $rc, true );
1577 $user->incEditCount();
1581 $status->warning( 'edit-no-change' );
1583 // Keep the same revision ID, but do some updates on it
1584 $revisionId = $this->getRevIdFetched();
1585 // Update page_touched, this is usually implicit in the page update
1586 // Other cache updates are done in onArticleEdit()
1587 $this->mTitle
->invalidateCache();
1590 if( !$wgDBtransactions ) {
1591 ignore_user_abort( $userAbort );
1593 // Now that ignore_user_abort is restored, we can respond to fatal errors
1594 if( !$status->isOK() ) {
1595 wfProfileOut( __METHOD__
);
1599 # Invalidate cache of this article and all pages using this article
1600 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1601 Article
::onArticleEdit( $this->mTitle
, 'skiptransclusions' );
1602 # Update links tables, site stats, etc.
1603 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1605 # Create new article
1606 $status->value
['new'] = true;
1608 # Set statistics members
1609 # We work out if it's countable after PST to avoid counter drift
1610 # when articles are created with {{subst:}}
1611 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1612 $this->mTotalAdjustment
= 1;
1616 # Add the page record; stake our claim on this title!
1617 # This will return false if the article already exists
1618 $newid = $this->insertOn( $dbw );
1620 if( $newid === false ) {
1622 $status->fatal( 'edit-already-exists' );
1623 wfProfileOut( __METHOD__
);
1627 # Save the revision text...
1628 $revision = new Revision( array(
1630 'comment' => $summary,
1631 'minor_edit' => $isminor,
1633 'user' => $user->getId(),
1634 'user_text' => $user->getName(),
1636 $revisionId = $revision->insertOn( $dbw );
1638 $this->mTitle
->resetArticleID( $newid );
1640 # Update the page record with revision data
1641 $this->updateRevisionOn( $dbw, $revision, 0 );
1643 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1644 # Update recentchanges
1645 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1646 global $wgUseRCPatrol, $wgUseNPPatrol;
1647 # Mark as patrolled if the user can do so
1648 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $this->mTitle
->userCan('autopatrol');
1649 # Add RC row to the DB
1650 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1651 '', strlen($text), $revisionId, $patrolled );
1652 # Log auto-patrolled edits
1654 PatrolLog
::record( $rc, true );
1657 $user->incEditCount();
1660 # Update links, etc.
1661 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1664 Article
::onArticleCreate( $this->mTitle
);
1666 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1667 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1670 # Do updates right now unless deferral was requested
1671 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1675 // Return the new revision (or null) to the caller
1676 $status->value
['revision'] = $revision;
1678 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1679 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status ) );
1681 wfProfileOut( __METHOD__
);
1686 * @deprecated wrapper for doRedirect
1688 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1689 wfDeprecated( __METHOD__
);
1690 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1694 * Output a redirect back to the article.
1695 * This is typically used after an edit.
1697 * @param $noRedir Boolean: add redirect=no
1698 * @param $sectionAnchor String: section to redirect to, including "#"
1699 * @param $extraQuery String: extra query params
1701 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1704 $query = 'redirect=no';
1706 $query .= "&$query";
1708 $query = $extraQuery;
1710 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1714 * Mark this particular edit/page as patrolled
1716 public function markpatrolled() {
1717 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1718 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1720 # If we haven't been given an rc_id value, we can't do anything
1721 $rcid = (int) $wgRequest->getVal('rcid');
1722 $rc = RecentChange
::newFromId($rcid);
1723 if( is_null($rc) ) {
1724 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1728 #It would be nice to see where the user had actually come from, but for now just guess
1729 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1730 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1732 $dbw = wfGetDB( DB_MASTER
);
1733 $errors = $rc->doMarkPatrolled();
1735 if( in_array(array('rcpatroldisabled'), $errors) ) {
1736 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1740 if( in_array(array('hookaborted'), $errors) ) {
1741 // The hook itself has handled any output
1745 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1746 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1747 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1748 $wgOut->returnToMain( false, $return );
1752 if( !empty($errors) ) {
1753 $wgOut->showPermissionsErrorPage( $errors );
1758 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1759 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1760 $wgOut->returnToMain( false, $return );
1764 * User-interface handler for the "watch" action
1767 public function watch() {
1768 global $wgUser, $wgOut;
1769 if( $wgUser->isAnon() ) {
1770 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1773 if( wfReadOnly() ) {
1774 $wgOut->readOnlyPage();
1777 if( $this->doWatch() ) {
1778 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1779 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1780 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1782 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1786 * Add this page to $wgUser's watchlist
1787 * @return bool true on successful watch operation
1789 public function doWatch() {
1791 if( $wgUser->isAnon() ) {
1794 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1795 $wgUser->addWatch( $this->mTitle
);
1796 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1802 * User interface handler for the "unwatch" action.
1804 public function unwatch() {
1805 global $wgUser, $wgOut;
1806 if( $wgUser->isAnon() ) {
1807 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1810 if( wfReadOnly() ) {
1811 $wgOut->readOnlyPage();
1814 if( $this->doUnwatch() ) {
1815 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1816 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1817 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1819 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1823 * Stop watching a page
1824 * @return bool true on successful unwatch
1826 public function doUnwatch() {
1828 if( $wgUser->isAnon() ) {
1831 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1832 $wgUser->removeWatch( $this->mTitle
);
1833 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1839 * action=protect handler
1841 public function protect() {
1842 $form = new ProtectionForm( $this );
1847 * action=unprotect handler (alias)
1849 public function unprotect() {
1854 * Update the article's restriction field, and leave a log entry.
1856 * @param $limit Array: set of restriction keys
1857 * @param $reason String
1858 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1859 * @param $expiry Array: per restriction type expiration
1860 * @return bool true on success
1862 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1863 global $wgUser, $wgRestrictionTypes, $wgContLang;
1865 $id = $this->mTitle
->getArticleID();
1866 if( $id <= 0 ||
wfReadOnly() ||
!$this->mTitle
->userCan('protect') ) {
1874 // Take this opportunity to purge out expired restrictions
1875 Title
::purgeExpiredRestrictions();
1877 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1878 # we expect a single selection, but the schema allows otherwise.
1880 $updated = Article
::flattenRestrictions( $limit );
1882 foreach( $wgRestrictionTypes as $action ) {
1883 if( isset( $expiry[$action] ) ) {
1884 # Get current restrictions on $action
1885 $aLimits = $this->mTitle
->getRestrictions( $action );
1886 $current[$action] = implode( '', $aLimits );
1887 # Are any actual restrictions being dealt with here?
1888 $aRChanged = count($aLimits) ||
!empty($limit[$action]);
1889 # If something changed, we need to log it. Checking $aRChanged
1890 # assures that "unprotecting" a page that is not protected does
1891 # not log just because the expiry was "changed".
1892 if( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
1898 $current = Article
::flattenRestrictions( $current );
1900 $changed = ($changed ||
$current != $updated );
1901 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1902 $protect = ( $updated != '' );
1904 # If nothing's changed, do nothing
1906 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1908 $dbw = wfGetDB( DB_MASTER
);
1910 # Prepare a null revision to be added to the history
1911 $modified = $current != '' && $protect;
1913 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1915 $comment_type = 'unprotectedarticle';
1917 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1919 # Only restrictions with the 'protect' right can cascade...
1920 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1921 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1922 # The schema allows multiple restrictions
1923 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
1925 $cascade_description = '';
1927 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1931 $comment .= ": $reason";
1933 $editComment = $comment;
1934 $encodedExpiry = array();
1935 $protect_description = '';
1936 foreach( $limit as $action => $restrictions ) {
1937 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
1938 if( $restrictions != '' ) {
1939 $protect_description .= "[$action=$restrictions] (";
1940 if( $encodedExpiry[$action] != 'infinity' ) {
1941 $protect_description .= wfMsgForContent( 'protect-expiring',
1942 $wgContLang->timeanddate( $expiry[$action], false, false ) );
1944 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1946 $protect_description .= ') ';
1949 $protect_description = trim($protect_description);
1951 if( $protect_description && $protect )
1952 $editComment .= " ($protect_description)";
1954 $editComment .= "$cascade_description";
1955 # Update restrictions table
1956 foreach( $limit as $action => $restrictions ) {
1957 if($restrictions != '' ) {
1958 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1959 array( 'pr_page' => $id,
1960 'pr_type' => $action,
1961 'pr_level' => $restrictions,
1962 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
1963 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
1965 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1966 'pr_type' => $action ), __METHOD__
);
1970 # Insert a null revision
1971 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1972 $nullRevId = $nullRevision->insertOn( $dbw );
1974 $latest = $this->getLatest();
1975 # Update page record
1976 $dbw->update( 'page',
1978 'page_touched' => $dbw->timestamp(),
1979 'page_restrictions' => '',
1980 'page_latest' => $nullRevId
1981 ), array( /* WHERE */
1983 ), 'Article::protect'
1986 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
1987 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1989 # Update the protection log
1990 $log = new LogPage( 'protect' );
1992 $params = array($protect_description,$cascade ?
'cascade' : '');
1993 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
1995 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1999 } # End "changed" check
2005 * Take an array of page restrictions and flatten it to a string
2006 * suitable for insertion into the page_restrictions field.
2007 * @param $limit Array
2010 protected static function flattenRestrictions( $limit ) {
2011 if( !is_array( $limit ) ) {
2012 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2016 foreach( $limit as $action => $restrictions ) {
2017 if( $restrictions != '' ) {
2018 $bits[] = "$action=$restrictions";
2021 return implode( ':', $bits );
2025 * Auto-generates a deletion reason
2026 * @param &$hasHistory Boolean: whether the page has a history
2028 public function generateReason( &$hasHistory ) {
2030 $dbw = wfGetDB( DB_MASTER
);
2031 // Get the last revision
2032 $rev = Revision
::newFromTitle( $this->mTitle
);
2033 if( is_null( $rev ) )
2036 // Get the article's contents
2037 $contents = $rev->getText();
2039 // If the page is blank, use the text from the previous revision,
2040 // which can only be blank if there's a move/import/protect dummy revision involved
2041 if( $contents == '' ) {
2042 $prev = $rev->getPrevious();
2044 $contents = $prev->getText();
2049 // Find out if there was only one contributor
2050 // Only scan the last 20 revisions
2052 $res = $dbw->select( 'revision', 'rev_user_text',
2053 array( 'rev_page' => $this->getID() ), __METHOD__
,
2054 array( 'LIMIT' => $limit )
2056 if( $res === false )
2057 // This page has no revisions, which is very weird
2059 if( $res->numRows() > 1 )
2062 $hasHistory = false;
2063 $row = $dbw->fetchObject( $res );
2064 $onlyAuthor = $row->rev_user_text
;
2065 // Try to find a second contributor
2066 foreach( $res as $row ) {
2067 if( $row->rev_user_text
!= $onlyAuthor ) {
2068 $onlyAuthor = false;
2072 $dbw->freeResult( $res );
2074 // Generate the summary with a '$1' placeholder
2076 // The current revision is blank and the one before is also
2077 // blank. It's just not our lucky day
2078 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2081 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2083 $reason = wfMsgForContent( 'excontent', '$1' );
2086 if( $reason == '-' ) {
2087 // Allow these UI messages to be blanked out cleanly
2091 // Replace newlines with spaces to prevent uglyness
2092 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2093 // Calculate the maximum amount of chars to get
2094 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2095 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2096 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2097 // Remove possible unfinished links
2098 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2099 // Now replace the '$1' placeholder
2100 $reason = str_replace( '$1', $contents, $reason );
2106 * UI entry point for page deletion
2108 public function delete() {
2109 global $wgUser, $wgOut, $wgRequest;
2111 $confirm = $wgRequest->wasPosted() &&
2112 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2114 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2115 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2117 $reason = $this->DeleteReasonList
;
2119 if( $reason != 'other' && $this->DeleteReason
!= '' ) {
2120 // Entry from drop down menu + additional comment
2121 $reason .= ': ' . $this->DeleteReason
;
2122 } elseif( $reason == 'other' ) {
2123 $reason = $this->DeleteReason
;
2125 # Flag to hide all contents of the archived revisions
2126 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2128 # This code desperately needs to be totally rewritten
2130 # Read-only check...
2131 if( wfReadOnly() ) {
2132 $wgOut->readOnlyPage();
2137 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2139 if( count( $permission_errors ) > 0 ) {
2140 $wgOut->showPermissionsErrorPage( $permission_errors );
2144 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2146 # Better double-check that it hasn't been deleted yet!
2147 $dbw = wfGetDB( DB_MASTER
);
2148 $conds = $this->mTitle
->pageCond();
2149 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2150 if( $latest === false ) {
2151 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2152 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2153 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2157 # Hack for big sites
2158 $bigHistory = $this->isBigDeletion();
2159 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2160 global $wgLang, $wgDeleteRevisionsLimit;
2161 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2162 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2167 $this->doDelete( $reason, $suppress );
2168 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2170 } elseif( $this->mTitle
->userIsWatching() ) {
2176 // Generate deletion reason
2177 $hasHistory = false;
2178 if( !$reason ) $reason = $this->generateReason($hasHistory);
2180 // If the page has a history, insert a warning
2181 if( $hasHistory && !$confirm ) {
2182 $skin = $wgUser->getSkin();
2183 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2185 global $wgLang, $wgDeleteRevisionsLimit;
2186 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2187 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2191 return $this->confirmDelete( $reason );
2195 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2197 public function isBigDeletion() {
2198 global $wgDeleteRevisionsLimit;
2199 if( $wgDeleteRevisionsLimit ) {
2200 $revCount = $this->estimateRevisionCount();
2201 return $revCount > $wgDeleteRevisionsLimit;
2207 * @return int approximate revision count
2209 public function estimateRevisionCount() {
2210 $dbr = wfGetDB( DB_SLAVE
);
2211 // For an exact count...
2212 //return $dbr->selectField( 'revision', 'COUNT(*)',
2213 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2214 return $dbr->estimateRowCount( 'revision', '*',
2215 array( 'rev_page' => $this->getId() ), __METHOD__
);
2219 * Get the last N authors
2220 * @param $num Integer: number of revisions to get
2221 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2222 * @return array Array of authors, duplicates not removed
2224 public function getLastNAuthors( $num, $revLatest = 0 ) {
2225 wfProfileIn( __METHOD__
);
2226 // First try the slave
2227 // If that doesn't have the latest revision, try the master
2229 $db = wfGetDB( DB_SLAVE
);
2231 $res = $db->select( array( 'page', 'revision' ),
2232 array( 'rev_id', 'rev_user_text' ),
2234 'page_namespace' => $this->mTitle
->getNamespace(),
2235 'page_title' => $this->mTitle
->getDBkey(),
2236 'rev_page = page_id'
2237 ), __METHOD__
, $this->getSelectOptions( array(
2238 'ORDER BY' => 'rev_timestamp DESC',
2243 wfProfileOut( __METHOD__
);
2246 $row = $db->fetchObject( $res );
2247 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2248 $db = wfGetDB( DB_MASTER
);
2253 } while ( $continue );
2255 $authors = array( $row->rev_user_text
);
2256 while ( $row = $db->fetchObject( $res ) ) {
2257 $authors[] = $row->rev_user_text
;
2259 wfProfileOut( __METHOD__
);
2264 * Output deletion confirmation dialog
2265 * @param $reason String: prefilled reason
2267 public function confirmDelete( $reason ) {
2268 global $wgOut, $wgUser;
2270 wfDebug( "Article::confirmDelete\n" );
2272 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2273 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2274 $wgOut->addWikiMsg( 'confirmdeletetext' );
2276 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2277 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2279 <td class='mw-input'>" .
2280 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2281 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2287 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2289 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2290 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2291 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2292 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2293 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2294 "<tr id=\"wpDeleteReasonListRow\">
2295 <td class='mw-label'>" .
2296 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2298 <td class='mw-input'>" .
2299 Xml
::listDropDown( 'wpDeleteReasonList',
2300 wfMsgForContent( 'deletereason-dropdown' ),
2301 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2304 <tr id=\"wpDeleteReasonRow\">
2305 <td class='mw-label'>" .
2306 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2308 <td class='mw-input'>" .
2309 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2310 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2315 <td class='mw-input'>" .
2316 Xml
::checkLabel( wfMsg( 'watchthis' ),
2317 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2323 <td class='mw-submit'>" .
2324 Xml
::submitButton( wfMsg( 'deletepage' ),
2325 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2328 Xml
::closeElement( 'table' ) .
2329 Xml
::closeElement( 'fieldset' ) .
2330 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2331 Xml
::closeElement( 'form' );
2333 if( $wgUser->isAllowed( 'editinterface' ) ) {
2334 $skin = $wgUser->getSkin();
2335 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2336 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2339 $wgOut->addHTML( $form );
2340 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2344 * Perform a deletion and output success or failure messages
2346 public function doDelete( $reason, $suppress = false ) {
2347 global $wgOut, $wgUser;
2348 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2351 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2352 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2353 $deleted = $this->mTitle
->getPrefixedText();
2355 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2356 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2358 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2360 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2361 $wgOut->returnToMain( false );
2362 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2364 if( $error == '' ) {
2365 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2366 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2367 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2369 $wgOut->showFatalError( $error );
2376 * Back-end article deletion
2377 * Deletes the article with database consistency, writes logs, purges caches
2380 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2381 global $wgUseSquid, $wgDeferredUpdateList;
2382 global $wgUseTrackbacks;
2384 wfDebug( __METHOD__
."\n" );
2386 $dbw = wfGetDB( DB_MASTER
);
2387 $ns = $this->mTitle
->getNamespace();
2388 $t = $this->mTitle
->getDBkey();
2389 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2391 if( $t == '' ||
$id == 0 ) {
2395 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2396 array_push( $wgDeferredUpdateList, $u );
2398 // Bitfields to further suppress the content
2401 // This should be 15...
2402 $bitfield |
= Revision
::DELETED_TEXT
;
2403 $bitfield |
= Revision
::DELETED_COMMENT
;
2404 $bitfield |
= Revision
::DELETED_USER
;
2405 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2407 $bitfield = 'rev_deleted';
2411 // For now, shunt the revision data into the archive table.
2412 // Text is *not* removed from the text table; bulk storage
2413 // is left intact to avoid breaking block-compression or
2414 // immutable storage schemes.
2416 // For backwards compatibility, note that some older archive
2417 // table entries will have ar_text and ar_flags fields still.
2419 // In the future, we may keep revisions and mark them with
2420 // the rev_deleted field, which is reserved for this purpose.
2421 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2423 'ar_namespace' => 'page_namespace',
2424 'ar_title' => 'page_title',
2425 'ar_comment' => 'rev_comment',
2426 'ar_user' => 'rev_user',
2427 'ar_user_text' => 'rev_user_text',
2428 'ar_timestamp' => 'rev_timestamp',
2429 'ar_minor_edit' => 'rev_minor_edit',
2430 'ar_rev_id' => 'rev_id',
2431 'ar_text_id' => 'rev_text_id',
2432 'ar_text' => '\'\'', // Be explicit to appease
2433 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2434 'ar_len' => 'rev_len',
2435 'ar_page_id' => 'page_id',
2436 'ar_deleted' => $bitfield
2439 'page_id = rev_page'
2443 # Delete restrictions for it
2444 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2446 # Now that it's safely backed up, delete it
2447 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2448 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2454 # If using cascading deletes, we can skip some explicit deletes
2455 if( !$dbw->cascadingDeletes() ) {
2456 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2458 if($wgUseTrackbacks)
2459 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2461 # Delete outgoing links
2462 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2463 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2464 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2465 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2466 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2467 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2468 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2471 # If using cleanup triggers, we can skip some manual deletes
2472 if( !$dbw->cleanupTriggers() ) {
2473 # Clean up recentchanges entries...
2474 $dbw->delete( 'recentchanges',
2475 array( 'rc_type != '.RC_LOG
,
2476 'rc_namespace' => $this->mTitle
->getNamespace(),
2477 'rc_title' => $this->mTitle
->getDBKey() ),
2479 $dbw->delete( 'recentchanges',
2480 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2485 Article
::onArticleDelete( $this->mTitle
);
2487 # Fix category table counts
2489 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2490 foreach( $res as $row ) {
2491 $cats []= $row->cl_to
;
2493 $this->updateCategoryCounts( array(), $cats );
2495 # Clear the cached article id so the interface doesn't act like we exist
2496 $this->mTitle
->resetArticleID( 0 );
2497 $this->mTitle
->mArticleID
= 0;
2499 # Log the deletion, if the page was suppressed, log it at Oversight instead
2500 $logtype = $suppress ?
'suppress' : 'delete';
2501 $log = new LogPage( $logtype );
2503 # Make sure logging got through
2504 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2512 * Roll back the most recent consecutive set of edits to a page
2513 * from the same user; fails if there are no eligible edits to
2514 * roll back to, e.g. user is the sole contributor. This function
2515 * performs permissions checks on $wgUser, then calls commitRollback()
2516 * to do the dirty work
2518 * @param $fromP String: Name of the user whose edits to rollback.
2519 * @param $summary String: Custom summary. Set to default summary if empty.
2520 * @param $token String: Rollback token.
2521 * @param $bot Boolean: If true, mark all reverted edits as bot.
2523 * @param $resultDetails Array: contains result-specific array of additional values
2524 * 'alreadyrolled' : 'current' (rev)
2525 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2527 * @return array of errors, each error formatted as
2528 * array(messagekey, param1, param2, ...).
2529 * On success, the array is empty. This array can also be passed to
2530 * OutputPage::showPermissionsErrorPage().
2532 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2534 $resultDetails = null;
2537 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2538 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2539 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2541 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2542 $errors[] = array( 'sessionfailure' );
2544 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2545 $errors[] = array( 'actionthrottledtext' );
2547 # If there were errors, bail out now
2548 if( !empty( $errors ) )
2551 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2555 * Backend implementation of doRollback(), please refer there for parameter
2556 * and return value documentation
2558 * NOTE: This function does NOT check ANY permissions, it just commits the
2559 * rollback to the DB Therefore, you should only call this function direct-
2560 * ly if you want to use custom permissions checks. If you don't, use
2561 * doRollback() instead.
2563 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2564 global $wgUseRCPatrol, $wgUser, $wgLang;
2565 $dbw = wfGetDB( DB_MASTER
);
2567 if( wfReadOnly() ) {
2568 return array( array( 'readonlytext' ) );
2571 # Get the last editor
2572 $current = Revision
::newFromTitle( $this->mTitle
);
2573 if( is_null( $current ) ) {
2574 # Something wrong... no page?
2575 return array(array('notanarticle'));
2578 $from = str_replace( '_', ' ', $fromP );
2579 if( $from != $current->getUserText() ) {
2580 $resultDetails = array( 'current' => $current );
2581 return array(array('alreadyrolled',
2582 htmlspecialchars($this->mTitle
->getPrefixedText()),
2583 htmlspecialchars($fromP),
2584 htmlspecialchars($current->getUserText())
2588 # Get the last edit not by this guy
2589 $user = intval( $current->getUser() );
2590 $user_text = $dbw->addQuotes( $current->getUserText() );
2591 $s = $dbw->selectRow( 'revision',
2592 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2593 array( 'rev_page' => $current->getPage(),
2594 "rev_user != {$user} OR rev_user_text != {$user_text}"
2596 array( 'USE INDEX' => 'page_timestamp',
2597 'ORDER BY' => 'rev_timestamp DESC' )
2599 if( $s === false ) {
2600 # No one else ever edited this page
2601 return array(array('cantrollback'));
2602 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2603 # Only admins can see this text
2604 return array(array('notvisiblerev'));
2608 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2609 # Mark all reverted edits as bot
2612 if( $wgUseRCPatrol ) {
2613 # Mark all reverted edits as patrolled
2614 $set['rc_patrolled'] = 1;
2618 $dbw->update( 'recentchanges', $set,
2620 'rc_cur_id' => $current->getPage(),
2621 'rc_user_text' => $current->getUserText(),
2622 "rc_timestamp > '{$s->rev_timestamp}'",
2627 # Generate the edit summary if necessary
2628 $target = Revision
::newFromId( $s->rev_id
);
2629 if( empty( $summary ) ){
2630 $summary = wfMsgForContent( 'revertpage' );
2633 # Allow the custom summary to use the same args as the default message
2635 $target->getUserText(), $from, $s->rev_id
,
2636 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2637 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2639 $summary = wfMsgReplaceArgs( $summary, $args );
2642 $flags = EDIT_UPDATE
;
2644 if( $wgUser->isAllowed('minoredit') )
2645 $flags |
= EDIT_MINOR
;
2647 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2648 $flags |
= EDIT_FORCE_BOT
;
2649 # Actually store the edit
2650 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2651 if( !empty( $status->value
['revision'] ) ) {
2652 $revId = $status->value
['revision']->getId();
2657 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2659 $resultDetails = array(
2660 'summary' => $summary,
2661 'current' => $current,
2662 'target' => $target,
2669 * User interface for rollback operations
2671 public function rollback() {
2672 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2675 $result = $this->doRollback(
2676 $wgRequest->getVal( 'from' ),
2677 $wgRequest->getText( 'summary' ),
2678 $wgRequest->getVal( 'token' ),
2679 $wgRequest->getBool( 'bot' ),
2683 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2684 $wgOut->rateLimited();
2687 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2688 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2689 $errArray = $result[0];
2690 $errMsg = array_shift( $errArray );
2691 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2692 if( isset( $details['current'] ) ){
2693 $current = $details['current'];
2694 if( $current->getComment() != '' ) {
2695 $wgOut->addWikiMsgArray( 'editcomment', array(
2696 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2701 # Display permissions errors before read-only message -- there's no
2702 # point in misleading the user into thinking the inability to rollback
2703 # is only temporary.
2704 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2705 # array_diff is completely broken for arrays of arrays, sigh. Re-
2706 # move any 'readonlytext' error manually.
2708 foreach( $result as $error ) {
2709 if( $error != array( 'readonlytext' ) ) {
2713 $wgOut->showPermissionsErrorPage( $out );
2716 if( $result == array( array( 'readonlytext' ) ) ) {
2717 $wgOut->readOnlyPage();
2721 $current = $details['current'];
2722 $target = $details['target'];
2723 $newId = $details['newid'];
2724 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2725 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2726 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2727 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2728 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2729 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2730 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2731 $wgOut->returnToMain( false, $this->mTitle
);
2733 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2734 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2735 $de->showDiff( '', '' );
2741 * Do standard deferred updates after page view
2743 public function viewUpdates() {
2744 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2745 # Don't update page view counters on views from bot users (bug 14044)
2746 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2747 Article
::incViewCount( $this->getID() );
2748 $u = new SiteStatsUpdate( 1, 0, 0 );
2749 array_push( $wgDeferredUpdateList, $u );
2751 # Update newtalk / watchlist notification status
2752 $wgUser->clearNotification( $this->mTitle
);
2756 * Prepare text which is about to be saved.
2757 * Returns a stdclass with source, pst and output members
2759 public function prepareTextForEdit( $text, $revid=null ) {
2760 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2762 return $this->mPreparedEdit
;
2765 $edit = (object)array();
2766 $edit->revid
= $revid;
2767 $edit->newText
= $text;
2768 $edit->pst
= $this->preSaveTransform( $text );
2769 $options = new ParserOptions
;
2770 $options->setTidy( true );
2771 $options->enableLimitReport();
2772 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2773 $edit->oldText
= $this->getContent();
2774 $this->mPreparedEdit
= $edit;
2779 * Do standard deferred updates after page edit.
2780 * Update links tables, site stats, search index and message cache.
2781 * Purges pages that include this page if the text was changed here.
2782 * Every 100th edit, prune the recent changes table.
2785 * @param $text New text of the article
2786 * @param $summary Edit summary
2787 * @param $minoredit Minor edit
2788 * @param $timestamp_of_pagechange Timestamp associated with the page change
2789 * @param $newid rev_id value of the new revision
2790 * @param $changed Whether or not the content actually changed
2792 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2793 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2795 wfProfileIn( __METHOD__
);
2798 # Be careful not to double-PST: $text is usually already PST-ed once
2799 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2800 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2801 $editInfo = $this->prepareTextForEdit( $text, $newid );
2803 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2804 $editInfo = $this->mPreparedEdit
;
2807 # Save it to the parser cache
2808 if( $wgEnableParserCache ) {
2809 $parserCache = ParserCache
::singleton();
2810 $parserCache->save( $editInfo->output
, $this, $wgUser );
2813 # Update the links tables
2814 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
, false );
2815 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2818 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2820 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2821 if( 0 == mt_rand( 0, 99 ) ) {
2822 // Flush old entries from the `recentchanges` table; we do this on
2823 // random requests so as to avoid an increase in writes for no good reason
2825 $dbw = wfGetDB( DB_MASTER
);
2826 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2827 $recentchanges = $dbw->tableName( 'recentchanges' );
2828 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2829 $dbw->query( $sql );
2833 $id = $this->getID();
2834 $title = $this->mTitle
->getPrefixedDBkey();
2835 $shortTitle = $this->mTitle
->getDBkey();
2838 wfProfileOut( __METHOD__
);
2842 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2843 array_push( $wgDeferredUpdateList, $u );
2844 $u = new SearchUpdate( $id, $title, $text );
2845 array_push( $wgDeferredUpdateList, $u );
2847 # If this is another user's talk page, update newtalk
2848 # Don't do this if $changed = false otherwise some idiot can null-edit a
2849 # load of user talk pages and piss people off, nor if it's a minor edit
2850 # by a properly-flagged bot.
2851 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2852 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2853 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2854 $other = User
::newFromName( $shortTitle, false );
2856 wfDebug( __METHOD__
.": invalid username\n" );
2857 } elseif( User
::isIP( $shortTitle ) ) {
2858 // An anonymous user
2859 $other->setNewtalk( true );
2860 } elseif( $other->isLoggedIn() ) {
2861 $other->setNewtalk( true );
2863 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2868 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2869 $wgMessageCache->replace( $shortTitle, $text );
2872 wfProfileOut( __METHOD__
);
2876 * Perform article updates on a special page creation.
2878 * @param $rev Revision object
2880 * @todo This is a shitty interface function. Kill it and replace the
2881 * other shitty functions like editUpdates and such so it's not needed
2884 public function createUpdates( $rev ) {
2885 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2886 $this->mTotalAdjustment
= 1;
2887 $this->editUpdates( $rev->getText(), $rev->getComment(),
2888 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2892 * Generate the navigation links when browsing through an article revisions
2893 * It shows the information as:
2894 * Revision as of \<date\>; view current revision
2895 * \<- Previous version | Next Version -\>
2897 * @param $oldid String: revision ID of this article revision
2899 public function setOldSubtitle( $oldid = 0 ) {
2900 global $wgLang, $wgOut, $wgUser;
2902 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
2906 $revision = Revision
::newFromId( $oldid );
2908 $current = ( $oldid == $this->mLatest
);
2909 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2910 $sk = $wgUser->getSkin();
2912 ?
wfMsgHtml( 'currentrevisionlink' )
2913 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'currentrevisionlink' ) );
2915 ?
wfMsgHtml( 'diff' )
2916 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
2917 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2919 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2920 : wfMsgHtml( 'previousrevision' );
2922 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
2923 : wfMsgHtml( 'diff' );
2924 $nextlink = $current
2925 ?
wfMsgHtml( 'nextrevision' )
2926 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2927 $nextdiff = $current
2928 ?
wfMsgHtml( 'diff' )
2929 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
2932 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2933 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2934 if( $revision->isCurrent() ) {
2935 // We don't handle top deleted edits too well
2936 $cdel = wfMsgHtml( 'rev-delundel' );
2937 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2938 // If revision was hidden from sysops
2939 $cdel = wfMsgHtml( 'rev-delundel' );
2941 $cdel = $sk->makeKnownLinkObj( $revdel,
2942 wfMsgHtml('rev-delundel'),
2943 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2944 '&oldid=' . urlencode( $oldid ) );
2945 // Bolden oversighted content
2946 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2947 $cdel = "<strong>$cdel</strong>";
2949 $cdel = "(<small>$cdel</small>) ";
2951 # Show user links if allowed to see them. Normally they
2952 # are hidden regardless, but since we can already see the text here...
2953 $userlinks = $sk->revUserTools( $revision, false );
2955 $m = wfMsg( 'revision-info-current' );
2956 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2957 ?
'revision-info-current'
2960 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" .
2962 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgHtml( 'revision-nav', $prevdiff,
2963 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2964 $wgOut->setSubtitle( $r );
2968 * This function is called right before saving the wikitext,
2969 * so we can do things like signatures and links-in-context.
2971 * @param $text String
2973 public function preSaveTransform( $text ) {
2974 global $wgParser, $wgUser;
2975 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2978 /* Caching functions */
2981 * checkLastModified returns true if it has taken care of all
2982 * output to the client that is necessary for this request.
2983 * (that is, it has sent a cached version of the page)
2985 protected function tryFileCache() {
2986 static $called = false;
2988 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2992 if( $this->isFileCacheable() ) {
2993 $cache = new HTMLFileCache( $this->mTitle
);
2994 if( $cache->isFileCacheGood( $this->mTouched
) ) {
2995 wfDebug( "Article::tryFileCache(): about to load file\n" );
2996 $cache->loadFromFileCache();
2999 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3000 ob_start( array(&$cache, 'saveToFileCache' ) );
3003 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3009 * Check if the page can be cached
3012 public function isFileCacheable() {
3014 if( HTMLFileCache
::useFileCache() ) {
3015 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3016 // Extension may have reason to disable file caching on some pages.
3018 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3025 * Loads page_touched and returns a value indicating if it should be used
3028 public function checkTouched() {
3029 if( !$this->mDataLoaded
) {
3030 $this->loadPageData();
3032 return !$this->mIsRedirect
;
3036 * Get the page_touched field
3038 public function getTouched() {
3039 # Ensure that page data has been loaded
3040 if( !$this->mDataLoaded
) {
3041 $this->loadPageData();
3043 return $this->mTouched
;
3047 * Get the page_latest field
3049 public function getLatest() {
3050 if( !$this->mDataLoaded
) {
3051 $this->loadPageData();
3053 return $this->mLatest
;
3057 * Edit an article without doing all that other stuff
3058 * The article must already exist; link tables etc
3059 * are not updated, caches are not flushed.
3061 * @param $text String: text submitted
3062 * @param $comment String: comment submitted
3063 * @param $minor Boolean: whereas it's a minor modification
3065 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3066 wfProfileIn( __METHOD__
);
3068 $dbw = wfGetDB( DB_MASTER
);
3069 $revision = new Revision( array(
3070 'page' => $this->getId(),
3072 'comment' => $comment,
3073 'minor_edit' => $minor ?
1 : 0,
3075 $revision->insertOn( $dbw );
3076 $this->updateRevisionOn( $dbw, $revision );
3078 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3080 wfProfileOut( __METHOD__
);
3084 * Used to increment the view counter
3086 * @param $id Integer: article id
3088 public static function incViewCount( $id ) {
3089 $id = intval( $id );
3090 global $wgHitcounterUpdateFreq, $wgDBtype;
3092 $dbw = wfGetDB( DB_MASTER
);
3093 $pageTable = $dbw->tableName( 'page' );
3094 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3095 $acchitsTable = $dbw->tableName( 'acchits' );
3097 if( $wgHitcounterUpdateFreq <= 1 ) {
3098 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3102 # Not important enough to warrant an error page in case of failure
3103 $oldignore = $dbw->ignoreErrors( true );
3105 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3107 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3108 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3109 # Most of the time (or on SQL errors), skip row count check
3110 $dbw->ignoreErrors( $oldignore );
3114 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3115 $row = $dbw->fetchObject( $res );
3116 $rown = intval( $row->n
);
3117 if( $rown >= $wgHitcounterUpdateFreq ){
3118 wfProfileIn( 'Article::incViewCount-collect' );
3119 $old_user_abort = ignore_user_abort( true );
3121 if($wgDBtype == 'mysql')
3122 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3123 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3124 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3125 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3127 $dbw->query("DELETE FROM $hitcounterTable");
3128 if($wgDBtype == 'mysql') {
3129 $dbw->query('UNLOCK TABLES');
3130 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3131 'WHERE page_id = hc_id');
3134 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3135 "FROM $acchitsTable WHERE page_id = hc_id");
3137 $dbw->query("DROP TABLE $acchitsTable");
3139 ignore_user_abort( $old_user_abort );
3140 wfProfileOut( 'Article::incViewCount-collect' );
3142 $dbw->ignoreErrors( $oldignore );
3146 * The onArticle*() functions are supposed to be a kind of hooks
3147 * which should be called whenever any of the specified actions
3150 * This is a good place to put code to clear caches, for instance.
3152 * This is called on page move and undelete, as well as edit
3154 * @param $title a title object
3157 public static function onArticleCreate( $title ) {
3158 # Update existence markers on article/talk tabs...
3159 if( $title->isTalkPage() ) {
3160 $other = $title->getSubjectPage();
3162 $other = $title->getTalkPage();
3164 $other->invalidateCache();
3165 $other->purgeSquid();
3167 $title->touchLinks();
3168 $title->purgeSquid();
3169 $title->deleteTitleProtection();
3172 public static function onArticleDelete( $title ) {
3173 global $wgMessageCache;
3174 # Update existence markers on article/talk tabs...
3175 if( $title->isTalkPage() ) {
3176 $other = $title->getSubjectPage();
3178 $other = $title->getTalkPage();
3180 $other->invalidateCache();
3181 $other->purgeSquid();
3183 $title->touchLinks();
3184 $title->purgeSquid();
3187 HTMLFileCache
::clearFileCache( $title );
3190 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3191 $wgMessageCache->replace( $title->getDBkey(), false );
3194 if( $title->getNamespace() == NS_FILE
) {
3195 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3196 $update->doUpdate();
3199 if( $title->getNamespace() == NS_USER_TALK
) {
3200 $user = User
::newFromName( $title->getText(), false );
3201 $user->setNewtalk( false );
3206 * Purge caches on page update etc
3208 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3209 global $wgDeferredUpdateList;
3211 // Invalidate caches of articles which include this page
3212 if( $transclusions !== 'skiptransclusions' )
3213 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3215 // Invalidate the caches of all pages which redirect here
3216 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3218 # Purge squid for this page only
3219 $title->purgeSquid();
3221 # Clear file cache for this page only
3222 HTMLFileCache
::clearFileCache( $title );
3228 * Overriden by ImagePage class, only present here to avoid a fatal error
3229 * Called for ?action=revert
3231 public function revert() {
3233 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3237 * Info about this page
3238 * Called for ?action=info when $wgAllowPageInfo is on.
3240 public function info() {
3241 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3243 if( !$wgAllowPageInfo ) {
3244 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3248 $page = $this->mTitle
->getSubjectPage();
3250 $wgOut->setPagetitle( $page->getPrefixedText() );
3251 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3252 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3254 if( !$this->mTitle
->exists() ) {
3255 $wgOut->addHTML( '<div class="noarticletext">' );
3256 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3257 // This doesn't quite make sense; the user is asking for
3258 // information about the _page_, not the message... -- RC
3259 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3261 $msg = $wgUser->isLoggedIn()
3263 : 'noarticletextanon';
3264 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3266 $wgOut->addHTML( '</div>' );
3268 $dbr = wfGetDB( DB_SLAVE
);
3270 'wl_title' => $page->getDBkey(),
3271 'wl_namespace' => $page->getNamespace() );
3272 $numwatchers = $dbr->selectField(
3277 $this->getSelectOptions() );
3279 $pageInfo = $this->pageCountInfo( $page );
3280 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3282 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3283 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3285 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3287 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3289 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3291 $wgOut->addHTML( '</ul>' );
3296 * Return the total number of edits and number of unique editors
3297 * on a given page. If page does not exist, returns false.
3299 * @param $title Title object
3302 protected function pageCountInfo( $title ) {
3303 $id = $title->getArticleId();
3307 $dbr = wfGetDB( DB_SLAVE
);
3308 $rev_clause = array( 'rev_page' => $id );
3309 $edits = $dbr->selectField(
3314 $this->getSelectOptions()
3316 $authors = $dbr->selectField(
3318 'COUNT(DISTINCT rev_user_text)',
3321 $this->getSelectOptions()
3323 return array( 'edits' => $edits, 'authors' => $authors );
3327 * Return a list of templates used by this article.
3328 * Uses the templatelinks table
3330 * @return Array of Title objects
3332 public function getUsedTemplates() {
3334 $id = $this->mTitle
->getArticleID();
3338 $dbr = wfGetDB( DB_SLAVE
);
3339 $res = $dbr->select( array( 'templatelinks' ),
3340 array( 'tl_namespace', 'tl_title' ),
3341 array( 'tl_from' => $id ),
3343 if( $res !== false ) {
3344 foreach( $res as $row ) {
3345 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3348 $dbr->freeResult( $res );
3353 * Returns a list of hidden categories this page is a member of.
3354 * Uses the page_props and categorylinks tables.
3356 * @return Array of Title objects
3358 public function getHiddenCategories() {
3360 $id = $this->mTitle
->getArticleID();
3364 $dbr = wfGetDB( DB_SLAVE
);
3365 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3367 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3368 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3370 if( $res !== false ) {
3371 foreach( $res as $row ) {
3372 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3375 $dbr->freeResult( $res );
3380 * Return an applicable autosummary if one exists for the given edit.
3381 * @param $oldtext String: the previous text of the page.
3382 * @param $newtext String: The submitted text of the page.
3383 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3384 * @return string An appropriate autosummary, or an empty string.
3386 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3387 # Decide what kind of autosummary is needed.
3389 # Redirect autosummaries
3390 $ot = Title
::newFromRedirect( $oldtext );
3391 $rt = Title
::newFromRedirect( $newtext );
3392 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3393 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3396 # New page autosummaries
3397 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3398 # If they're making a new article, give its text, truncated, in the summary.
3400 $truncatedtext = $wgContLang->truncate(
3401 str_replace("\n", ' ', $newtext),
3402 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3404 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3407 # Blanking autosummaries
3408 if( $oldtext != '' && $newtext == '' ) {
3409 return wfMsgForContent( 'autosumm-blank' );
3410 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3411 # Removing more than 90% of the article
3413 $truncatedtext = $wgContLang->truncate(
3415 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3418 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3421 # If we reach this point, there's no applicable autosummary for our case, so our
3422 # autosummary is empty.
3427 * Add the primary page-view wikitext to the output buffer
3428 * Saves the text into the parser cache if possible.
3429 * Updates templatelinks if it is out of date.
3431 * @param $text String
3432 * @param $cache Boolean
3434 public function outputWikiText( $text, $cache = true ) {
3435 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3437 $popts = $wgOut->parserOptions();
3438 $popts->setTidy(true);
3439 $popts->enableLimitReport();
3440 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3441 $popts, true, true, $this->getRevIdFetched() );
3442 $popts->setTidy(false);
3443 $popts->enableLimitReport( false );
3444 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3445 $parserCache = ParserCache
::singleton();
3446 $parserCache->save( $parserOutput, $this, $wgUser );
3448 // Make sure file cache is not used on uncacheable content.
3449 // Output that has magic words in it can still use the parser cache
3450 // (if enabled), though it will generally expire sooner.
3451 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3452 $wgUseFileCache = false;
3455 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3456 // templatelinks table may have become out of sync,
3457 // especially if using variable-based transclusions.
3458 // For paranoia, check if things have changed and if
3459 // so apply updates to the database. This will ensure
3460 // that cascaded protections apply as soon as the changes
3463 # Get templates from templatelinks
3464 $id = $this->mTitle
->getArticleID();
3466 $tlTemplates = array();
3468 $dbr = wfGetDB( DB_SLAVE
);
3469 $res = $dbr->select( array( 'templatelinks' ),
3470 array( 'tl_namespace', 'tl_title' ),
3471 array( 'tl_from' => $id ),
3476 if( $res !== false ) {
3477 foreach( $res as $row ) {
3478 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3482 # Get templates from parser output.
3483 $poTemplates_allns = $parserOutput->getTemplates();
3485 $poTemplates = array ();
3486 foreach ( $poTemplates_allns as $ns_templates ) {
3487 $poTemplates = array_merge( $poTemplates, $ns_templates );
3491 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3493 if( count( $templates_diff ) > 0 ) {
3494 # Whee, link updates time.
3495 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3500 $wgOut->addParserOutput( $parserOutput );
3504 * Update all the appropriate counts in the category table, given that
3505 * we've added the categories $added and deleted the categories $deleted.
3507 * @param $added array The names of categories that were added
3508 * @param $deleted array The names of categories that were deleted
3511 public function updateCategoryCounts( $added, $deleted ) {
3512 $ns = $this->mTitle
->getNamespace();
3513 $dbw = wfGetDB( DB_MASTER
);
3515 # First make sure the rows exist. If one of the "deleted" ones didn't
3516 # exist, we might legitimately not create it, but it's simpler to just
3517 # create it and then give it a negative value, since the value is bogus
3520 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3521 $insertCats = array_merge( $added, $deleted );
3522 if( !$insertCats ) {
3523 # Okay, nothing to do
3526 $insertRows = array();
3527 foreach( $insertCats as $cat ) {
3528 $insertRows[] = array( 'cat_title' => $cat );
3530 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3532 $addFields = array( 'cat_pages = cat_pages + 1' );
3533 $removeFields = array( 'cat_pages = cat_pages - 1' );
3534 if( $ns == NS_CATEGORY
) {
3535 $addFields[] = 'cat_subcats = cat_subcats + 1';
3536 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3537 } elseif( $ns == NS_FILE
) {
3538 $addFields[] = 'cat_files = cat_files + 1';
3539 $removeFields[] = 'cat_files = cat_files - 1';
3546 array( 'cat_title' => $added ),
3554 array( 'cat_title' => $deleted ),