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
::newFromRedirectRecurse( $text ); // recurse through to only get the final target
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 = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
223 wfProfileOut( __METHOD__
);
226 $this->loadContent();
227 wfProfileOut( __METHOD__
);
228 return $this->mContent
;
233 * Get the text of the current revision. No side-effects...
235 * @return Return the text of the current revision
237 public function getRawText() {
238 // Check process cache for current revision
239 if( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
240 return $this->mContent
;
242 $rev = Revision
::newFromTitle( $this->mTitle
);
243 $text = $rev ?
$rev->getRawText() : false;
248 * This function returns the text of a section, specified by a number ($section).
249 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
250 * the first section before any such heading (section 0).
252 * If a section contains subsections, these are also returned.
254 * @param $text String: text to look in
255 * @param $section Integer: section number
256 * @return string text of the requested section
259 public function getSection( $text, $section ) {
261 return $wgParser->getSection( $text, $section );
265 * Get the text that needs to be saved in order to undo all revisions
266 * between $undo and $undoafter. Revisions must belong to the same page,
267 * must exist and must not be deleted
268 * @param $undo Revision
269 * @param $undoafter Revision Must be an earlier revision than $undo
270 * @return mixed string on success, false on failure
272 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
273 $undo_text = $undo->getText();
274 $undoafter_text = $undoafter->getText();
275 $cur_text = $this->getContent();
276 if ( $cur_text == $undo_text ) {
277 # No use doing a merge if it's just a straight revert.
278 return $undoafter_text;
281 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
287 * @return int The oldid of the article that is to be shown, 0 for the
290 public function getOldID() {
291 if( is_null( $this->mOldId
) ) {
292 $this->mOldId
= $this->getOldIDFromRequest();
294 return $this->mOldId
;
298 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
300 * @return int The old id for the request
302 public function getOldIDFromRequest() {
304 $this->mRedirectUrl
= false;
305 $oldid = $wgRequest->getVal( 'oldid' );
306 if( isset( $oldid ) ) {
307 $oldid = intval( $oldid );
308 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
309 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
313 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
315 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
316 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
329 * Load the revision (including text) into this object
331 function loadContent() {
332 if( $this->mContentLoaded
) return;
333 wfProfileIn( __METHOD__
);
335 $oldid = $this->getOldID();
336 # Pre-fill content with error message so that if something
337 # fails we'll have something telling us what we intended.
338 $this->mOldId
= $oldid;
339 $this->fetchContent( $oldid );
340 wfProfileOut( __METHOD__
);
345 * Fetch a page record with the given conditions
346 * @param $dbr Database object
347 * @param $conditions Array
349 protected function pageData( $dbr, $conditions ) {
363 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
364 $row = $dbr->selectRow(
370 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
375 * @param $dbr Database object
376 * @param $title Title object
378 public function pageDataFromTitle( $dbr, $title ) {
379 return $this->pageData( $dbr, array(
380 'page_namespace' => $title->getNamespace(),
381 'page_title' => $title->getDBkey() ) );
385 * @param $dbr Database
388 protected function pageDataFromId( $dbr, $id ) {
389 return $this->pageData( $dbr, array( 'page_id' => $id ) );
393 * Set the general counter, title etc data loaded from
396 * @param $data Database row object or "fromdb"
398 public function loadPageData( $data = 'fromdb' ) {
399 if( $data === 'fromdb' ) {
400 $dbr = wfGetDB( DB_MASTER
);
401 $data = $this->pageDataFromId( $dbr, $this->getId() );
404 $lc = LinkCache
::singleton();
406 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
408 $this->mTitle
->mArticleID
= $data->page_id
;
410 # Old-fashioned restrictions
411 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
413 $this->mCounter
= $data->page_counter
;
414 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
415 $this->mIsRedirect
= $data->page_is_redirect
;
416 $this->mLatest
= $data->page_latest
;
418 if( is_object( $this->mTitle
) ) {
419 $lc->addBadLinkObj( $this->mTitle
);
421 $this->mTitle
->mArticleID
= 0;
424 $this->mDataLoaded
= true;
428 * Get text of an article from database
429 * Does *NOT* follow redirects.
430 * @param $oldid Int: 0 for whatever the latest revision is
433 function fetchContent( $oldid = 0 ) {
434 if( $this->mContentLoaded
) {
435 return $this->mContent
;
438 $dbr = wfGetDB( DB_MASTER
);
440 # Pre-fill content with error message so that if something
441 # fails we'll have something telling us what we intended.
442 $t = $this->mTitle
->getPrefixedText();
443 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
444 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
447 $revision = Revision
::newFromId( $oldid );
448 if( is_null( $revision ) ) {
449 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
452 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
454 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
457 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
458 $this->loadPageData( $data );
460 if( !$this->mDataLoaded
) {
461 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
463 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
466 $this->loadPageData( $data );
468 $revision = Revision
::newFromId( $this->mLatest
);
469 if( is_null( $revision ) ) {
470 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
475 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
476 // We should instead work with the Revision object when we need it...
477 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
479 $this->mUser
= $revision->getUser();
480 $this->mUserText
= $revision->getUserText();
481 $this->mComment
= $revision->getComment();
482 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
484 $this->mRevIdFetched
= $revision->getId();
485 $this->mContentLoaded
= true;
486 $this->mRevision
=& $revision;
488 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
490 return $this->mContent
;
494 * Read/write accessor to select FOR UPDATE
496 * @param $x Mixed: FIXME
498 public function forUpdate( $x = NULL ) {
499 return wfSetVar( $this->mForUpdate
, $x );
503 * Get the database which should be used for reads
506 * @deprecated - just call wfGetDB( DB_MASTER ) instead
509 wfDeprecated( __METHOD__
);
510 return wfGetDB( DB_MASTER
);
514 * Get options for all SELECT statements
516 * @param $options Array: an optional options array which'll be appended to
518 * @return Array: options
520 protected function getSelectOptions( $options = '' ) {
521 if( $this->mForUpdate
) {
522 if( is_array( $options ) ) {
523 $options[] = 'FOR UPDATE';
525 $options = 'FOR UPDATE';
532 * @return int Page ID
534 public function getID() {
535 if( $this->mTitle
) {
536 return $this->mTitle
->getArticleID();
543 * @return bool Whether or not the page exists in the database
545 public function exists() {
546 return $this->getId() > 0;
550 * Check if this page is something we're going to be showing
551 * some sort of sensible content for. If we return false, page
552 * views (plain action=view) will return an HTTP 404 response,
553 * so spiders and robots can know they're following a bad link.
557 public function hasViewableContent() {
558 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
562 * @return int The view count for the page
564 public function getCount() {
565 if( -1 == $this->mCounter
) {
566 $id = $this->getID();
570 $dbr = wfGetDB( DB_SLAVE
);
571 $this->mCounter
= $dbr->selectField( 'page',
573 array( 'page_id' => $id ),
575 $this->getSelectOptions()
579 return $this->mCounter
;
583 * Determine whether a page would be suitable for being counted as an
584 * article in the site_stats table based on the title & its content
586 * @param $text String: text to analyze
589 public function isCountable( $text ) {
590 global $wgUseCommaCount;
592 $token = $wgUseCommaCount ?
',' : '[[';
593 return $this->mTitle
->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
597 * Tests if the article text represents a redirect
599 * @param $text String: FIXME
602 public function isRedirect( $text = false ) {
603 if( $text === false ) {
604 if( $this->mDataLoaded
) {
605 return $this->mIsRedirect
;
607 // Apparently loadPageData was never called
608 $this->loadContent();
609 $titleObj = Title
::newFromRedirectRe( $this->fetchContent() );
611 $titleObj = Title
::newFromRedirect( $text );
613 return $titleObj !== NULL;
617 * Returns true if the currently-referenced revision is the current edit
618 * to this page (and it exists).
621 public function isCurrent() {
622 # If no oldid, this is the current version.
623 if( $this->getOldID() == 0 ) {
626 return $this->exists() && isset($this->mRevision
) && $this->mRevision
->isCurrent();
630 * Loads everything except the text
631 * This isn't necessary for all uses, so it's only done if needed.
633 protected function loadLastEdit() {
634 if( -1 != $this->mUser
)
637 # New or non-existent articles have no user information
638 $id = $this->getID();
639 if( 0 == $id ) return;
641 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
642 if( !is_null( $this->mLastRevision
) ) {
643 $this->mUser
= $this->mLastRevision
->getUser();
644 $this->mUserText
= $this->mLastRevision
->getUserText();
645 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
646 $this->mComment
= $this->mLastRevision
->getComment();
647 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
648 $this->mRevIdFetched
= $this->mLastRevision
->getId();
652 public function getTimestamp() {
653 // Check if the field has been filled by ParserCache::get()
654 if( !$this->mTimestamp
) {
655 $this->loadLastEdit();
657 return wfTimestamp(TS_MW
, $this->mTimestamp
);
660 public function getUser() {
661 $this->loadLastEdit();
665 public function getUserText() {
666 $this->loadLastEdit();
667 return $this->mUserText
;
670 public function getComment() {
671 $this->loadLastEdit();
672 return $this->mComment
;
675 public function getMinorEdit() {
676 $this->loadLastEdit();
677 return $this->mMinorEdit
;
680 /* Use this to fetch the rev ID used on page views */
681 public function getRevIdFetched() {
682 $this->loadLastEdit();
683 return $this->mRevIdFetched
;
687 * @param $limit Integer: default 0.
688 * @param $offset Integer: default 0.
690 public function getContributors($limit = 0, $offset = 0) {
691 # XXX: this is expensive; cache this info somewhere.
694 $dbr = wfGetDB( DB_SLAVE
);
695 $revTable = $dbr->tableName( 'revision' );
696 $userTable = $dbr->tableName( 'user' );
697 $user = $this->getUser();
698 $pageId = $this->getId();
700 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
701 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
702 WHERE rev_page = $pageId
703 AND rev_user != $user
704 GROUP BY rev_user, rev_user_text, user_real_name
705 ORDER BY timestamp DESC";
707 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
708 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
710 $sql .= ' '. $this->getSelectOptions();
712 $res = $dbr->query($sql, __METHOD__
);
714 return new UserArrayFromResult( $res );
718 * This is the default action of the script: just view the page of
721 public function view() {
722 global $wgUser, $wgOut, $wgRequest, $wgContLang;
723 global $wgEnableParserCache, $wgStylePath, $wgParser;
724 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
725 global $wgDefaultRobotPolicy;
727 wfProfileIn( __METHOD__
);
729 # Get variables from query string
730 $oldid = $this->getOldID();
733 if( $oldid === 0 && $this->checkTouched() ) {
736 $parserCache = ParserCache
::singleton();
737 $wgOut->setETag( $parserCache->getETag($this,$wgUser) );
739 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
740 wfProfileOut( __METHOD__
);
742 } else if( $this->tryFileCache() ) {
743 # tell wgOut that output is taken care of
745 $this->viewUpdates();
746 wfProfileOut( __METHOD__
);
751 $ns = $this->mTitle
->getNamespace(); # shortcut
752 $sk = $wgUser->getSkin();
754 # getOldID may want us to redirect somewhere else
755 if( $this->mRedirectUrl
) {
756 $wgOut->redirect( $this->mRedirectUrl
);
757 wfProfileOut( __METHOD__
);
761 $diff = $wgRequest->getVal( 'diff' );
762 $rcid = $wgRequest->getVal( 'rcid' );
763 $rdfrom = $wgRequest->getVal( 'rdfrom' );
764 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
765 $purge = $wgRequest->getVal( 'action' ) == 'purge';
768 $wgOut->setArticleFlag( true );
770 # Discourage indexing of printable versions, but encourage following
771 if( $wgOut->isPrintable() ) {
772 $policy = 'noindex,follow';
773 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
774 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
775 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
776 # Honour customised robot policies for this namespace
777 $policy = $wgNamespaceRobotPolicies[$ns];
779 $policy = $wgDefaultRobotPolicy;
781 $wgOut->setRobotPolicy( $policy );
783 # If we got diff and oldid in the query, we want to see a
784 # diff page instead of the article.
786 if( !is_null( $diff ) ) {
787 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
789 $diff = $wgRequest->getVal( 'diff' );
790 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
791 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
792 // DifferenceEngine directly fetched the revision:
793 $this->mRevIdFetched
= $de->mNewid
;
794 $de->showDiffPage( $diffOnly );
796 // Needed to get the page's current revision
797 $this->loadPageData();
798 if( $diff == 0 ||
$diff == $this->mLatest
) {
799 # Run view updates for current revision only
800 $this->viewUpdates();
802 wfProfileOut( __METHOD__
);
806 if( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
807 # User/User_talk subpages are not modified. (bug 11443)
808 if( !$this->mTitle
->isSubpage() ) {
809 $block = new Block();
810 if( $block->load( $this->mTitle
->getBaseText() ) ) {
811 $wgOut->setRobotpolicy( 'noindex,nofollow' );
816 # Should the parser cache be used?
817 $pcache = $this->useParserCache( $oldid );
818 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
819 if( $wgUser->getOption( 'stubthreshold' ) ) {
820 wfIncrStats( 'pcache_miss_stub' );
823 $wasRedirected = false;
824 if( isset( $this->mRedirectedFrom
) ) {
825 // This is an internally redirected page view.
826 // We'll need a backlink to the source page for navigation.
827 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
828 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
829 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
830 $wgOut->setSubtitle( $s );
832 // Set the fragment if one was specified in the redirect
833 if( strval( $this->mTitle
->getFragment() ) != '' ) {
834 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
835 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
837 $wasRedirected = true;
839 } elseif( !empty( $rdfrom ) ) {
840 // This is an externally redirected view, from some other wiki.
841 // If it was reported from a trusted site, supply a backlink.
842 global $wgRedirectSources;
843 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
844 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
845 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
846 $wgOut->setSubtitle( $s );
847 $wasRedirected = true;
852 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
853 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
854 // Ensure that UI elements requiring revision ID have
855 // the correct version information.
856 $wgOut->setRevisionId( $this->mLatest
);
859 # Fetch content and check for errors
861 # If the article does not exist and was deleted, show the log
862 if( $this->getID() == 0 ) {
863 $this->showDeletionLog();
865 $text = $this->getContent();
866 // For now, check also for ID until getContent actually returns
867 // false for pages that do not exists
868 if( $text === false ||
$this->getID() === 0 ) {
869 # Failed to load, replace text with error message
870 $t = $this->mTitle
->getPrefixedText();
872 $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
873 $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
874 // Always use page content for pages in the MediaWiki namespace
875 // since it contains the default message
876 } elseif ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
) {
877 $text = wfMsgExt( 'noarticletext', 'parsemag' );
882 if( $this->getID() === 0 ) {
883 $wgOut->setRobotPolicy( 'noindex,nofollow' );
884 $text = "<div class='noarticletext'>\n$text\n</div>";
885 if( !$this->hasViewableContent() ) {
886 // If there's no backing content, send a 404 Not Found
887 // for better machine handling of broken links.
893 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
896 # Another whitelist check in case oldid is altering the title
897 if( !$this->mTitle
->userCanRead() ) {
898 $wgOut->loginToUse();
901 wfProfileOut( __METHOD__
);
905 # For ?curid=x urls, disallow indexing
906 if( $wgRequest->getInt('curid') )
907 $wgOut->setRobotPolicy( 'noindex,follow' );
909 # We're looking at an old revision
910 if( !empty( $oldid ) ) {
911 $wgOut->setRobotPolicy( 'noindex,nofollow' );
912 if( is_null( $this->mRevision
) ) {
913 // FIXME: This would be a nice place to load the 'no such page' text.
915 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
916 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
917 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
918 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
919 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
920 wfProfileOut( __METHOD__
);
923 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
924 // and we are allowed to see...
930 $wgOut->setRevisionId( $this->getRevIdFetched() );
932 // Pages containing custom CSS or JavaScript get special treatment
933 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
934 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
935 // Give hooks a chance to customise the output
936 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
937 // Wrap the whole lot in a <pre> and don't parse
939 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
940 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
941 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
942 $wgOut->addHTML( "\n</pre>\n" );
944 } else if( $rt = Title
::newFromRedirectArray( $text ) ) { # get an array of redirect targets
945 # Don't append the subtitle if this was an old revision
946 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
947 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
948 $wgOut->addParserOutputNoText( $parseout );
949 } else if( $pcache ) {
950 # Display content and save to parser cache
951 $this->outputWikiText( $text );
953 # Display content, don't attempt to save to parser cache
954 # Don't show section-edit links on old revisions... this way lies madness.
955 if( !$this->isCurrent() ) {
956 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
958 # Display content and don't save to parser cache
959 # With timing hack -- TS 2006-07-26
961 $this->outputWikiText( $text, false );
966 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
967 $this->mTitle
->getPrefixedDBkey()));
970 if( !$this->isCurrent() ) {
971 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
975 /* title may have been set from the cache */
976 $t = $wgOut->getPageTitle();
978 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
980 # For the main page, overwrite the <title> element with the con-
981 # tents of 'pagetitle-view-mainpage' instead of the default (if
983 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
984 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
985 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
989 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
990 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
991 $wgOut->addWikiMsg('anontalkpagetext');
994 # Only diffs and new page links from RC give rcid params, so if
995 # we are just viewing the page normally with no rcid, try to find it.
996 # This is more convenient for users.
997 if( $this->mTitle
->exists() && $this->mTitle
->userCan('patrol', false) ) {
999 $firstRev = $this->mTitle
->getFirstRevision();
1000 $rcid = $firstRev ?
$firstRev->isUnpatrolled() : 0;
1002 $rc = RecentChange
::newFromId( $rcid );
1003 // Already patrolled?
1004 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
1007 # If we have been passed an &rcid= parameter, we want to give the user a
1008 # chance to mark this new article as patrolled.
1009 if( !empty($rcid) && $this->mTitle
->exists() && $this->mTitle
->userCan('patrol', false) ) {
1011 "<div class='patrollink'>" .
1012 wfMsgHtml( 'markaspatrolledlink',
1013 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
1014 "action=markpatrolled&rcid=$rcid" )
1021 if( $wgUseTrackbacks ) {
1022 $this->addTrackbacks();
1025 $this->viewUpdates();
1026 wfProfileOut( __METHOD__
);
1029 protected function showDeletionLog() {
1030 global $wgUser, $wgOut;
1031 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1032 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
1033 if( $pager->getNumRows() > 0 ) {
1034 $pager->mLimit
= 10;
1035 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1036 $wgOut->addWikiMsg( 'deleted-notice' );
1038 $loglist->beginLogEventsList() .
1040 $loglist->endLogEventsList()
1042 if( $pager->getNumRows() > 10 ) {
1043 $wgOut->addHTML( $wgUser->getSkin()->link(
1044 SpecialPage
::getTitleFor( 'Log' ),
1045 wfMsgHtml( 'deletelog-fulllog' ),
1047 array( 'type' => 'delete', 'page' => $this->mTitle
->getPrefixedText() )
1050 $wgOut->addHTML( '</div>' );
1055 * Should the parser cache be used?
1057 protected function useParserCache( $oldid ) {
1058 global $wgUser, $wgEnableParserCache;
1060 return $wgEnableParserCache
1061 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1064 && !$this->mTitle
->isCssOrJsPage()
1065 && !$this->mTitle
->isCssJsSubpage();
1070 * @param $target Title object or Array of destination(s) to redirect
1071 * @param $appendSubtitle Boolean [optional]
1072 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1074 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1075 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1077 if( !is_array( $target ) ) {
1078 $target = array( $target );
1080 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1081 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1082 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1083 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of entities?
1085 if( $appendSubtitle ) {
1086 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1088 $sk = $wgUser->getSkin();
1089 // the loop prepends the arrow image before the link, so the first case needs to be outside
1090 $title = array_shift( $target );
1092 $link = $sk->makeKnownLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
1094 $link = $sk->makeLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
1096 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1097 foreach( $target as $rt ) {
1099 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1100 . $sk->makeKnownLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
1102 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1103 . $sk->makeLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
1106 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1107 '<span class="redirectText">'.$link.'</span>';
1111 public function addTrackbacks() {
1112 global $wgOut, $wgUser;
1113 $dbr = wfGetDB( DB_SLAVE
);
1114 $tbs = $dbr->select( 'trackbacks',
1115 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1116 array('tb_page' => $this->getID() )
1118 if( !$dbr->numRows($tbs) ) return;
1121 while( $o = $dbr->fetchObject($tbs) ) {
1123 if( $wgUser->isAllowed( 'trackback' ) ) {
1124 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1125 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1126 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1129 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1136 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1137 $this->mTitle
->invalidateCache();
1140 public function deletetrackback() {
1141 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1142 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1143 $wgOut->addWikiMsg( 'sessionfailure' );
1147 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1148 if( count($permission_errors) ) {
1149 $wgOut->showPermissionsErrorPage( $permission_errors );
1153 $db = wfGetDB( DB_MASTER
);
1154 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1156 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1157 $this->mTitle
->invalidateCache();
1160 public function render() {
1162 $wgOut->setArticleBodyOnly(true);
1167 * Handle action=purge
1169 public function purge() {
1170 global $wgUser, $wgRequest, $wgOut;
1171 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1172 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1177 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1178 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1179 $form = "<form method=\"post\" action=\"$action\">\n" .
1180 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1182 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1183 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1184 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1185 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1186 $wgOut->addHTML( $top . $form . $bottom );
1191 * Perform the actions of a page purging
1193 public function doPurge() {
1195 // Invalidate the cache
1196 $this->mTitle
->invalidateCache();
1199 // Commit the transaction before the purge is sent
1200 $dbw = wfGetDB( DB_MASTER
);
1201 $dbw->immediateCommit();
1204 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1205 $update->doUpdate();
1207 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1208 global $wgMessageCache;
1209 if( $this->getID() == 0 ) {
1212 $text = $this->getRawText();
1214 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1219 * Insert a new empty page record for this article.
1220 * This *must* be followed up by creating a revision
1221 * and running $this->updateToLatest( $rev_id );
1222 * or else the record will be left in a funky state.
1223 * Best if all done inside a transaction.
1225 * @param $dbw Database
1226 * @return int The newly created page_id key, or false if the title already existed
1229 public function insertOn( $dbw ) {
1230 wfProfileIn( __METHOD__
);
1232 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1233 $dbw->insert( 'page', array(
1234 'page_id' => $page_id,
1235 'page_namespace' => $this->mTitle
->getNamespace(),
1236 'page_title' => $this->mTitle
->getDBkey(),
1237 'page_counter' => 0,
1238 'page_restrictions' => '',
1239 'page_is_redirect' => 0, # Will set this shortly...
1241 'page_random' => wfRandom(),
1242 'page_touched' => $dbw->timestamp(),
1243 'page_latest' => 0, # Fill this in shortly...
1244 'page_len' => 0, # Fill this in shortly...
1245 ), __METHOD__
, 'IGNORE' );
1247 $affected = $dbw->affectedRows();
1249 $newid = $dbw->insertId();
1250 $this->mTitle
->resetArticleId( $newid );
1252 wfProfileOut( __METHOD__
);
1253 return $affected ?
$newid : false;
1257 * Update the page record to point to a newly saved revision.
1259 * @param $dbw Database object
1260 * @param $revision Revision: For ID number, and text used to set
1261 length and redirect status fields
1262 * @param $lastRevision Integer: if given, will not overwrite the page field
1263 * when different from the currently set value.
1264 * Giving 0 indicates the new page flag should be set
1266 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1267 * removing rows in redirect table.
1268 * @return bool true on success, false on failure
1271 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1272 wfProfileIn( __METHOD__
);
1274 $text = $revision->getText();
1275 $rt = Title
::newFromRedirect( $text );
1277 $conditions = array( 'page_id' => $this->getId() );
1278 if( !is_null( $lastRevision ) ) {
1279 # An extra check against threads stepping on each other
1280 $conditions['page_latest'] = $lastRevision;
1283 $dbw->update( 'page',
1285 'page_latest' => $revision->getId(),
1286 'page_touched' => $dbw->timestamp(),
1287 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1288 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1289 'page_len' => strlen( $text ),
1294 $result = $dbw->affectedRows() != 0;
1296 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1299 wfProfileOut( __METHOD__
);
1304 * Add row to the redirect table if this is a redirect, remove otherwise.
1306 * @param $dbw Database
1307 * @param $redirectTitle a title object pointing to the redirect target,
1308 * or NULL if this is not a redirect
1309 * @param $lastRevIsRedirect If given, will optimize adding and
1310 * removing rows in redirect table.
1311 * @return bool true on success, false on failure
1314 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1315 // Always update redirects (target link might have changed)
1316 // Update/Insert if we don't know if the last revision was a redirect or not
1317 // Delete if changing from redirect to non-redirect
1318 $isRedirect = !is_null($redirectTitle);
1319 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1320 wfProfileIn( __METHOD__
);
1322 // This title is a redirect, Add/Update row in the redirect table
1323 $set = array( /* SET */
1324 'rd_namespace' => $redirectTitle->getNamespace(),
1325 'rd_title' => $redirectTitle->getDBkey(),
1326 'rd_from' => $this->getId(),
1328 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1330 // This is not a redirect, remove row from redirect table
1331 $where = array( 'rd_from' => $this->getId() );
1332 $dbw->delete( 'redirect', $where, __METHOD__
);
1334 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1335 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1337 wfProfileOut( __METHOD__
);
1338 return ( $dbw->affectedRows() != 0 );
1344 * If the given revision is newer than the currently set page_latest,
1345 * update the page record. Otherwise, do nothing.
1347 * @param $dbw Database object
1348 * @param $revision Revision object
1350 public function updateIfNewerOn( &$dbw, $revision ) {
1351 wfProfileIn( __METHOD__
);
1352 $row = $dbw->selectRow(
1353 array( 'revision', 'page' ),
1354 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1356 'page_id' => $this->getId(),
1357 'page_latest=rev_id' ),
1360 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1361 wfProfileOut( __METHOD__
);
1364 $prev = $row->rev_id
;
1365 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1367 # No or missing previous revision; mark the page as new
1369 $lastRevIsRedirect = null;
1371 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1372 wfProfileOut( __METHOD__
);
1377 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1378 * @return string Complete article text, or null if error
1380 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1381 wfProfileIn( __METHOD__
);
1382 if( strval( $section ) == '' ) {
1383 // Whole-page edit; let the whole text through
1385 if( is_null($edittime) ) {
1386 $rev = Revision
::newFromTitle( $this->mTitle
);
1388 $dbw = wfGetDB( DB_MASTER
);
1389 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1392 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1393 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1396 $oldtext = $rev->getText();
1398 if( $section == 'new' ) {
1399 # Inserting a new section
1400 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1401 $text = strlen( trim( $oldtext ) ) > 0
1402 ?
"{$oldtext}\n\n{$subject}{$text}"
1403 : "{$subject}{$text}";
1405 # Replacing an existing section; roll out the big guns
1407 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1410 wfProfileOut( __METHOD__
);
1415 * @deprecated use Article::doEdit()
1417 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1418 wfDeprecated( __METHOD__
);
1419 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1420 ( $isminor ? EDIT_MINOR
: 0 ) |
1421 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1422 ( $bot ? EDIT_FORCE_BOT
: 0 );
1424 # If this is a comment, add the summary as headline
1425 if( $comment && $summary != "" ) {
1426 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1429 $this->doEdit( $text, $summary, $flags );
1431 $dbw = wfGetDB( DB_MASTER
);
1433 if(!$this->mTitle
->userIsWatching()) {
1439 if( $this->mTitle
->userIsWatching() ) {
1445 $this->doRedirect( $this->isRedirect( $text ) );
1449 * @deprecated use Article::doEdit()
1451 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1452 wfDeprecated( __METHOD__
);
1453 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1454 ( $minor ? EDIT_MINOR
: 0 ) |
1455 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1457 $status = $this->doEdit( $text, $summary, $flags );
1458 if( !$status->isOK() ) {
1462 $dbw = wfGetDB( DB_MASTER
);
1464 if(!$this->mTitle
->userIsWatching()) {
1470 if( $this->mTitle
->userIsWatching() ) {
1477 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1478 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1480 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1487 * Change an existing article or create a new article. Updates RC and all necessary caches,
1488 * optionally via the deferred update array.
1490 * $wgUser must be set before calling this function.
1492 * @param $text String: new text
1493 * @param $summary String: edit summary
1494 * @param $flags Integer bitfield:
1496 * Article is known or assumed to be non-existent, create a new one
1498 * Article is known or assumed to be pre-existing, update it
1500 * Mark this edit minor, if the user is allowed to do so
1502 * Do not log the change in recentchanges
1504 * Mark the edit a "bot" edit regardless of user rights
1505 * EDIT_DEFER_UPDATES
1506 * Defer some of the updates until the end of index.php
1508 * Fill in blank summaries with generated text where possible
1510 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1511 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1512 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1513 * edit-already-exists error will be returned. These two conditions are also possible with
1514 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1516 * @param $baseRevId the revision ID this edit was based off, if any
1517 * @param $user Optional user object, $wgUser will be used if not passed
1519 * @return Status object. Possible errors:
1520 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1521 * edit-gone-missing: In update mode, but the article didn't exist
1522 * edit-conflict: In update mode, the article changed unexpectedly
1523 * edit-no-change: Warning that the text was the same as before
1524 * edit-already-exists: In creation mode, but the article already exists
1526 * Extensions may define additional errors.
1528 * $return->value will contain an associative array with members as follows:
1529 * new: Boolean indicating if the function attempted to create a new article
1530 * revision: The revision object for the inserted revision, or null
1532 * Compatibility note: this function previously returned a boolean value indicating success/failure
1534 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1535 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1537 # Low-level sanity check
1538 if( $this->mTitle
->getText() == '' ) {
1539 throw new MWException( 'Something is trying to edit an article with an empty title' );
1542 wfProfileIn( __METHOD__
);
1544 $user = is_null($user) ?
$wgUser : $user;
1545 $status = Status
::newGood( array() );
1547 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1548 $this->loadPageData();
1550 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1551 $aid = $this->mTitle
->getArticleID();
1553 $flags |
= EDIT_UPDATE
;
1559 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1560 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1562 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1563 wfProfileOut( __METHOD__
);
1564 if( $status->isOK() ) {
1565 $status->fatal( 'edit-hook-aborted');
1570 # Silently ignore EDIT_MINOR if not allowed
1571 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1572 $bot = $flags & EDIT_FORCE_BOT
;
1574 $oldtext = $this->getRawText(); // current revision
1575 $oldsize = strlen( $oldtext );
1577 # Provide autosummaries if one is not provided and autosummaries are enabled.
1578 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1579 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1582 $editInfo = $this->prepareTextForEdit( $text );
1583 $text = $editInfo->pst
;
1584 $newsize = strlen( $text );
1586 $dbw = wfGetDB( DB_MASTER
);
1587 $now = wfTimestampNow();
1589 if( $flags & EDIT_UPDATE
) {
1590 # Update article, but only if changed.
1591 $status->value
['new'] = false;
1592 # Make sure the revision is either completely inserted or not inserted at all
1593 if( !$wgDBtransactions ) {
1594 $userAbort = ignore_user_abort( true );
1599 $changed = ( strcmp( $text, $oldtext ) != 0 );
1602 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1603 - (int)$this->isCountable( $oldtext );
1604 $this->mTotalAdjustment
= 0;
1606 if( !$this->mLatest
) {
1607 # Article gone missing
1608 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1609 $status->fatal( 'edit-gone-missing' );
1610 wfProfileOut( __METHOD__
);
1614 $revision = new Revision( array(
1615 'page' => $this->getId(),
1616 'comment' => $summary,
1617 'minor_edit' => $isminor,
1619 'parent_id' => $this->mLatest
,
1620 'user' => $user->getId(),
1621 'user_text' => $user->getName(),
1625 $revisionId = $revision->insertOn( $dbw );
1629 # Note that we use $this->mLatest instead of fetching a value from the master DB
1630 # during the course of this function. This makes sure that EditPage can detect
1631 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1632 # before this function is called. A previous function used a separate query, this
1633 # creates a window where concurrent edits can cause an ignored edit conflict.
1634 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1637 /* Belated edit conflict! Run away!! */
1638 $status->fatal( 'edit-conflict' );
1639 # Delete the invalid revision if the DB is not transactional
1640 if( !$wgDBtransactions ) {
1641 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1646 global $wgUseRCPatrol;
1647 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1648 # Update recentchanges
1649 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1650 # Mark as patrolled if the user can do so
1651 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan('autopatrol');
1652 # Add RC row to the DB
1653 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1654 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1655 $revisionId, $patrolled
1657 # Log auto-patrolled edits
1659 PatrolLog
::record( $rc, true );
1662 $user->incEditCount();
1666 $status->warning( 'edit-no-change' );
1668 // Keep the same revision ID, but do some updates on it
1669 $revisionId = $this->getRevIdFetched();
1670 // Update page_touched, this is usually implicit in the page update
1671 // Other cache updates are done in onArticleEdit()
1672 $this->mTitle
->invalidateCache();
1675 if( !$wgDBtransactions ) {
1676 ignore_user_abort( $userAbort );
1678 // Now that ignore_user_abort is restored, we can respond to fatal errors
1679 if( !$status->isOK() ) {
1680 wfProfileOut( __METHOD__
);
1684 # Invalidate cache of this article and all pages using this article
1685 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1686 Article
::onArticleEdit( $this->mTitle
, 'skiptransclusions' );
1687 # Update links tables, site stats, etc.
1688 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1690 # Create new article
1691 $status->value
['new'] = true;
1693 # Set statistics members
1694 # We work out if it's countable after PST to avoid counter drift
1695 # when articles are created with {{subst:}}
1696 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1697 $this->mTotalAdjustment
= 1;
1701 # Add the page record; stake our claim on this title!
1702 # This will return false if the article already exists
1703 $newid = $this->insertOn( $dbw );
1705 if( $newid === false ) {
1707 $status->fatal( 'edit-already-exists' );
1708 wfProfileOut( __METHOD__
);
1712 # Save the revision text...
1713 $revision = new Revision( array(
1715 'comment' => $summary,
1716 'minor_edit' => $isminor,
1718 'user' => $user->getId(),
1719 'user_text' => $user->getName(),
1721 $revisionId = $revision->insertOn( $dbw );
1723 $this->mTitle
->resetArticleID( $newid );
1725 # Update the page record with revision data
1726 $this->updateRevisionOn( $dbw, $revision, 0 );
1728 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1729 # Update recentchanges
1730 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1731 global $wgUseRCPatrol, $wgUseNPPatrol;
1732 # Mark as patrolled if the user can do so
1733 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $this->mTitle
->userCan('autopatrol');
1734 # Add RC row to the DB
1735 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1736 '', strlen($text), $revisionId, $patrolled );
1737 # Log auto-patrolled edits
1739 PatrolLog
::record( $rc, true );
1742 $user->incEditCount();
1745 # Update links, etc.
1746 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1749 Article
::onArticleCreate( $this->mTitle
);
1751 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1752 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1755 # Do updates right now unless deferral was requested
1756 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1760 // Return the new revision (or null) to the caller
1761 $status->value
['revision'] = $revision;
1763 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1764 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status ) );
1766 wfProfileOut( __METHOD__
);
1771 * @deprecated wrapper for doRedirect
1773 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1774 wfDeprecated( __METHOD__
);
1775 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1779 * Output a redirect back to the article.
1780 * This is typically used after an edit.
1782 * @param $noRedir Boolean: add redirect=no
1783 * @param $sectionAnchor String: section to redirect to, including "#"
1784 * @param $extraQuery String: extra query params
1786 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1789 $query = 'redirect=no';
1791 $query .= "&$query";
1793 $query = $extraQuery;
1795 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1799 * Mark this particular edit/page as patrolled
1801 public function markpatrolled() {
1802 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1803 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1805 # If we haven't been given an rc_id value, we can't do anything
1806 $rcid = (int) $wgRequest->getVal('rcid');
1807 $rc = RecentChange
::newFromId($rcid);
1808 if( is_null($rc) ) {
1809 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1813 #It would be nice to see where the user had actually come from, but for now just guess
1814 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1815 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1817 $dbw = wfGetDB( DB_MASTER
);
1818 $errors = $rc->doMarkPatrolled();
1820 if( in_array(array('rcpatroldisabled'), $errors) ) {
1821 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1825 if( in_array(array('hookaborted'), $errors) ) {
1826 // The hook itself has handled any output
1830 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1831 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1832 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1833 $wgOut->returnToMain( false, $return );
1837 if( !empty($errors) ) {
1838 $wgOut->showPermissionsErrorPage( $errors );
1843 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1844 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1845 $wgOut->returnToMain( false, $return );
1849 * User-interface handler for the "watch" action
1852 public function watch() {
1853 global $wgUser, $wgOut;
1854 if( $wgUser->isAnon() ) {
1855 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1858 if( wfReadOnly() ) {
1859 $wgOut->readOnlyPage();
1862 if( $this->doWatch() ) {
1863 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1864 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1865 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1867 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1871 * Add this page to $wgUser's watchlist
1872 * @return bool true on successful watch operation
1874 public function doWatch() {
1876 if( $wgUser->isAnon() ) {
1879 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1880 $wgUser->addWatch( $this->mTitle
);
1881 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1887 * User interface handler for the "unwatch" action.
1889 public function unwatch() {
1890 global $wgUser, $wgOut;
1891 if( $wgUser->isAnon() ) {
1892 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1895 if( wfReadOnly() ) {
1896 $wgOut->readOnlyPage();
1899 if( $this->doUnwatch() ) {
1900 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1901 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1902 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1904 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1908 * Stop watching a page
1909 * @return bool true on successful unwatch
1911 public function doUnwatch() {
1913 if( $wgUser->isAnon() ) {
1916 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1917 $wgUser->removeWatch( $this->mTitle
);
1918 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1924 * action=protect handler
1926 public function protect() {
1927 $form = new ProtectionForm( $this );
1932 * action=unprotect handler (alias)
1934 public function unprotect() {
1939 * Update the article's restriction field, and leave a log entry.
1941 * @param $limit Array: set of restriction keys
1942 * @param $reason String
1943 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1944 * @param $expiry Array: per restriction type expiration
1945 * @return bool true on success
1947 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1948 global $wgUser, $wgRestrictionTypes, $wgContLang;
1950 $id = $this->mTitle
->getArticleID();
1951 if( $id <= 0 ||
wfReadOnly() ||
!$this->mTitle
->userCan('protect') ) {
1959 // Take this opportunity to purge out expired restrictions
1960 Title
::purgeExpiredRestrictions();
1962 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1963 # we expect a single selection, but the schema allows otherwise.
1965 $updated = Article
::flattenRestrictions( $limit );
1967 foreach( $wgRestrictionTypes as $action ) {
1968 if( isset( $expiry[$action] ) ) {
1969 # Get current restrictions on $action
1970 $aLimits = $this->mTitle
->getRestrictions( $action );
1971 $current[$action] = implode( '', $aLimits );
1972 # Are any actual restrictions being dealt with here?
1973 $aRChanged = count($aLimits) ||
!empty($limit[$action]);
1974 # If something changed, we need to log it. Checking $aRChanged
1975 # assures that "unprotecting" a page that is not protected does
1976 # not log just because the expiry was "changed".
1977 if( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
1983 $current = Article
::flattenRestrictions( $current );
1985 $changed = ($changed ||
$current != $updated );
1986 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1987 $protect = ( $updated != '' );
1989 # If nothing's changed, do nothing
1991 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1993 $dbw = wfGetDB( DB_MASTER
);
1995 # Prepare a null revision to be added to the history
1996 $modified = $current != '' && $protect;
1998 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2000 $comment_type = 'unprotectedarticle';
2002 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2004 # Only restrictions with the 'protect' right can cascade...
2005 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2006 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2007 # The schema allows multiple restrictions
2008 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2010 $cascade_description = '';
2012 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2016 $comment .= ": $reason";
2018 $editComment = $comment;
2019 $encodedExpiry = array();
2020 $protect_description = '';
2021 foreach( $limit as $action => $restrictions ) {
2022 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
2023 if( $restrictions != '' ) {
2024 $protect_description .= "[$action=$restrictions] (";
2025 if( $encodedExpiry[$action] != 'infinity' ) {
2026 $protect_description .= wfMsgForContent( 'protect-expiring',
2027 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2028 $wgContLang->date( $expiry[$action], false, false ) ,
2029 $wgContLang->time( $expiry[$action], false, false ) );
2031 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2033 $protect_description .= ') ';
2036 $protect_description = trim($protect_description);
2038 if( $protect_description && $protect )
2039 $editComment .= " ($protect_description)";
2041 $editComment .= "$cascade_description";
2042 # Update restrictions table
2043 foreach( $limit as $action => $restrictions ) {
2044 if($restrictions != '' ) {
2045 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2046 array( 'pr_page' => $id,
2047 'pr_type' => $action,
2048 'pr_level' => $restrictions,
2049 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
2050 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
2052 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2053 'pr_type' => $action ), __METHOD__
);
2057 # Insert a null revision
2058 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2059 $nullRevId = $nullRevision->insertOn( $dbw );
2061 $latest = $this->getLatest();
2062 # Update page record
2063 $dbw->update( 'page',
2065 'page_touched' => $dbw->timestamp(),
2066 'page_restrictions' => '',
2067 'page_latest' => $nullRevId
2068 ), array( /* WHERE */
2070 ), 'Article::protect'
2073 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2074 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2076 # Update the protection log
2077 $log = new LogPage( 'protect' );
2079 $params = array($protect_description,$cascade ?
'cascade' : '');
2080 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
2082 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2086 } # End "changed" check
2092 * Take an array of page restrictions and flatten it to a string
2093 * suitable for insertion into the page_restrictions field.
2094 * @param $limit Array
2097 protected static function flattenRestrictions( $limit ) {
2098 if( !is_array( $limit ) ) {
2099 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2103 foreach( $limit as $action => $restrictions ) {
2104 if( $restrictions != '' ) {
2105 $bits[] = "$action=$restrictions";
2108 return implode( ':', $bits );
2112 * Auto-generates a deletion reason
2113 * @param &$hasHistory Boolean: whether the page has a history
2115 public function generateReason( &$hasHistory ) {
2117 $dbw = wfGetDB( DB_MASTER
);
2118 // Get the last revision
2119 $rev = Revision
::newFromTitle( $this->mTitle
);
2120 if( is_null( $rev ) )
2123 // Get the article's contents
2124 $contents = $rev->getText();
2126 // If the page is blank, use the text from the previous revision,
2127 // which can only be blank if there's a move/import/protect dummy revision involved
2128 if( $contents == '' ) {
2129 $prev = $rev->getPrevious();
2131 $contents = $prev->getText();
2136 // Find out if there was only one contributor
2137 // Only scan the last 20 revisions
2139 $res = $dbw->select( 'revision', 'rev_user_text',
2140 array( 'rev_page' => $this->getID() ), __METHOD__
,
2141 array( 'LIMIT' => $limit )
2143 if( $res === false )
2144 // This page has no revisions, which is very weird
2146 if( $res->numRows() > 1 )
2149 $hasHistory = false;
2150 $row = $dbw->fetchObject( $res );
2151 $onlyAuthor = $row->rev_user_text
;
2152 // Try to find a second contributor
2153 foreach( $res as $row ) {
2154 if( $row->rev_user_text
!= $onlyAuthor ) {
2155 $onlyAuthor = false;
2159 $dbw->freeResult( $res );
2161 // Generate the summary with a '$1' placeholder
2163 // The current revision is blank and the one before is also
2164 // blank. It's just not our lucky day
2165 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2168 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2170 $reason = wfMsgForContent( 'excontent', '$1' );
2173 if( $reason == '-' ) {
2174 // Allow these UI messages to be blanked out cleanly
2178 // Replace newlines with spaces to prevent uglyness
2179 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2180 // Calculate the maximum amount of chars to get
2181 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2182 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2183 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2184 // Remove possible unfinished links
2185 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2186 // Now replace the '$1' placeholder
2187 $reason = str_replace( '$1', $contents, $reason );
2193 * UI entry point for page deletion
2195 public function delete() {
2196 global $wgUser, $wgOut, $wgRequest;
2198 $confirm = $wgRequest->wasPosted() &&
2199 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2201 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2202 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2204 $reason = $this->DeleteReasonList
;
2206 if( $reason != 'other' && $this->DeleteReason
!= '' ) {
2207 // Entry from drop down menu + additional comment
2208 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2209 } elseif( $reason == 'other' ) {
2210 $reason = $this->DeleteReason
;
2212 # Flag to hide all contents of the archived revisions
2213 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2215 # This code desperately needs to be totally rewritten
2217 # Read-only check...
2218 if( wfReadOnly() ) {
2219 $wgOut->readOnlyPage();
2224 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2226 if( count( $permission_errors ) > 0 ) {
2227 $wgOut->showPermissionsErrorPage( $permission_errors );
2231 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2233 # Better double-check that it hasn't been deleted yet!
2234 $dbw = wfGetDB( DB_MASTER
);
2235 $conds = $this->mTitle
->pageCond();
2236 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2237 if( $latest === false ) {
2238 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2239 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2240 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2244 # Hack for big sites
2245 $bigHistory = $this->isBigDeletion();
2246 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2247 global $wgLang, $wgDeleteRevisionsLimit;
2248 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2249 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2254 $this->doDelete( $reason, $suppress );
2255 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2257 } elseif( $this->mTitle
->userIsWatching() ) {
2263 // Generate deletion reason
2264 $hasHistory = false;
2265 if( !$reason ) $reason = $this->generateReason($hasHistory);
2267 // If the page has a history, insert a warning
2268 if( $hasHistory && !$confirm ) {
2269 $skin = $wgUser->getSkin();
2270 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2272 global $wgLang, $wgDeleteRevisionsLimit;
2273 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2274 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2278 return $this->confirmDelete( $reason );
2282 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2284 public function isBigDeletion() {
2285 global $wgDeleteRevisionsLimit;
2286 if( $wgDeleteRevisionsLimit ) {
2287 $revCount = $this->estimateRevisionCount();
2288 return $revCount > $wgDeleteRevisionsLimit;
2294 * @return int approximate revision count
2296 public function estimateRevisionCount() {
2297 $dbr = wfGetDB( DB_SLAVE
);
2298 // For an exact count...
2299 //return $dbr->selectField( 'revision', 'COUNT(*)',
2300 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2301 return $dbr->estimateRowCount( 'revision', '*',
2302 array( 'rev_page' => $this->getId() ), __METHOD__
);
2306 * Get the last N authors
2307 * @param $num Integer: number of revisions to get
2308 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2309 * @return array Array of authors, duplicates not removed
2311 public function getLastNAuthors( $num, $revLatest = 0 ) {
2312 wfProfileIn( __METHOD__
);
2313 // First try the slave
2314 // If that doesn't have the latest revision, try the master
2316 $db = wfGetDB( DB_SLAVE
);
2318 $res = $db->select( array( 'page', 'revision' ),
2319 array( 'rev_id', 'rev_user_text' ),
2321 'page_namespace' => $this->mTitle
->getNamespace(),
2322 'page_title' => $this->mTitle
->getDBkey(),
2323 'rev_page = page_id'
2324 ), __METHOD__
, $this->getSelectOptions( array(
2325 'ORDER BY' => 'rev_timestamp DESC',
2330 wfProfileOut( __METHOD__
);
2333 $row = $db->fetchObject( $res );
2334 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2335 $db = wfGetDB( DB_MASTER
);
2340 } while ( $continue );
2342 $authors = array( $row->rev_user_text
);
2343 while ( $row = $db->fetchObject( $res ) ) {
2344 $authors[] = $row->rev_user_text
;
2346 wfProfileOut( __METHOD__
);
2351 * Output deletion confirmation dialog
2352 * @param $reason String: prefilled reason
2354 public function confirmDelete( $reason ) {
2355 global $wgOut, $wgUser;
2357 wfDebug( "Article::confirmDelete\n" );
2359 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2360 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2361 $wgOut->addWikiMsg( 'confirmdeletetext' );
2363 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2364 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2366 <td class='mw-input'>" .
2367 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2368 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2374 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2376 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2377 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2378 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2379 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2380 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2381 "<tr id=\"wpDeleteReasonListRow\">
2382 <td class='mw-label'>" .
2383 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2385 <td class='mw-input'>" .
2386 Xml
::listDropDown( 'wpDeleteReasonList',
2387 wfMsgForContent( 'deletereason-dropdown' ),
2388 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2391 <tr id=\"wpDeleteReasonRow\">
2392 <td class='mw-label'>" .
2393 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2395 <td class='mw-input'>" .
2396 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2397 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2402 <td class='mw-input'>" .
2403 Xml
::checkLabel( wfMsg( 'watchthis' ),
2404 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2410 <td class='mw-submit'>" .
2411 Xml
::submitButton( wfMsg( 'deletepage' ),
2412 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2415 Xml
::closeElement( 'table' ) .
2416 Xml
::closeElement( 'fieldset' ) .
2417 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2418 Xml
::closeElement( 'form' );
2420 if( $wgUser->isAllowed( 'editinterface' ) ) {
2421 $skin = $wgUser->getSkin();
2422 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2423 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2426 $wgOut->addHTML( $form );
2427 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2431 * Perform a deletion and output success or failure messages
2433 public function doDelete( $reason, $suppress = false ) {
2434 global $wgOut, $wgUser;
2435 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2438 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2439 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2440 $deleted = $this->mTitle
->getPrefixedText();
2442 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2443 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2445 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2447 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2448 $wgOut->returnToMain( false );
2449 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2451 if( $error == '' ) {
2452 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2453 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2454 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2456 $wgOut->showFatalError( $error );
2463 * Back-end article deletion
2464 * Deletes the article with database consistency, writes logs, purges caches
2467 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2468 global $wgUseSquid, $wgDeferredUpdateList;
2469 global $wgUseTrackbacks;
2471 wfDebug( __METHOD__
."\n" );
2473 $dbw = wfGetDB( DB_MASTER
);
2474 $ns = $this->mTitle
->getNamespace();
2475 $t = $this->mTitle
->getDBkey();
2476 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2478 if( $t == '' ||
$id == 0 ) {
2482 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2483 array_push( $wgDeferredUpdateList, $u );
2485 // Bitfields to further suppress the content
2488 // This should be 15...
2489 $bitfield |
= Revision
::DELETED_TEXT
;
2490 $bitfield |
= Revision
::DELETED_COMMENT
;
2491 $bitfield |
= Revision
::DELETED_USER
;
2492 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2494 $bitfield = 'rev_deleted';
2498 // For now, shunt the revision data into the archive table.
2499 // Text is *not* removed from the text table; bulk storage
2500 // is left intact to avoid breaking block-compression or
2501 // immutable storage schemes.
2503 // For backwards compatibility, note that some older archive
2504 // table entries will have ar_text and ar_flags fields still.
2506 // In the future, we may keep revisions and mark them with
2507 // the rev_deleted field, which is reserved for this purpose.
2508 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2510 'ar_namespace' => 'page_namespace',
2511 'ar_title' => 'page_title',
2512 'ar_comment' => 'rev_comment',
2513 'ar_user' => 'rev_user',
2514 'ar_user_text' => 'rev_user_text',
2515 'ar_timestamp' => 'rev_timestamp',
2516 'ar_minor_edit' => 'rev_minor_edit',
2517 'ar_rev_id' => 'rev_id',
2518 'ar_text_id' => 'rev_text_id',
2519 'ar_text' => '\'\'', // Be explicit to appease
2520 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2521 'ar_len' => 'rev_len',
2522 'ar_page_id' => 'page_id',
2523 'ar_deleted' => $bitfield
2526 'page_id = rev_page'
2530 # Delete restrictions for it
2531 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2533 # Now that it's safely backed up, delete it
2534 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2535 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2541 # If using cascading deletes, we can skip some explicit deletes
2542 if( !$dbw->cascadingDeletes() ) {
2543 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2545 if($wgUseTrackbacks)
2546 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2548 # Delete outgoing links
2549 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2550 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2551 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2552 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2553 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2554 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2555 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2558 # If using cleanup triggers, we can skip some manual deletes
2559 if( !$dbw->cleanupTriggers() ) {
2560 # Clean up recentchanges entries...
2561 $dbw->delete( 'recentchanges',
2562 array( 'rc_type != '.RC_LOG
,
2563 'rc_namespace' => $this->mTitle
->getNamespace(),
2564 'rc_title' => $this->mTitle
->getDBKey() ),
2566 $dbw->delete( 'recentchanges',
2567 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2572 Article
::onArticleDelete( $this->mTitle
);
2574 # Fix category table counts
2576 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2577 foreach( $res as $row ) {
2578 $cats []= $row->cl_to
;
2580 $this->updateCategoryCounts( array(), $cats );
2582 # Clear the cached article id so the interface doesn't act like we exist
2583 $this->mTitle
->resetArticleID( 0 );
2584 $this->mTitle
->mArticleID
= 0;
2586 # Log the deletion, if the page was suppressed, log it at Oversight instead
2587 $logtype = $suppress ?
'suppress' : 'delete';
2588 $log = new LogPage( $logtype );
2590 # Make sure logging got through
2591 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2599 * Roll back the most recent consecutive set of edits to a page
2600 * from the same user; fails if there are no eligible edits to
2601 * roll back to, e.g. user is the sole contributor. This function
2602 * performs permissions checks on $wgUser, then calls commitRollback()
2603 * to do the dirty work
2605 * @param $fromP String: Name of the user whose edits to rollback.
2606 * @param $summary String: Custom summary. Set to default summary if empty.
2607 * @param $token String: Rollback token.
2608 * @param $bot Boolean: If true, mark all reverted edits as bot.
2610 * @param $resultDetails Array: contains result-specific array of additional values
2611 * 'alreadyrolled' : 'current' (rev)
2612 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2614 * @return array of errors, each error formatted as
2615 * array(messagekey, param1, param2, ...).
2616 * On success, the array is empty. This array can also be passed to
2617 * OutputPage::showPermissionsErrorPage().
2619 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2621 $resultDetails = null;
2624 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2625 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2626 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2628 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2629 $errors[] = array( 'sessionfailure' );
2631 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2632 $errors[] = array( 'actionthrottledtext' );
2634 # If there were errors, bail out now
2635 if( !empty( $errors ) )
2638 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2642 * Backend implementation of doRollback(), please refer there for parameter
2643 * and return value documentation
2645 * NOTE: This function does NOT check ANY permissions, it just commits the
2646 * rollback to the DB Therefore, you should only call this function direct-
2647 * ly if you want to use custom permissions checks. If you don't, use
2648 * doRollback() instead.
2650 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2651 global $wgUseRCPatrol, $wgUser, $wgLang;
2652 $dbw = wfGetDB( DB_MASTER
);
2654 if( wfReadOnly() ) {
2655 return array( array( 'readonlytext' ) );
2658 # Get the last editor
2659 $current = Revision
::newFromTitle( $this->mTitle
);
2660 if( is_null( $current ) ) {
2661 # Something wrong... no page?
2662 return array(array('notanarticle'));
2665 $from = str_replace( '_', ' ', $fromP );
2666 if( $from != $current->getUserText() ) {
2667 $resultDetails = array( 'current' => $current );
2668 return array(array('alreadyrolled',
2669 htmlspecialchars($this->mTitle
->getPrefixedText()),
2670 htmlspecialchars($fromP),
2671 htmlspecialchars($current->getUserText())
2675 # Get the last edit not by this guy
2676 $user = intval( $current->getUser() );
2677 $user_text = $dbw->addQuotes( $current->getUserText() );
2678 $s = $dbw->selectRow( 'revision',
2679 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2680 array( 'rev_page' => $current->getPage(),
2681 "rev_user != {$user} OR rev_user_text != {$user_text}"
2683 array( 'USE INDEX' => 'page_timestamp',
2684 'ORDER BY' => 'rev_timestamp DESC' )
2686 if( $s === false ) {
2687 # No one else ever edited this page
2688 return array(array('cantrollback'));
2689 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2690 # Only admins can see this text
2691 return array(array('notvisiblerev'));
2695 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2696 # Mark all reverted edits as bot
2699 if( $wgUseRCPatrol ) {
2700 # Mark all reverted edits as patrolled
2701 $set['rc_patrolled'] = 1;
2705 $dbw->update( 'recentchanges', $set,
2707 'rc_cur_id' => $current->getPage(),
2708 'rc_user_text' => $current->getUserText(),
2709 "rc_timestamp > '{$s->rev_timestamp}'",
2714 # Generate the edit summary if necessary
2715 $target = Revision
::newFromId( $s->rev_id
);
2716 if( empty( $summary ) ){
2717 $summary = wfMsgForContent( 'revertpage' );
2720 # Allow the custom summary to use the same args as the default message
2722 $target->getUserText(), $from, $s->rev_id
,
2723 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2724 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2726 $summary = wfMsgReplaceArgs( $summary, $args );
2729 $flags = EDIT_UPDATE
;
2731 if( $wgUser->isAllowed('minoredit') )
2732 $flags |
= EDIT_MINOR
;
2734 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2735 $flags |
= EDIT_FORCE_BOT
;
2736 # Actually store the edit
2737 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2738 if( !empty( $status->value
['revision'] ) ) {
2739 $revId = $status->value
['revision']->getId();
2744 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2746 $resultDetails = array(
2747 'summary' => $summary,
2748 'current' => $current,
2749 'target' => $target,
2756 * User interface for rollback operations
2758 public function rollback() {
2759 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2762 $result = $this->doRollback(
2763 $wgRequest->getVal( 'from' ),
2764 $wgRequest->getText( 'summary' ),
2765 $wgRequest->getVal( 'token' ),
2766 $wgRequest->getBool( 'bot' ),
2770 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2771 $wgOut->rateLimited();
2774 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2775 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2776 $errArray = $result[0];
2777 $errMsg = array_shift( $errArray );
2778 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2779 if( isset( $details['current'] ) ){
2780 $current = $details['current'];
2781 if( $current->getComment() != '' ) {
2782 $wgOut->addWikiMsgArray( 'editcomment', array(
2783 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2788 # Display permissions errors before read-only message -- there's no
2789 # point in misleading the user into thinking the inability to rollback
2790 # is only temporary.
2791 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2792 # array_diff is completely broken for arrays of arrays, sigh. Re-
2793 # move any 'readonlytext' error manually.
2795 foreach( $result as $error ) {
2796 if( $error != array( 'readonlytext' ) ) {
2800 $wgOut->showPermissionsErrorPage( $out );
2803 if( $result == array( array( 'readonlytext' ) ) ) {
2804 $wgOut->readOnlyPage();
2808 $current = $details['current'];
2809 $target = $details['target'];
2810 $newId = $details['newid'];
2811 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2812 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2813 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2814 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2815 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2816 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2817 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2818 $wgOut->returnToMain( false, $this->mTitle
);
2820 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2821 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2822 $de->showDiff( '', '' );
2828 * Do standard deferred updates after page view
2830 public function viewUpdates() {
2831 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2832 # Don't update page view counters on views from bot users (bug 14044)
2833 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2834 Article
::incViewCount( $this->getID() );
2835 $u = new SiteStatsUpdate( 1, 0, 0 );
2836 array_push( $wgDeferredUpdateList, $u );
2838 # Update newtalk / watchlist notification status
2839 $wgUser->clearNotification( $this->mTitle
);
2843 * Prepare text which is about to be saved.
2844 * Returns a stdclass with source, pst and output members
2846 public function prepareTextForEdit( $text, $revid=null ) {
2847 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2849 return $this->mPreparedEdit
;
2852 $edit = (object)array();
2853 $edit->revid
= $revid;
2854 $edit->newText
= $text;
2855 $edit->pst
= $this->preSaveTransform( $text );
2856 $options = new ParserOptions
;
2857 $options->setTidy( true );
2858 $options->enableLimitReport();
2859 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2860 $edit->oldText
= $this->getContent();
2861 $this->mPreparedEdit
= $edit;
2866 * Do standard deferred updates after page edit.
2867 * Update links tables, site stats, search index and message cache.
2868 * Purges pages that include this page if the text was changed here.
2869 * Every 100th edit, prune the recent changes table.
2872 * @param $text New text of the article
2873 * @param $summary Edit summary
2874 * @param $minoredit Minor edit
2875 * @param $timestamp_of_pagechange Timestamp associated with the page change
2876 * @param $newid rev_id value of the new revision
2877 * @param $changed Whether or not the content actually changed
2879 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2880 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2882 wfProfileIn( __METHOD__
);
2885 # Be careful not to double-PST: $text is usually already PST-ed once
2886 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2887 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2888 $editInfo = $this->prepareTextForEdit( $text, $newid );
2890 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2891 $editInfo = $this->mPreparedEdit
;
2894 # Save it to the parser cache
2895 if( $wgEnableParserCache ) {
2896 $parserCache = ParserCache
::singleton();
2897 $parserCache->save( $editInfo->output
, $this, $wgUser );
2900 # Update the links tables
2901 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
, false );
2902 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2905 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2907 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2908 if( 0 == mt_rand( 0, 99 ) ) {
2909 // Flush old entries from the `recentchanges` table; we do this on
2910 // random requests so as to avoid an increase in writes for no good reason
2912 $dbw = wfGetDB( DB_MASTER
);
2913 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2914 $recentchanges = $dbw->tableName( 'recentchanges' );
2915 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2916 $dbw->query( $sql );
2920 $id = $this->getID();
2921 $title = $this->mTitle
->getPrefixedDBkey();
2922 $shortTitle = $this->mTitle
->getDBkey();
2925 wfProfileOut( __METHOD__
);
2929 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2930 array_push( $wgDeferredUpdateList, $u );
2931 $u = new SearchUpdate( $id, $title, $text );
2932 array_push( $wgDeferredUpdateList, $u );
2934 # If this is another user's talk page, update newtalk
2935 # Don't do this if $changed = false otherwise some idiot can null-edit a
2936 # load of user talk pages and piss people off, nor if it's a minor edit
2937 # by a properly-flagged bot.
2938 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2939 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2940 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2941 $other = User
::newFromName( $shortTitle, false );
2943 wfDebug( __METHOD__
.": invalid username\n" );
2944 } elseif( User
::isIP( $shortTitle ) ) {
2945 // An anonymous user
2946 $other->setNewtalk( true );
2947 } elseif( $other->isLoggedIn() ) {
2948 $other->setNewtalk( true );
2950 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2955 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2956 $wgMessageCache->replace( $shortTitle, $text );
2959 wfProfileOut( __METHOD__
);
2963 * Perform article updates on a special page creation.
2965 * @param $rev Revision object
2967 * @todo This is a shitty interface function. Kill it and replace the
2968 * other shitty functions like editUpdates and such so it's not needed
2971 public function createUpdates( $rev ) {
2972 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2973 $this->mTotalAdjustment
= 1;
2974 $this->editUpdates( $rev->getText(), $rev->getComment(),
2975 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2979 * Generate the navigation links when browsing through an article revisions
2980 * It shows the information as:
2981 * Revision as of \<date\>; view current revision
2982 * \<- Previous version | Next Version -\>
2984 * @param $oldid String: revision ID of this article revision
2986 public function setOldSubtitle( $oldid = 0 ) {
2987 global $wgLang, $wgOut, $wgUser;
2989 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
2993 $revision = Revision
::newFromId( $oldid );
2995 $current = ( $oldid == $this->mLatest
);
2996 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2997 $sk = $wgUser->getSkin();
2999 ?
wfMsgHtml( 'currentrevisionlink' )
3000 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'currentrevisionlink' ) );
3002 ?
wfMsgHtml( 'diff' )
3003 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
3004 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3006 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
3007 : wfMsgHtml( 'previousrevision' );
3009 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
3010 : wfMsgHtml( 'diff' );
3011 $nextlink = $current
3012 ?
wfMsgHtml( 'nextrevision' )
3013 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
3014 $nextdiff = $current
3015 ?
wfMsgHtml( 'diff' )
3016 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
3019 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3020 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
3021 if( $revision->isCurrent() ) {
3022 // We don't handle top deleted edits too well
3023 $cdel = wfMsgHtml( 'rev-delundel' );
3024 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3025 // If revision was hidden from sysops
3026 $cdel = wfMsgHtml( 'rev-delundel' );
3028 $cdel = $sk->makeKnownLinkObj( $revdel,
3029 wfMsgHtml('rev-delundel'),
3030 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
3031 '&oldid=' . urlencode( $oldid ) );
3032 // Bolden oversighted content
3033 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
3034 $cdel = "<strong>$cdel</strong>";
3036 $cdel = "(<small>$cdel</small>) ";
3038 # Show user links if allowed to see them. Normally they
3039 # are hidden regardless, but since we can already see the text here...
3040 $userlinks = $sk->revUserTools( $revision, false );
3042 $m = wfMsg( 'revision-info-current' );
3043 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3044 ?
'revision-info-current'
3047 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" .
3049 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgHtml( 'revision-nav', $prevdiff,
3050 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3051 $wgOut->setSubtitle( $r );
3055 * This function is called right before saving the wikitext,
3056 * so we can do things like signatures and links-in-context.
3058 * @param $text String
3060 public function preSaveTransform( $text ) {
3061 global $wgParser, $wgUser;
3062 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3065 /* Caching functions */
3068 * checkLastModified returns true if it has taken care of all
3069 * output to the client that is necessary for this request.
3070 * (that is, it has sent a cached version of the page)
3072 protected function tryFileCache() {
3073 static $called = false;
3075 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3079 if( $this->isFileCacheable() ) {
3080 $cache = new HTMLFileCache( $this->mTitle
);
3081 if( $cache->isFileCacheGood( $this->mTouched
) ) {
3082 wfDebug( "Article::tryFileCache(): about to load file\n" );
3083 $cache->loadFromFileCache();
3086 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3087 ob_start( array(&$cache, 'saveToFileCache' ) );
3090 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3096 * Check if the page can be cached
3099 public function isFileCacheable() {
3101 if( HTMLFileCache
::useFileCache() ) {
3102 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3103 // Extension may have reason to disable file caching on some pages.
3105 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3112 * Loads page_touched and returns a value indicating if it should be used
3115 public function checkTouched() {
3116 if( !$this->mDataLoaded
) {
3117 $this->loadPageData();
3119 return !$this->mIsRedirect
;
3123 * Get the page_touched field
3125 public function getTouched() {
3126 # Ensure that page data has been loaded
3127 if( !$this->mDataLoaded
) {
3128 $this->loadPageData();
3130 return $this->mTouched
;
3134 * Get the page_latest field
3136 public function getLatest() {
3137 if( !$this->mDataLoaded
) {
3138 $this->loadPageData();
3140 return $this->mLatest
;
3144 * Edit an article without doing all that other stuff
3145 * The article must already exist; link tables etc
3146 * are not updated, caches are not flushed.
3148 * @param $text String: text submitted
3149 * @param $comment String: comment submitted
3150 * @param $minor Boolean: whereas it's a minor modification
3152 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3153 wfProfileIn( __METHOD__
);
3155 $dbw = wfGetDB( DB_MASTER
);
3156 $revision = new Revision( array(
3157 'page' => $this->getId(),
3159 'comment' => $comment,
3160 'minor_edit' => $minor ?
1 : 0,
3162 $revision->insertOn( $dbw );
3163 $this->updateRevisionOn( $dbw, $revision );
3165 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3167 wfProfileOut( __METHOD__
);
3171 * Used to increment the view counter
3173 * @param $id Integer: article id
3175 public static function incViewCount( $id ) {
3176 $id = intval( $id );
3177 global $wgHitcounterUpdateFreq, $wgDBtype;
3179 $dbw = wfGetDB( DB_MASTER
);
3180 $pageTable = $dbw->tableName( 'page' );
3181 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3182 $acchitsTable = $dbw->tableName( 'acchits' );
3184 if( $wgHitcounterUpdateFreq <= 1 ) {
3185 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3189 # Not important enough to warrant an error page in case of failure
3190 $oldignore = $dbw->ignoreErrors( true );
3192 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3194 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3195 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3196 # Most of the time (or on SQL errors), skip row count check
3197 $dbw->ignoreErrors( $oldignore );
3201 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3202 $row = $dbw->fetchObject( $res );
3203 $rown = intval( $row->n
);
3204 if( $rown >= $wgHitcounterUpdateFreq ){
3205 wfProfileIn( 'Article::incViewCount-collect' );
3206 $old_user_abort = ignore_user_abort( true );
3208 if($wgDBtype == 'mysql')
3209 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3210 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3211 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3212 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3214 $dbw->query("DELETE FROM $hitcounterTable");
3215 if($wgDBtype == 'mysql') {
3216 $dbw->query('UNLOCK TABLES');
3217 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3218 'WHERE page_id = hc_id');
3221 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3222 "FROM $acchitsTable WHERE page_id = hc_id");
3224 $dbw->query("DROP TABLE $acchitsTable");
3226 ignore_user_abort( $old_user_abort );
3227 wfProfileOut( 'Article::incViewCount-collect' );
3229 $dbw->ignoreErrors( $oldignore );
3233 * The onArticle*() functions are supposed to be a kind of hooks
3234 * which should be called whenever any of the specified actions
3237 * This is a good place to put code to clear caches, for instance.
3239 * This is called on page move and undelete, as well as edit
3241 * @param $title a title object
3244 public static function onArticleCreate( $title ) {
3245 # Update existence markers on article/talk tabs...
3246 if( $title->isTalkPage() ) {
3247 $other = $title->getSubjectPage();
3249 $other = $title->getTalkPage();
3251 $other->invalidateCache();
3252 $other->purgeSquid();
3254 $title->touchLinks();
3255 $title->purgeSquid();
3256 $title->deleteTitleProtection();
3259 public static function onArticleDelete( $title ) {
3260 global $wgMessageCache;
3261 # Update existence markers on article/talk tabs...
3262 if( $title->isTalkPage() ) {
3263 $other = $title->getSubjectPage();
3265 $other = $title->getTalkPage();
3267 $other->invalidateCache();
3268 $other->purgeSquid();
3270 $title->touchLinks();
3271 $title->purgeSquid();
3274 HTMLFileCache
::clearFileCache( $title );
3277 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3278 $wgMessageCache->replace( $title->getDBkey(), false );
3281 if( $title->getNamespace() == NS_FILE
) {
3282 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3283 $update->doUpdate();
3286 if( $title->getNamespace() == NS_USER_TALK
) {
3287 $user = User
::newFromName( $title->getText(), false );
3288 $user->setNewtalk( false );
3293 * Purge caches on page update etc
3295 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3296 global $wgDeferredUpdateList;
3298 // Invalidate caches of articles which include this page
3299 if( $transclusions !== 'skiptransclusions' )
3300 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3302 // Invalidate the caches of all pages which redirect here
3303 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3305 # Purge squid for this page only
3306 $title->purgeSquid();
3308 # Clear file cache for this page only
3309 HTMLFileCache
::clearFileCache( $title );
3315 * Overriden by ImagePage class, only present here to avoid a fatal error
3316 * Called for ?action=revert
3318 public function revert() {
3320 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3324 * Info about this page
3325 * Called for ?action=info when $wgAllowPageInfo is on.
3327 public function info() {
3328 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3330 if( !$wgAllowPageInfo ) {
3331 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3335 $page = $this->mTitle
->getSubjectPage();
3337 $wgOut->setPagetitle( $page->getPrefixedText() );
3338 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3339 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3341 if( !$this->mTitle
->exists() ) {
3342 $wgOut->addHTML( '<div class="noarticletext">' );
3343 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3344 // This doesn't quite make sense; the user is asking for
3345 // information about the _page_, not the message... -- RC
3346 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3348 $msg = $wgUser->isLoggedIn()
3350 : 'noarticletextanon';
3351 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3353 $wgOut->addHTML( '</div>' );
3355 $dbr = wfGetDB( DB_SLAVE
);
3357 'wl_title' => $page->getDBkey(),
3358 'wl_namespace' => $page->getNamespace() );
3359 $numwatchers = $dbr->selectField(
3364 $this->getSelectOptions() );
3366 $pageInfo = $this->pageCountInfo( $page );
3367 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3369 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3370 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3372 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3374 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3376 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3378 $wgOut->addHTML( '</ul>' );
3383 * Return the total number of edits and number of unique editors
3384 * on a given page. If page does not exist, returns false.
3386 * @param $title Title object
3389 protected function pageCountInfo( $title ) {
3390 $id = $title->getArticleId();
3394 $dbr = wfGetDB( DB_SLAVE
);
3395 $rev_clause = array( 'rev_page' => $id );
3396 $edits = $dbr->selectField(
3401 $this->getSelectOptions()
3403 $authors = $dbr->selectField(
3405 'COUNT(DISTINCT rev_user_text)',
3408 $this->getSelectOptions()
3410 return array( 'edits' => $edits, 'authors' => $authors );
3414 * Return a list of templates used by this article.
3415 * Uses the templatelinks table
3417 * @return Array of Title objects
3419 public function getUsedTemplates() {
3421 $id = $this->mTitle
->getArticleID();
3425 $dbr = wfGetDB( DB_SLAVE
);
3426 $res = $dbr->select( array( 'templatelinks' ),
3427 array( 'tl_namespace', 'tl_title' ),
3428 array( 'tl_from' => $id ),
3430 if( $res !== false ) {
3431 foreach( $res as $row ) {
3432 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3435 $dbr->freeResult( $res );
3440 * Returns a list of hidden categories this page is a member of.
3441 * Uses the page_props and categorylinks tables.
3443 * @return Array of Title objects
3445 public function getHiddenCategories() {
3447 $id = $this->mTitle
->getArticleID();
3451 $dbr = wfGetDB( DB_SLAVE
);
3452 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3454 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3455 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3457 if( $res !== false ) {
3458 foreach( $res as $row ) {
3459 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3462 $dbr->freeResult( $res );
3467 * Return an applicable autosummary if one exists for the given edit.
3468 * @param $oldtext String: the previous text of the page.
3469 * @param $newtext String: The submitted text of the page.
3470 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3471 * @return string An appropriate autosummary, or an empty string.
3473 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3474 # Decide what kind of autosummary is needed.
3476 # Redirect autosummaries
3477 $ot = Title
::newFromRedirect( $oldtext );
3478 $rt = Title
::newFromRedirect( $newtext );
3479 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3480 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3483 # New page autosummaries
3484 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3485 # If they're making a new article, give its text, truncated, in the summary.
3487 $truncatedtext = $wgContLang->truncate(
3488 str_replace("\n", ' ', $newtext),
3489 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3491 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3494 # Blanking autosummaries
3495 if( $oldtext != '' && $newtext == '' ) {
3496 return wfMsgForContent( 'autosumm-blank' );
3497 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3498 # Removing more than 90% of the article
3500 $truncatedtext = $wgContLang->truncate(
3502 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3505 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3508 # If we reach this point, there's no applicable autosummary for our case, so our
3509 # autosummary is empty.
3514 * Add the primary page-view wikitext to the output buffer
3515 * Saves the text into the parser cache if possible.
3516 * Updates templatelinks if it is out of date.
3518 * @param $text String
3519 * @param $cache Boolean
3521 public function outputWikiText( $text, $cache = true ) {
3522 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3524 $popts = $wgOut->parserOptions();
3525 $popts->setTidy(true);
3526 $popts->enableLimitReport();
3527 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3528 $popts, true, true, $this->getRevIdFetched() );
3529 $popts->setTidy(false);
3530 $popts->enableLimitReport( false );
3531 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3532 $parserCache = ParserCache
::singleton();
3533 $parserCache->save( $parserOutput, $this, $wgUser );
3535 // Make sure file cache is not used on uncacheable content.
3536 // Output that has magic words in it can still use the parser cache
3537 // (if enabled), though it will generally expire sooner.
3538 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3539 $wgUseFileCache = false;
3542 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3543 // templatelinks table may have become out of sync,
3544 // especially if using variable-based transclusions.
3545 // For paranoia, check if things have changed and if
3546 // so apply updates to the database. This will ensure
3547 // that cascaded protections apply as soon as the changes
3550 # Get templates from templatelinks
3551 $id = $this->mTitle
->getArticleID();
3553 $tlTemplates = array();
3555 $dbr = wfGetDB( DB_SLAVE
);
3556 $res = $dbr->select( array( 'templatelinks' ),
3557 array( 'tl_namespace', 'tl_title' ),
3558 array( 'tl_from' => $id ),
3563 if( $res !== false ) {
3564 foreach( $res as $row ) {
3565 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3569 # Get templates from parser output.
3570 $poTemplates_allns = $parserOutput->getTemplates();
3572 $poTemplates = array ();
3573 foreach ( $poTemplates_allns as $ns_templates ) {
3574 $poTemplates = array_merge( $poTemplates, $ns_templates );
3578 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3580 if( count( $templates_diff ) > 0 ) {
3581 # Whee, link updates time.
3582 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3587 $wgOut->addParserOutput( $parserOutput );
3591 * Update all the appropriate counts in the category table, given that
3592 * we've added the categories $added and deleted the categories $deleted.
3594 * @param $added array The names of categories that were added
3595 * @param $deleted array The names of categories that were deleted
3598 public function updateCategoryCounts( $added, $deleted ) {
3599 $ns = $this->mTitle
->getNamespace();
3600 $dbw = wfGetDB( DB_MASTER
);
3602 # First make sure the rows exist. If one of the "deleted" ones didn't
3603 # exist, we might legitimately not create it, but it's simpler to just
3604 # create it and then give it a negative value, since the value is bogus
3607 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3608 $insertCats = array_merge( $added, $deleted );
3609 if( !$insertCats ) {
3610 # Okay, nothing to do
3613 $insertRows = array();
3614 foreach( $insertCats as $cat ) {
3615 $insertRows[] = array( 'cat_title' => $cat );
3617 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3619 $addFields = array( 'cat_pages = cat_pages + 1' );
3620 $removeFields = array( 'cat_pages = cat_pages - 1' );
3621 if( $ns == NS_CATEGORY
) {
3622 $addFields[] = 'cat_subcats = cat_subcats + 1';
3623 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3624 } elseif( $ns == NS_FILE
) {
3625 $addFields[] = 'cat_files = cat_files + 1';
3626 $removeFields[] = 'cat_files = cat_files - 1';
3633 array( 'cat_title' => $added ),
3641 array( 'cat_title' => $deleted ),