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 $row = $dbr->selectRow( 'redirect',
88 array('rd_namespace', 'rd_title'),
89 array('rd_from' => $this->getID() ),
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
::newFromRedirectRecurse( $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 $hideBit = Revision
::DELETED_USER
; // username hidden?
702 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
703 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
704 WHERE rev_page = $pageId
705 AND rev_user != $user
706 AND rev_deleted & $hideBit = 0
707 GROUP BY rev_user, rev_user_text, user_real_name
708 ORDER BY timestamp DESC";
711 $sql = $dbr->limitResult($sql, $limit, $offset);
713 $sql .= ' '. $this->getSelectOptions();
715 $res = $dbr->query($sql, __METHOD__
);
717 return new UserArrayFromResult( $res );
721 * This is the default action of the script: just view the page of
724 public function view() {
725 global $wgUser, $wgOut, $wgRequest, $wgContLang;
726 global $wgEnableParserCache, $wgStylePath, $wgParser;
727 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
728 global $wgDefaultRobotPolicy;
730 # Let the parser know if this is the printable version
731 if( $wgOut->isPrintable() ) {
732 $wgOut->parserOptions()->setIsPrintable( true );
735 wfProfileIn( __METHOD__
);
737 # Get variables from query string
738 $oldid = $this->getOldID();
740 # Try client and file cache
741 if( $oldid === 0 && $this->checkTouched() ) {
744 $parserCache = ParserCache
::singleton();
745 $wgOut->setETag( $parserCache->getETag($this, $wgOut->parserOptions()) );
747 # Is is client cached?
748 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
749 wfProfileOut( __METHOD__
);
752 } else if( $this->tryFileCache() ) {
753 # tell wgOut that output is taken care of
755 $this->viewUpdates();
756 wfProfileOut( __METHOD__
);
761 $ns = $this->mTitle
->getNamespace(); # shortcut
762 $sk = $wgUser->getSkin();
764 # getOldID may want us to redirect somewhere else
765 if( $this->mRedirectUrl
) {
766 $wgOut->redirect( $this->mRedirectUrl
);
767 wfProfileOut( __METHOD__
);
771 $diff = $wgRequest->getVal( 'diff' );
772 $rcid = $wgRequest->getVal( 'rcid' );
773 $rdfrom = $wgRequest->getVal( 'rdfrom' );
774 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
775 $purge = $wgRequest->getVal( 'action' ) == 'purge';
778 $wgOut->setArticleFlag( true );
780 # Discourage indexing of printable versions, but encourage following
781 if( $wgOut->isPrintable() ) {
782 $policy = 'noindex,follow';
783 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
784 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
785 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
786 # Honour customised robot policies for this namespace
787 $policy = $wgNamespaceRobotPolicies[$ns];
789 $policy = $wgDefaultRobotPolicy;
791 $wgOut->setRobotPolicy( $policy );
793 # Allow admins to see deleted content if explicitly requested
794 $delId = $diff ?
$diff : $oldid;
795 $unhide = $wgRequest->getInt('unhide') == 1;
796 # If we got diff and oldid in the query, we want to see a
797 # diff page instead of the article.
798 if( !is_null( $diff ) ) {
799 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
801 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
802 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
803 // DifferenceEngine directly fetched the revision:
804 $this->mRevIdFetched
= $de->mNewid
;
805 $de->showDiffPage( $diffOnly );
807 // Needed to get the page's current revision
808 $this->loadPageData();
809 if( $diff == 0 ||
$diff == $this->mLatest
) {
810 # Run view updates for current revision only
811 $this->viewUpdates();
813 wfProfileOut( __METHOD__
);
817 if( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
818 # User/User_talk subpages are not modified. (bug 11443)
819 if( !$this->mTitle
->isSubpage() ) {
820 $block = new Block();
821 if( $block->load( $this->mTitle
->getBaseText() ) ) {
822 $wgOut->setRobotpolicy( 'noindex,nofollow' );
827 # Should the parser cache be used?
828 $pcache = $this->useParserCache( $oldid );
829 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
830 if( $wgUser->getOption( 'stubthreshold' ) ) {
831 wfIncrStats( 'pcache_miss_stub' );
834 $wasRedirected = false;
835 if( isset( $this->mRedirectedFrom
) ) {
836 // This is an internally redirected page view.
837 // We'll need a backlink to the source page for navigation.
838 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
839 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
840 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
841 $wgOut->setSubtitle( $s );
843 // Set the fragment if one was specified in the redirect
844 if( strval( $this->mTitle
->getFragment() ) != '' ) {
845 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
846 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
849 // Add a <link rel="canonical"> tag
850 $wgOut->addLink( array( 'rel' => 'canonical',
851 'href' => $this->mTitle
->getLocalURL() )
853 $wasRedirected = true;
855 } elseif( !empty( $rdfrom ) ) {
856 // This is an externally redirected view, from some other wiki.
857 // If it was reported from a trusted site, supply a backlink.
858 global $wgRedirectSources;
859 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
860 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
861 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
862 $wgOut->setSubtitle( $s );
863 $wasRedirected = true;
867 # Allow a specific header on talk pages, like [[MediaWiki:Talkpagetext]]
868 if( $this->mTitle
->isTalkPage() ) {
869 $msg = wfMsgNoTrans( 'talkpageheader' );
870 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
871 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
876 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
877 if( $pcache && $wgOut->tryParserCache( $this ) ) {
878 // Ensure that UI elements requiring revision ID have
879 // the correct version information.
880 $wgOut->setRevisionId( $this->mLatest
);
883 # Fetch content and check for errors
885 # If the article does not exist and was deleted/moved, show the log
886 if( $this->getID() == 0 ) {
889 $text = $this->getContent();
890 // For now, check also for ID until getContent actually returns
891 // false for pages that do not exists
892 if( $text === false ||
$this->getID() === 0 ) {
893 # Failed to load, replace text with error message
894 $t = $this->mTitle
->getPrefixedText();
896 $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
897 $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
898 // Always use page content for pages in the MediaWiki namespace
899 // since it contains the default message
900 } elseif ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
) {
901 $text = wfMsgExt( 'noarticletext', 'parsemag' );
906 if( $this->getID() === 0 ) {
907 $wgOut->setRobotPolicy( 'noindex,nofollow' );
908 $text = "<div class='noarticletext'>\n$text\n</div>";
909 if( !$this->hasViewableContent() ) {
910 // If there's no backing content, send a 404 Not Found
911 // for better machine handling of broken links.
917 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
920 # Another whitelist check in case oldid is altering the title
921 if( !$this->mTitle
->userCanRead() ) {
922 $wgOut->loginToUse();
925 wfProfileOut( __METHOD__
);
929 # For ?curid=x urls, disallow indexing
930 if( $wgRequest->getInt('curid') )
931 $wgOut->setRobotPolicy( 'noindex,follow' );
933 # We're looking at an old revision
934 if( !empty( $oldid ) ) {
935 $wgOut->setRobotPolicy( 'noindex,nofollow' );
936 if( is_null( $this->mRevision
) ) {
937 // FIXME: This would be a nice place to load the 'no such page' text.
939 $this->setOldSubtitle( $oldid );
940 # Allow admins to see deleted content if explicitly requested
941 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
942 // If the user is not allowed to see it...
943 if( !$this->mRevision
->userCan(Revision
::DELETED_TEXT
) ) {
944 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
945 'rev-deleted-text-permission' );
946 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
947 wfProfileOut( __METHOD__
);
949 // If the user needs to confirm that they want to see it...
950 } else if( !$unhide ) {
951 # Give explanation and add a link to view the revision...
952 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
953 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
954 array('rev-deleted-text-unhide',$link) );
955 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
956 wfProfileOut( __METHOD__
);
958 // We are allowed to see...
960 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
961 'rev-deleted-text-view' );
964 // Is this the current revision and otherwise cacheable? Try the parser cache...
965 if( $oldid === $this->getLatest() && $this->useParserCache( false )
966 && $wgOut->tryParserCache( $this ) )
973 // Ensure that UI elements requiring revision ID have
974 // the correct version information.
975 $wgOut->setRevisionId( $this->getRevIdFetched() );
979 // Pages containing custom CSS or JavaScript get special treatment
980 } else if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
981 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
982 // Give hooks a chance to customise the output
983 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
984 // Wrap the whole lot in a <pre> and don't parse
986 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
987 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
988 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
989 $wgOut->addHTML( "\n</pre>\n" );
991 } else if( $rt = Title
::newFromRedirectArray( $text ) ) { # get an array of redirect targets
992 # Don't append the subtitle if this was an old revision
993 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
994 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
995 $wgOut->addParserOutputNoText( $parseout );
996 } else if( $pcache ) {
997 # Display content and save to parser cache
998 $this->outputWikiText( $text );
1000 # Display content, don't attempt to save to parser cache
1001 # Don't show section-edit links on old revisions... this way lies madness.
1002 if( !$this->isCurrent() ) {
1003 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
1005 # Display content and don't save to parser cache
1006 # With timing hack -- TS 2006-07-26
1008 $this->outputWikiText( $text, false );
1013 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
1014 $this->mTitle
->getPrefixedDBkey()));
1017 if( !$this->isCurrent() ) {
1018 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
1022 /* title may have been set from the cache */
1023 $t = $wgOut->getPageTitle();
1025 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1027 # For the main page, overwrite the <title> element with the con-
1028 # tents of 'pagetitle-view-mainpage' instead of the default (if
1029 # that's not empty).
1030 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
1031 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
1032 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
1036 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1037 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1038 $wgOut->addWikiMsg('anontalkpagetext');
1041 # If we have been passed an &rcid= parameter, we want to give the user a
1042 # chance to mark this new article as patrolled.
1043 if( !empty($rcid) && $this->mTitle
->exists() && $this->mTitle
->quickUserCan('patrol') ) {
1045 "<div class='patrollink'>" .
1046 wfMsgHtml( 'markaspatrolledlink',
1047 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
1048 "action=markpatrolled&rcid=$rcid" )
1055 if( $wgUseTrackbacks ) {
1056 $this->addTrackbacks();
1059 $this->viewUpdates();
1060 wfProfileOut( __METHOD__
);
1063 protected function showLogs() {
1064 global $wgUser, $wgOut;
1065 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1066 $pager = new LogPager( $loglist, array('move', 'delete'), false, $this->mTitle
->getPrefixedText() );
1067 if( $pager->getNumRows() > 0 ) {
1068 $pager->mLimit
= 10;
1069 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1070 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1072 $loglist->beginLogEventsList() .
1074 $loglist->endLogEventsList()
1076 if( $pager->getNumRows() > 10 ) {
1077 $wgOut->addHTML( $wgUser->getSkin()->link(
1078 SpecialPage
::getTitleFor( 'Log' ),
1079 wfMsgHtml( 'log-fulllog' ),
1081 array( 'page' => $this->mTitle
->getPrefixedText() )
1084 $wgOut->addHTML( '</div>' );
1089 * Should the parser cache be used?
1091 protected function useParserCache( $oldid ) {
1092 global $wgUser, $wgEnableParserCache;
1094 return $wgEnableParserCache
1095 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1098 && !$this->mTitle
->isCssOrJsPage()
1099 && !$this->mTitle
->isCssJsSubpage();
1104 * @param $target Title object or Array of destination(s) to redirect
1105 * @param $appendSubtitle Boolean [optional]
1106 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1108 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1109 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1111 if( !is_array( $target ) ) {
1112 $target = array( $target );
1114 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1115 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1116 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1117 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of entities?
1119 if( $appendSubtitle ) {
1120 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1122 $sk = $wgUser->getSkin();
1123 // the loop prepends the arrow image before the link, so the first case needs to be outside
1124 $title = array_shift( $target );
1126 $link = $sk->makeKnownLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
1128 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1130 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1131 foreach( $target as $rt ) {
1133 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1134 . $sk->makeKnownLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
1136 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1137 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1140 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1141 '<span class="redirectText">'.$link.'</span>';
1145 public function addTrackbacks() {
1146 global $wgOut, $wgUser;
1147 $dbr = wfGetDB( DB_SLAVE
);
1148 $tbs = $dbr->select( 'trackbacks',
1149 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1150 array('tb_page' => $this->getID() )
1152 if( !$dbr->numRows($tbs) ) return;
1155 while( $o = $dbr->fetchObject($tbs) ) {
1157 if( $wgUser->isAllowed( 'trackback' ) ) {
1158 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1159 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1160 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1163 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1170 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1171 $this->mTitle
->invalidateCache();
1174 public function deletetrackback() {
1175 global $wgUser, $wgRequest, $wgOut;
1176 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1177 $wgOut->addWikiMsg( 'sessionfailure' );
1181 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1182 if( count($permission_errors) ) {
1183 $wgOut->showPermissionsErrorPage( $permission_errors );
1187 $db = wfGetDB( DB_MASTER
);
1188 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1190 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1191 $this->mTitle
->invalidateCache();
1194 public function render() {
1196 $wgOut->setArticleBodyOnly(true);
1201 * Handle action=purge
1203 public function purge() {
1204 global $wgUser, $wgRequest, $wgOut;
1205 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1206 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1211 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1212 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1213 $form = "<form method=\"post\" action=\"$action\">\n" .
1214 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1216 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1217 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1218 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1219 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1220 $wgOut->addHTML( $top . $form . $bottom );
1225 * Perform the actions of a page purging
1227 public function doPurge() {
1229 // Invalidate the cache
1230 $this->mTitle
->invalidateCache();
1233 // Commit the transaction before the purge is sent
1234 $dbw = wfGetDB( DB_MASTER
);
1235 $dbw->immediateCommit();
1238 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1239 $update->doUpdate();
1241 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1242 global $wgMessageCache;
1243 if( $this->getID() == 0 ) {
1246 $text = $this->getRawText();
1248 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1253 * Insert a new empty page record for this article.
1254 * This *must* be followed up by creating a revision
1255 * and running $this->updateToLatest( $rev_id );
1256 * or else the record will be left in a funky state.
1257 * Best if all done inside a transaction.
1259 * @param $dbw Database
1260 * @return int The newly created page_id key, or false if the title already existed
1263 public function insertOn( $dbw ) {
1264 wfProfileIn( __METHOD__
);
1266 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1267 $dbw->insert( 'page', array(
1268 'page_id' => $page_id,
1269 'page_namespace' => $this->mTitle
->getNamespace(),
1270 'page_title' => $this->mTitle
->getDBkey(),
1271 'page_counter' => 0,
1272 'page_restrictions' => '',
1273 'page_is_redirect' => 0, # Will set this shortly...
1275 'page_random' => wfRandom(),
1276 'page_touched' => $dbw->timestamp(),
1277 'page_latest' => 0, # Fill this in shortly...
1278 'page_len' => 0, # Fill this in shortly...
1279 ), __METHOD__
, 'IGNORE' );
1281 $affected = $dbw->affectedRows();
1283 $newid = $dbw->insertId();
1284 $this->mTitle
->resetArticleId( $newid );
1286 wfProfileOut( __METHOD__
);
1287 return $affected ?
$newid : false;
1291 * Update the page record to point to a newly saved revision.
1293 * @param $dbw Database object
1294 * @param $revision Revision: For ID number, and text used to set
1295 length and redirect status fields
1296 * @param $lastRevision Integer: if given, will not overwrite the page field
1297 * when different from the currently set value.
1298 * Giving 0 indicates the new page flag should be set
1300 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1301 * removing rows in redirect table.
1302 * @return bool true on success, false on failure
1305 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1306 wfProfileIn( __METHOD__
);
1308 $text = $revision->getText();
1309 $rt = Title
::newFromRedirect( $text );
1311 $conditions = array( 'page_id' => $this->getId() );
1312 if( !is_null( $lastRevision ) ) {
1313 # An extra check against threads stepping on each other
1314 $conditions['page_latest'] = $lastRevision;
1317 $dbw->update( 'page',
1319 'page_latest' => $revision->getId(),
1320 'page_touched' => $dbw->timestamp(),
1321 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1322 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1323 'page_len' => strlen( $text ),
1328 $result = $dbw->affectedRows() != 0;
1330 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1333 wfProfileOut( __METHOD__
);
1338 * Add row to the redirect table if this is a redirect, remove otherwise.
1340 * @param $dbw Database
1341 * @param $redirectTitle a title object pointing to the redirect target,
1342 * or NULL if this is not a redirect
1343 * @param $lastRevIsRedirect If given, will optimize adding and
1344 * removing rows in redirect table.
1345 * @return bool true on success, false on failure
1348 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1349 // Always update redirects (target link might have changed)
1350 // Update/Insert if we don't know if the last revision was a redirect or not
1351 // Delete if changing from redirect to non-redirect
1352 $isRedirect = !is_null($redirectTitle);
1353 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1354 wfProfileIn( __METHOD__
);
1356 // This title is a redirect, Add/Update row in the redirect table
1357 $set = array( /* SET */
1358 'rd_namespace' => $redirectTitle->getNamespace(),
1359 'rd_title' => $redirectTitle->getDBkey(),
1360 'rd_from' => $this->getId(),
1362 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1364 // This is not a redirect, remove row from redirect table
1365 $where = array( 'rd_from' => $this->getId() );
1366 $dbw->delete( 'redirect', $where, __METHOD__
);
1368 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1369 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1371 wfProfileOut( __METHOD__
);
1372 return ( $dbw->affectedRows() != 0 );
1378 * If the given revision is newer than the currently set page_latest,
1379 * update the page record. Otherwise, do nothing.
1381 * @param $dbw Database object
1382 * @param $revision Revision object
1384 public function updateIfNewerOn( &$dbw, $revision ) {
1385 wfProfileIn( __METHOD__
);
1386 $row = $dbw->selectRow(
1387 array( 'revision', 'page' ),
1388 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1390 'page_id' => $this->getId(),
1391 'page_latest=rev_id' ),
1394 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1395 wfProfileOut( __METHOD__
);
1398 $prev = $row->rev_id
;
1399 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1401 # No or missing previous revision; mark the page as new
1403 $lastRevIsRedirect = null;
1405 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1406 wfProfileOut( __METHOD__
);
1411 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1412 * @return string Complete article text, or null if error
1414 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1415 wfProfileIn( __METHOD__
);
1416 if( strval( $section ) == '' ) {
1417 // Whole-page edit; let the whole text through
1419 if( is_null($edittime) ) {
1420 $rev = Revision
::newFromTitle( $this->mTitle
);
1422 $dbw = wfGetDB( DB_MASTER
);
1423 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1426 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1427 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1430 $oldtext = $rev->getText();
1432 if( $section == 'new' ) {
1433 # Inserting a new section
1434 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1435 $text = strlen( trim( $oldtext ) ) > 0
1436 ?
"{$oldtext}\n\n{$subject}{$text}"
1437 : "{$subject}{$text}";
1439 # Replacing an existing section; roll out the big guns
1441 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1444 wfProfileOut( __METHOD__
);
1449 * @deprecated use Article::doEdit()
1451 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1452 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1453 ( $isminor ? EDIT_MINOR
: 0 ) |
1454 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1455 ( $bot ? EDIT_FORCE_BOT
: 0 );
1457 # If this is a comment, add the summary as headline
1458 if( $comment && $summary != "" ) {
1459 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1462 $this->doEdit( $text, $summary, $flags );
1464 $dbw = wfGetDB( DB_MASTER
);
1466 if(!$this->mTitle
->userIsWatching()) {
1472 if( $this->mTitle
->userIsWatching() ) {
1478 $this->doRedirect( $this->isRedirect( $text ) );
1482 * @deprecated use Article::doEdit()
1484 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1485 wfDeprecated( __METHOD__
);
1486 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1487 ( $minor ? EDIT_MINOR
: 0 ) |
1488 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1490 $status = $this->doEdit( $text, $summary, $flags );
1491 if( !$status->isOK() ) {
1495 $dbw = wfGetDB( DB_MASTER
);
1497 if(!$this->mTitle
->userIsWatching()) {
1503 if( $this->mTitle
->userIsWatching() ) {
1510 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1511 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1513 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1520 * Change an existing article or create a new article. Updates RC and all necessary caches,
1521 * optionally via the deferred update array.
1523 * $wgUser must be set before calling this function.
1525 * @param $text String: new text
1526 * @param $summary String: edit summary
1527 * @param $flags Integer bitfield:
1529 * Article is known or assumed to be non-existent, create a new one
1531 * Article is known or assumed to be pre-existing, update it
1533 * Mark this edit minor, if the user is allowed to do so
1535 * Do not log the change in recentchanges
1537 * Mark the edit a "bot" edit regardless of user rights
1538 * EDIT_DEFER_UPDATES
1539 * Defer some of the updates until the end of index.php
1541 * Fill in blank summaries with generated text where possible
1543 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1544 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1545 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1546 * edit-already-exists error will be returned. These two conditions are also possible with
1547 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1549 * @param $baseRevId the revision ID this edit was based off, if any
1550 * @param $user Optional user object, $wgUser will be used if not passed
1552 * @return Status object. Possible errors:
1553 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1554 * edit-gone-missing: In update mode, but the article didn't exist
1555 * edit-conflict: In update mode, the article changed unexpectedly
1556 * edit-no-change: Warning that the text was the same as before
1557 * edit-already-exists: In creation mode, but the article already exists
1559 * Extensions may define additional errors.
1561 * $return->value will contain an associative array with members as follows:
1562 * new: Boolean indicating if the function attempted to create a new article
1563 * revision: The revision object for the inserted revision, or null
1565 * Compatibility note: this function previously returned a boolean value indicating success/failure
1567 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1568 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1570 # Low-level sanity check
1571 if( $this->mTitle
->getText() == '' ) {
1572 throw new MWException( 'Something is trying to edit an article with an empty title' );
1575 wfProfileIn( __METHOD__
);
1577 $user = is_null($user) ?
$wgUser : $user;
1578 $status = Status
::newGood( array() );
1580 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1581 $this->loadPageData();
1583 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1584 $aid = $this->mTitle
->getArticleID();
1586 $flags |
= EDIT_UPDATE
;
1592 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1593 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1595 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1596 wfProfileOut( __METHOD__
);
1597 if( $status->isOK() ) {
1598 $status->fatal( 'edit-hook-aborted');
1603 # Silently ignore EDIT_MINOR if not allowed
1604 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1605 $bot = $flags & EDIT_FORCE_BOT
;
1607 $oldtext = $this->getRawText(); // current revision
1608 $oldsize = strlen( $oldtext );
1610 # Provide autosummaries if one is not provided and autosummaries are enabled.
1611 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1612 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1615 $editInfo = $this->prepareTextForEdit( $text );
1616 $text = $editInfo->pst
;
1617 $newsize = strlen( $text );
1619 $dbw = wfGetDB( DB_MASTER
);
1620 $now = wfTimestampNow();
1622 if( $flags & EDIT_UPDATE
) {
1623 # Update article, but only if changed.
1624 $status->value
['new'] = false;
1625 # Make sure the revision is either completely inserted or not inserted at all
1626 if( !$wgDBtransactions ) {
1627 $userAbort = ignore_user_abort( true );
1632 $changed = ( strcmp( $text, $oldtext ) != 0 );
1635 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1636 - (int)$this->isCountable( $oldtext );
1637 $this->mTotalAdjustment
= 0;
1639 if( !$this->mLatest
) {
1640 # Article gone missing
1641 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1642 $status->fatal( 'edit-gone-missing' );
1643 wfProfileOut( __METHOD__
);
1647 $revision = new Revision( array(
1648 'page' => $this->getId(),
1649 'comment' => $summary,
1650 'minor_edit' => $isminor,
1652 'parent_id' => $this->mLatest
,
1653 'user' => $user->getId(),
1654 'user_text' => $user->getName(),
1658 $revisionId = $revision->insertOn( $dbw );
1662 # Note that we use $this->mLatest instead of fetching a value from the master DB
1663 # during the course of this function. This makes sure that EditPage can detect
1664 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1665 # before this function is called. A previous function used a separate query, this
1666 # creates a window where concurrent edits can cause an ignored edit conflict.
1667 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1670 /* Belated edit conflict! Run away!! */
1671 $status->fatal( 'edit-conflict' );
1672 # Delete the invalid revision if the DB is not transactional
1673 if( !$wgDBtransactions ) {
1674 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1679 global $wgUseRCPatrol;
1680 # Update recentchanges
1681 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1682 # Mark as patrolled if the user can do so
1683 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan('autopatrol');
1684 # Add RC row to the DB
1685 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1686 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1687 $revisionId, $patrolled
1689 # Log auto-patrolled edits
1691 PatrolLog
::record( $rc, true );
1694 # Notify extensions of a new edit
1695 wfRunHooks( 'NewRevisionFromEditComplete', array(&$this, $revision, $baseRevId, $user) );
1696 $user->incEditCount();
1700 $status->warning( 'edit-no-change' );
1702 // Keep the same revision ID, but do some updates on it
1703 $revisionId = $this->getRevIdFetched();
1704 // Update page_touched, this is usually implicit in the page update
1705 // Other cache updates are done in onArticleEdit()
1706 $this->mTitle
->invalidateCache();
1709 if( !$wgDBtransactions ) {
1710 ignore_user_abort( $userAbort );
1712 // Now that ignore_user_abort is restored, we can respond to fatal errors
1713 if( !$status->isOK() ) {
1714 wfProfileOut( __METHOD__
);
1718 # Invalidate cache of this article and all pages using this article
1719 # as a template. Partly deferred.
1720 Article
::onArticleEdit( $this->mTitle
);
1721 # Update links tables, site stats, etc.
1722 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1724 # Create new article
1725 $status->value
['new'] = true;
1727 # Set statistics members
1728 # We work out if it's countable after PST to avoid counter drift
1729 # when articles are created with {{subst:}}
1730 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1731 $this->mTotalAdjustment
= 1;
1735 # Add the page record; stake our claim on this title!
1736 # This will return false if the article already exists
1737 $newid = $this->insertOn( $dbw );
1739 if( $newid === false ) {
1741 $status->fatal( 'edit-already-exists' );
1742 wfProfileOut( __METHOD__
);
1746 # Save the revision text...
1747 $revision = new Revision( array(
1749 'comment' => $summary,
1750 'minor_edit' => $isminor,
1752 'user' => $user->getId(),
1753 'user_text' => $user->getName(),
1755 $revisionId = $revision->insertOn( $dbw );
1757 $this->mTitle
->resetArticleID( $newid );
1759 # Update the page record with revision data
1760 $this->updateRevisionOn( $dbw, $revision, 0 );
1762 # Update recentchanges
1763 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1764 global $wgUseRCPatrol, $wgUseNPPatrol;
1765 # Mark as patrolled if the user can do so
1766 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $this->mTitle
->userCan('autopatrol');
1767 # Add RC row to the DB
1768 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1769 '', strlen($text), $revisionId, $patrolled );
1770 # Log auto-patrolled edits
1772 PatrolLog
::record( $rc, true );
1775 # Notify extensions of a new page edit
1776 wfRunHooks( 'NewRevisionFromEditComplete', array(&$this, $revision, false, $user) );
1777 $user->incEditCount();
1780 # Update links, etc.
1781 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1784 Article
::onArticleCreate( $this->mTitle
);
1786 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1787 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1790 # Do updates right now unless deferral was requested
1791 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1795 // Return the new revision (or null) to the caller
1796 $status->value
['revision'] = $revision;
1798 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1799 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1801 wfProfileOut( __METHOD__
);
1806 * @deprecated wrapper for doRedirect
1808 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1809 wfDeprecated( __METHOD__
);
1810 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1814 * Output a redirect back to the article.
1815 * This is typically used after an edit.
1817 * @param $noRedir Boolean: add redirect=no
1818 * @param $sectionAnchor String: section to redirect to, including "#"
1819 * @param $extraQuery String: extra query params
1821 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1824 $query = 'redirect=no';
1826 $query .= "&$query";
1828 $query = $extraQuery;
1830 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1834 * Mark this particular edit/page as patrolled
1836 public function markpatrolled() {
1837 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1838 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1840 # If we haven't been given an rc_id value, we can't do anything
1841 $rcid = (int) $wgRequest->getVal('rcid');
1842 $rc = RecentChange
::newFromId($rcid);
1843 if( is_null($rc) ) {
1844 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1848 #It would be nice to see where the user had actually come from, but for now just guess
1849 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1850 $return = SpecialPage
::getTitleFor( $returnto );
1852 $dbw = wfGetDB( DB_MASTER
);
1853 $errors = $rc->doMarkPatrolled();
1855 if( in_array(array('rcpatroldisabled'), $errors) ) {
1856 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1860 if( in_array(array('hookaborted'), $errors) ) {
1861 // The hook itself has handled any output
1865 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1866 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1867 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1868 $wgOut->returnToMain( false, $return );
1872 if( !empty($errors) ) {
1873 $wgOut->showPermissionsErrorPage( $errors );
1878 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1879 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1880 $wgOut->returnToMain( false, $return );
1884 * User-interface handler for the "watch" action
1887 public function watch() {
1888 global $wgUser, $wgOut;
1889 if( $wgUser->isAnon() ) {
1890 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1893 if( wfReadOnly() ) {
1894 $wgOut->readOnlyPage();
1897 if( $this->doWatch() ) {
1898 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1899 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1900 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1902 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1906 * Add this page to $wgUser's watchlist
1907 * @return bool true on successful watch operation
1909 public function doWatch() {
1911 if( $wgUser->isAnon() ) {
1914 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1915 $wgUser->addWatch( $this->mTitle
);
1916 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1922 * User interface handler for the "unwatch" action.
1924 public function unwatch() {
1925 global $wgUser, $wgOut;
1926 if( $wgUser->isAnon() ) {
1927 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1930 if( wfReadOnly() ) {
1931 $wgOut->readOnlyPage();
1934 if( $this->doUnwatch() ) {
1935 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1936 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1937 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1939 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1943 * Stop watching a page
1944 * @return bool true on successful unwatch
1946 public function doUnwatch() {
1948 if( $wgUser->isAnon() ) {
1951 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1952 $wgUser->removeWatch( $this->mTitle
);
1953 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1959 * action=protect handler
1961 public function protect() {
1962 $form = new ProtectionForm( $this );
1967 * action=unprotect handler (alias)
1969 public function unprotect() {
1974 * Update the article's restriction field, and leave a log entry.
1976 * @param $limit Array: set of restriction keys
1977 * @param $reason String
1978 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1979 * @param $expiry Array: per restriction type expiration
1980 * @return bool true on success
1982 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1983 global $wgUser, $wgRestrictionTypes, $wgContLang;
1985 $id = $this->mTitle
->getArticleID();
1987 wfDebug( "updateRestrictions failed: $id <= 0\n" );
1991 if ( wfReadOnly() ) {
1992 wfDebug( "updateRestrictions failed: read-only\n" );
1996 if ( !$this->mTitle
->userCan( 'protect' ) ) {
1997 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2005 // Take this opportunity to purge out expired restrictions
2006 Title
::purgeExpiredRestrictions();
2008 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2009 # we expect a single selection, but the schema allows otherwise.
2011 $updated = Article
::flattenRestrictions( $limit );
2013 foreach( $wgRestrictionTypes as $action ) {
2014 if( isset( $expiry[$action] ) ) {
2015 # Get current restrictions on $action
2016 $aLimits = $this->mTitle
->getRestrictions( $action );
2017 $current[$action] = implode( '', $aLimits );
2018 # Are any actual restrictions being dealt with here?
2019 $aRChanged = count($aLimits) ||
!empty($limit[$action]);
2020 # If something changed, we need to log it. Checking $aRChanged
2021 # assures that "unprotecting" a page that is not protected does
2022 # not log just because the expiry was "changed".
2023 if( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2029 $current = Article
::flattenRestrictions( $current );
2031 $changed = ($changed ||
$current != $updated );
2032 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
2033 $protect = ( $updated != '' );
2035 # If nothing's changed, do nothing
2037 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2039 $dbw = wfGetDB( DB_MASTER
);
2041 # Prepare a null revision to be added to the history
2042 $modified = $current != '' && $protect;
2044 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2046 $comment_type = 'unprotectedarticle';
2048 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2050 # Only restrictions with the 'protect' right can cascade...
2051 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2052 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2053 # The schema allows multiple restrictions
2054 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2056 $cascade_description = '';
2058 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2062 $comment .= ": $reason";
2064 $editComment = $comment;
2065 $encodedExpiry = array();
2066 $protect_description = '';
2067 foreach( $limit as $action => $restrictions ) {
2068 if ( !isset($expiry[$action]) )
2069 $expiry[$action] = 'infinite';
2071 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
2072 if( $restrictions != '' ) {
2073 $protect_description .= "[$action=$restrictions] (";
2074 if( $encodedExpiry[$action] != 'infinity' ) {
2075 $protect_description .= wfMsgForContent( 'protect-expiring',
2076 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2077 $wgContLang->date( $expiry[$action], false, false ) ,
2078 $wgContLang->time( $expiry[$action], false, false ) );
2080 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2082 $protect_description .= ') ';
2085 $protect_description = trim($protect_description);
2087 if( $protect_description && $protect )
2088 $editComment .= " ($protect_description)";
2090 $editComment .= "$cascade_description";
2091 # Update restrictions table
2092 foreach( $limit as $action => $restrictions ) {
2093 if($restrictions != '' ) {
2094 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2095 array( 'pr_page' => $id,
2096 'pr_type' => $action,
2097 'pr_level' => $restrictions,
2098 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
2099 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
2101 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2102 'pr_type' => $action ), __METHOD__
);
2106 # Insert a null revision
2107 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2108 $nullRevId = $nullRevision->insertOn( $dbw );
2110 $latest = $this->getLatest();
2111 # Update page record
2112 $dbw->update( 'page',
2114 'page_touched' => $dbw->timestamp(),
2115 'page_restrictions' => '',
2116 'page_latest' => $nullRevId
2117 ), array( /* WHERE */
2119 ), 'Article::protect'
2122 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2123 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2125 # Update the protection log
2126 $log = new LogPage( 'protect' );
2128 $params = array($protect_description,$cascade ?
'cascade' : '');
2129 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
2131 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2135 } # End "changed" check
2141 * Take an array of page restrictions and flatten it to a string
2142 * suitable for insertion into the page_restrictions field.
2143 * @param $limit Array
2146 protected static function flattenRestrictions( $limit ) {
2147 if( !is_array( $limit ) ) {
2148 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2152 foreach( $limit as $action => $restrictions ) {
2153 if( $restrictions != '' ) {
2154 $bits[] = "$action=$restrictions";
2157 return implode( ':', $bits );
2161 * Auto-generates a deletion reason
2162 * @param &$hasHistory Boolean: whether the page has a history
2164 public function generateReason( &$hasHistory ) {
2166 $dbw = wfGetDB( DB_MASTER
);
2167 // Get the last revision
2168 $rev = Revision
::newFromTitle( $this->mTitle
);
2169 if( is_null( $rev ) )
2172 // Get the article's contents
2173 $contents = $rev->getText();
2175 // If the page is blank, use the text from the previous revision,
2176 // which can only be blank if there's a move/import/protect dummy revision involved
2177 if( $contents == '' ) {
2178 $prev = $rev->getPrevious();
2180 $contents = $prev->getText();
2185 // Find out if there was only one contributor
2186 // Only scan the last 20 revisions
2187 $res = $dbw->select( 'revision', 'rev_user_text',
2188 array( 'rev_page' => $this->getID(), 'rev_deleted & '.Revision
::DELETED_USER
.'=0' ),
2190 array( 'LIMIT' => 20 )
2192 if( $res === false )
2193 // This page has no revisions, which is very weird
2196 $hasHistory = ( $res->numRows() > 1 );
2197 $row = $dbw->fetchObject( $res );
2198 $onlyAuthor = $row->rev_user_text
;
2199 // Try to find a second contributor
2200 foreach( $res as $row ) {
2201 if( $row->rev_user_text
!= $onlyAuthor ) {
2202 $onlyAuthor = false;
2206 $dbw->freeResult( $res );
2208 // Generate the summary with a '$1' placeholder
2210 // The current revision is blank and the one before is also
2211 // blank. It's just not our lucky day
2212 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2215 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2217 $reason = wfMsgForContent( 'excontent', '$1' );
2220 if( $reason == '-' ) {
2221 // Allow these UI messages to be blanked out cleanly
2225 // Replace newlines with spaces to prevent uglyness
2226 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2227 // Calculate the maximum amount of chars to get
2228 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2229 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2230 $contents = $wgContLang->truncate( $contents, $maxLength );
2231 // Remove possible unfinished links
2232 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2233 // Now replace the '$1' placeholder
2234 $reason = str_replace( '$1', $contents, $reason );
2240 * UI entry point for page deletion
2242 public function delete() {
2243 global $wgUser, $wgOut, $wgRequest;
2245 $confirm = $wgRequest->wasPosted() &&
2246 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2248 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2249 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2251 $reason = $this->DeleteReasonList
;
2253 if( $reason != 'other' && $this->DeleteReason
!= '' ) {
2254 // Entry from drop down menu + additional comment
2255 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2256 } elseif( $reason == 'other' ) {
2257 $reason = $this->DeleteReason
;
2259 # Flag to hide all contents of the archived revisions
2260 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2262 # This code desperately needs to be totally rewritten
2264 # Read-only check...
2265 if( wfReadOnly() ) {
2266 $wgOut->readOnlyPage();
2271 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2273 if( count( $permission_errors ) > 0 ) {
2274 $wgOut->showPermissionsErrorPage( $permission_errors );
2278 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2280 # Better double-check that it hasn't been deleted yet!
2281 $dbw = wfGetDB( DB_MASTER
);
2282 $conds = $this->mTitle
->pageCond();
2283 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2284 if( $latest === false ) {
2285 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2286 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2287 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2291 # Hack for big sites
2292 $bigHistory = $this->isBigDeletion();
2293 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2294 global $wgLang, $wgDeleteRevisionsLimit;
2295 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2296 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2301 $this->doDelete( $reason, $suppress );
2302 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2304 } elseif( $this->mTitle
->userIsWatching() ) {
2310 // Generate deletion reason
2311 $hasHistory = false;
2312 if( !$reason ) $reason = $this->generateReason($hasHistory);
2314 // If the page has a history, insert a warning
2315 if( $hasHistory && !$confirm ) {
2316 $skin = $wgUser->getSkin();
2317 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2319 global $wgLang, $wgDeleteRevisionsLimit;
2320 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2321 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2325 return $this->confirmDelete( $reason );
2329 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2331 public function isBigDeletion() {
2332 global $wgDeleteRevisionsLimit;
2333 if( $wgDeleteRevisionsLimit ) {
2334 $revCount = $this->estimateRevisionCount();
2335 return $revCount > $wgDeleteRevisionsLimit;
2341 * @return int approximate revision count
2343 public function estimateRevisionCount() {
2344 $dbr = wfGetDB( DB_SLAVE
);
2345 // For an exact count...
2346 //return $dbr->selectField( 'revision', 'COUNT(*)',
2347 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2348 return $dbr->estimateRowCount( 'revision', '*',
2349 array( 'rev_page' => $this->getId() ), __METHOD__
);
2353 * Get the last N authors
2354 * @param $num Integer: number of revisions to get
2355 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2356 * @return array Array of authors, duplicates not removed
2358 public function getLastNAuthors( $num, $revLatest = 0 ) {
2359 wfProfileIn( __METHOD__
);
2360 // First try the slave
2361 // If that doesn't have the latest revision, try the master
2363 $db = wfGetDB( DB_SLAVE
);
2365 $res = $db->select( array( 'page', 'revision' ),
2366 array( 'rev_id', 'rev_user_text' ),
2368 'page_namespace' => $this->mTitle
->getNamespace(),
2369 'page_title' => $this->mTitle
->getDBkey(),
2370 'rev_page = page_id'
2371 ), __METHOD__
, $this->getSelectOptions( array(
2372 'ORDER BY' => 'rev_timestamp DESC',
2377 wfProfileOut( __METHOD__
);
2380 $row = $db->fetchObject( $res );
2381 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2382 $db = wfGetDB( DB_MASTER
);
2387 } while ( $continue );
2389 $authors = array( $row->rev_user_text
);
2390 while ( $row = $db->fetchObject( $res ) ) {
2391 $authors[] = $row->rev_user_text
;
2393 wfProfileOut( __METHOD__
);
2398 * Output deletion confirmation dialog
2399 * @param $reason String: prefilled reason
2401 public function confirmDelete( $reason ) {
2402 global $wgOut, $wgUser;
2404 wfDebug( "Article::confirmDelete\n" );
2406 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2407 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2408 $wgOut->addWikiMsg( 'confirmdeletetext' );
2410 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2411 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2413 <td class='mw-input'><strong>" .
2414 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2415 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2421 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2423 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2424 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2425 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2426 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2427 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2428 "<tr id=\"wpDeleteReasonListRow\">
2429 <td class='mw-label'>" .
2430 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2432 <td class='mw-input'>" .
2433 Xml
::listDropDown( 'wpDeleteReasonList',
2434 wfMsgForContent( 'deletereason-dropdown' ),
2435 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2438 <tr id=\"wpDeleteReasonRow\">
2439 <td class='mw-label'>" .
2440 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2442 <td class='mw-input'>" .
2443 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2444 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2449 <td class='mw-input'>" .
2450 Xml
::checkLabel( wfMsg( 'watchthis' ),
2451 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2457 <td class='mw-submit'>" .
2458 Xml
::submitButton( wfMsg( 'deletepage' ),
2459 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2462 Xml
::closeElement( 'table' ) .
2463 Xml
::closeElement( 'fieldset' ) .
2464 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2465 Xml
::closeElement( 'form' );
2467 if( $wgUser->isAllowed( 'editinterface' ) ) {
2468 $skin = $wgUser->getSkin();
2469 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2470 $link = $skin->link(
2472 wfMsgHtml( 'delete-edit-reasonlist' ),
2474 array( 'action' => 'edit' )
2476 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2479 $wgOut->addHTML( $form );
2480 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2484 * Perform a deletion and output success or failure messages
2486 public function doDelete( $reason, $suppress = false ) {
2487 global $wgOut, $wgUser;
2488 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2491 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2492 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2493 $deleted = $this->mTitle
->getPrefixedText();
2495 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2496 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2498 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2500 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2501 $wgOut->returnToMain( false );
2502 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2504 if( $error == '' ) {
2505 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2506 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2507 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2509 $wgOut->showFatalError( $error );
2516 * Back-end article deletion
2517 * Deletes the article with database consistency, writes logs, purges caches
2520 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2521 global $wgUseSquid, $wgDeferredUpdateList;
2522 global $wgUseTrackbacks;
2524 wfDebug( __METHOD__
."\n" );
2526 $dbw = wfGetDB( DB_MASTER
);
2527 $ns = $this->mTitle
->getNamespace();
2528 $t = $this->mTitle
->getDBkey();
2529 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2531 if( $t == '' ||
$id == 0 ) {
2535 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2536 array_push( $wgDeferredUpdateList, $u );
2538 // Bitfields to further suppress the content
2541 // This should be 15...
2542 $bitfield |
= Revision
::DELETED_TEXT
;
2543 $bitfield |
= Revision
::DELETED_COMMENT
;
2544 $bitfield |
= Revision
::DELETED_USER
;
2545 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2547 $bitfield = 'rev_deleted';
2551 // For now, shunt the revision data into the archive table.
2552 // Text is *not* removed from the text table; bulk storage
2553 // is left intact to avoid breaking block-compression or
2554 // immutable storage schemes.
2556 // For backwards compatibility, note that some older archive
2557 // table entries will have ar_text and ar_flags fields still.
2559 // In the future, we may keep revisions and mark them with
2560 // the rev_deleted field, which is reserved for this purpose.
2561 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2563 'ar_namespace' => 'page_namespace',
2564 'ar_title' => 'page_title',
2565 'ar_comment' => 'rev_comment',
2566 'ar_user' => 'rev_user',
2567 'ar_user_text' => 'rev_user_text',
2568 'ar_timestamp' => 'rev_timestamp',
2569 'ar_minor_edit' => 'rev_minor_edit',
2570 'ar_rev_id' => 'rev_id',
2571 'ar_text_id' => 'rev_text_id',
2572 'ar_text' => '\'\'', // Be explicit to appease
2573 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2574 'ar_len' => 'rev_len',
2575 'ar_page_id' => 'page_id',
2576 'ar_deleted' => $bitfield
2579 'page_id = rev_page'
2583 # Delete restrictions for it
2584 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2586 # Now that it's safely backed up, delete it
2587 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2588 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2594 # Fix category table counts
2596 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2597 foreach( $res as $row ) {
2598 $cats []= $row->cl_to
;
2600 $this->updateCategoryCounts( array(), $cats );
2602 # If using cascading deletes, we can skip some explicit deletes
2603 if( !$dbw->cascadingDeletes() ) {
2604 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2606 if($wgUseTrackbacks)
2607 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2609 # Delete outgoing links
2610 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2611 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2612 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2613 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2614 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2615 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2616 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2619 # If using cleanup triggers, we can skip some manual deletes
2620 if( !$dbw->cleanupTriggers() ) {
2621 # Clean up recentchanges entries...
2622 $dbw->delete( 'recentchanges',
2623 array( 'rc_type != '.RC_LOG
,
2624 'rc_namespace' => $this->mTitle
->getNamespace(),
2625 'rc_title' => $this->mTitle
->getDBkey() ),
2627 $dbw->delete( 'recentchanges',
2628 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2633 Article
::onArticleDelete( $this->mTitle
);
2635 # Clear the cached article id so the interface doesn't act like we exist
2636 $this->mTitle
->resetArticleID( 0 );
2638 # Log the deletion, if the page was suppressed, log it at Oversight instead
2639 $logtype = $suppress ?
'suppress' : 'delete';
2640 $log = new LogPage( $logtype );
2642 # Make sure logging got through
2643 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2651 * Roll back the most recent consecutive set of edits to a page
2652 * from the same user; fails if there are no eligible edits to
2653 * roll back to, e.g. user is the sole contributor. This function
2654 * performs permissions checks on $wgUser, then calls commitRollback()
2655 * to do the dirty work
2657 * @param $fromP String: Name of the user whose edits to rollback.
2658 * @param $summary String: Custom summary. Set to default summary if empty.
2659 * @param $token String: Rollback token.
2660 * @param $bot Boolean: If true, mark all reverted edits as bot.
2662 * @param $resultDetails Array: contains result-specific array of additional values
2663 * 'alreadyrolled' : 'current' (rev)
2664 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2666 * @return array of errors, each error formatted as
2667 * array(messagekey, param1, param2, ...).
2668 * On success, the array is empty. This array can also be passed to
2669 * OutputPage::showPermissionsErrorPage().
2671 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2673 $resultDetails = null;
2676 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2677 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2678 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2680 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2681 $errors[] = array( 'sessionfailure' );
2683 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2684 $errors[] = array( 'actionthrottledtext' );
2686 # If there were errors, bail out now
2687 if( !empty( $errors ) )
2690 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2694 * Backend implementation of doRollback(), please refer there for parameter
2695 * and return value documentation
2697 * NOTE: This function does NOT check ANY permissions, it just commits the
2698 * rollback to the DB Therefore, you should only call this function direct-
2699 * ly if you want to use custom permissions checks. If you don't, use
2700 * doRollback() instead.
2702 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2703 global $wgUseRCPatrol, $wgUser, $wgLang;
2704 $dbw = wfGetDB( DB_MASTER
);
2706 if( wfReadOnly() ) {
2707 return array( array( 'readonlytext' ) );
2710 # Get the last editor
2711 $current = Revision
::newFromTitle( $this->mTitle
);
2712 if( is_null( $current ) ) {
2713 # Something wrong... no page?
2714 return array(array('notanarticle'));
2717 $from = str_replace( '_', ' ', $fromP );
2718 if( $from != $current->getUserText() ) {
2719 $resultDetails = array( 'current' => $current );
2720 return array(array('alreadyrolled',
2721 htmlspecialchars($this->mTitle
->getPrefixedText()),
2722 htmlspecialchars($fromP),
2723 htmlspecialchars($current->getUserText())
2727 # Get the last edit not by this guy
2728 $user = intval( $current->getUser() );
2729 $user_text = $dbw->addQuotes( $current->getUserText() );
2730 $s = $dbw->selectRow( 'revision',
2731 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2732 array( 'rev_page' => $current->getPage(),
2733 "rev_user != {$user} OR rev_user_text != {$user_text}"
2735 array( 'USE INDEX' => 'page_timestamp',
2736 'ORDER BY' => 'rev_timestamp DESC' )
2738 if( $s === false ) {
2739 # No one else ever edited this page
2740 return array(array('cantrollback'));
2741 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2742 # Only admins can see this text
2743 return array(array('notvisiblerev'));
2747 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2748 # Mark all reverted edits as bot
2751 if( $wgUseRCPatrol ) {
2752 # Mark all reverted edits as patrolled
2753 $set['rc_patrolled'] = 1;
2757 $dbw->update( 'recentchanges', $set,
2759 'rc_cur_id' => $current->getPage(),
2760 'rc_user_text' => $current->getUserText(),
2761 "rc_timestamp > '{$s->rev_timestamp}'",
2766 # Generate the edit summary if necessary
2767 $target = Revision
::newFromId( $s->rev_id
);
2768 if( empty( $summary ) ){
2769 $summary = wfMsgForContent( 'revertpage' );
2772 # Allow the custom summary to use the same args as the default message
2774 $target->getUserText(), $from, $s->rev_id
,
2775 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2776 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2778 $summary = wfMsgReplaceArgs( $summary, $args );
2781 $flags = EDIT_UPDATE
;
2783 if( $wgUser->isAllowed('minoredit') )
2784 $flags |
= EDIT_MINOR
;
2786 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2787 $flags |
= EDIT_FORCE_BOT
;
2788 # Actually store the edit
2789 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2790 if( !empty( $status->value
['revision'] ) ) {
2791 $revId = $status->value
['revision']->getId();
2796 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2798 $resultDetails = array(
2799 'summary' => $summary,
2800 'current' => $current,
2801 'target' => $target,
2808 * User interface for rollback operations
2810 public function rollback() {
2811 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2814 $result = $this->doRollback(
2815 $wgRequest->getVal( 'from' ),
2816 $wgRequest->getText( 'summary' ),
2817 $wgRequest->getVal( 'token' ),
2818 $wgRequest->getBool( 'bot' ),
2822 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2823 $wgOut->rateLimited();
2826 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2827 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2828 $errArray = $result[0];
2829 $errMsg = array_shift( $errArray );
2830 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2831 if( isset( $details['current'] ) ){
2832 $current = $details['current'];
2833 if( $current->getComment() != '' ) {
2834 $wgOut->addWikiMsgArray( 'editcomment', array(
2835 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2840 # Display permissions errors before read-only message -- there's no
2841 # point in misleading the user into thinking the inability to rollback
2842 # is only temporary.
2843 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2844 # array_diff is completely broken for arrays of arrays, sigh. Re-
2845 # move any 'readonlytext' error manually.
2847 foreach( $result as $error ) {
2848 if( $error != array( 'readonlytext' ) ) {
2852 $wgOut->showPermissionsErrorPage( $out );
2855 if( $result == array( array( 'readonlytext' ) ) ) {
2856 $wgOut->readOnlyPage();
2860 $current = $details['current'];
2861 $target = $details['target'];
2862 $newId = $details['newid'];
2863 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2864 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2865 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2866 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2867 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2868 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2869 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2870 $wgOut->returnToMain( false, $this->mTitle
);
2872 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2873 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2874 $de->showDiff( '', '' );
2880 * Do standard deferred updates after page view
2882 public function viewUpdates() {
2883 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2884 # Don't update page view counters on views from bot users (bug 14044)
2885 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2886 Article
::incViewCount( $this->getID() );
2887 $u = new SiteStatsUpdate( 1, 0, 0 );
2888 array_push( $wgDeferredUpdateList, $u );
2890 # Update newtalk / watchlist notification status
2891 $wgUser->clearNotification( $this->mTitle
);
2895 * Prepare text which is about to be saved.
2896 * Returns a stdclass with source, pst and output members
2898 public function prepareTextForEdit( $text, $revid=null ) {
2899 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2901 return $this->mPreparedEdit
;
2904 $edit = (object)array();
2905 $edit->revid
= $revid;
2906 $edit->newText
= $text;
2907 $edit->pst
= $this->preSaveTransform( $text );
2908 $options = new ParserOptions
;
2909 $options->setTidy( true );
2910 $options->enableLimitReport();
2911 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2912 $edit->oldText
= $this->getContent();
2913 $this->mPreparedEdit
= $edit;
2918 * Do standard deferred updates after page edit.
2919 * Update links tables, site stats, search index and message cache.
2920 * Purges pages that include this page if the text was changed here.
2921 * Every 100th edit, prune the recent changes table.
2924 * @param $text New text of the article
2925 * @param $summary Edit summary
2926 * @param $minoredit Minor edit
2927 * @param $timestamp_of_pagechange Timestamp associated with the page change
2928 * @param $newid rev_id value of the new revision
2929 * @param $changed Whether or not the content actually changed
2931 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2932 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2934 wfProfileIn( __METHOD__
);
2937 # Be careful not to double-PST: $text is usually already PST-ed once
2938 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2939 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2940 $editInfo = $this->prepareTextForEdit( $text, $newid );
2942 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2943 $editInfo = $this->mPreparedEdit
;
2946 # Save it to the parser cache
2947 if( $wgEnableParserCache ) {
2948 $popts = new ParserOptions
;
2949 $popts->setTidy( true );
2950 $popts->enableLimitReport();
2951 $parserCache = ParserCache
::singleton();
2952 $parserCache->save( $editInfo->output
, $this, $popts );
2955 # Update the links tables
2956 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2959 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2961 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2962 if( 0 == mt_rand( 0, 99 ) ) {
2963 // Flush old entries from the `recentchanges` table; we do this on
2964 // random requests so as to avoid an increase in writes for no good reason
2966 $dbw = wfGetDB( DB_MASTER
);
2967 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2968 $recentchanges = $dbw->tableName( 'recentchanges' );
2969 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2970 $dbw->query( $sql );
2974 $id = $this->getID();
2975 $title = $this->mTitle
->getPrefixedDBkey();
2976 $shortTitle = $this->mTitle
->getDBkey();
2979 wfProfileOut( __METHOD__
);
2983 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2984 array_push( $wgDeferredUpdateList, $u );
2985 $u = new SearchUpdate( $id, $title, $text );
2986 array_push( $wgDeferredUpdateList, $u );
2988 # If this is another user's talk page, update newtalk
2989 # Don't do this if $changed = false otherwise some idiot can null-edit a
2990 # load of user talk pages and piss people off, nor if it's a minor edit
2991 # by a properly-flagged bot.
2992 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2993 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2994 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2995 $other = User
::newFromName( $shortTitle, false );
2997 wfDebug( __METHOD__
.": invalid username\n" );
2998 } elseif( User
::isIP( $shortTitle ) ) {
2999 // An anonymous user
3000 $other->setNewtalk( true );
3001 } elseif( $other->isLoggedIn() ) {
3002 $other->setNewtalk( true );
3004 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3009 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3010 $wgMessageCache->replace( $shortTitle, $text );
3013 wfProfileOut( __METHOD__
);
3017 * Perform article updates on a special page creation.
3019 * @param $rev Revision object
3021 * @todo This is a shitty interface function. Kill it and replace the
3022 * other shitty functions like editUpdates and such so it's not needed
3025 public function createUpdates( $rev ) {
3026 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3027 $this->mTotalAdjustment
= 1;
3028 $this->editUpdates( $rev->getText(), $rev->getComment(),
3029 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3033 * Generate the navigation links when browsing through an article revisions
3034 * It shows the information as:
3035 * Revision as of \<date\>; view current revision
3036 * \<- Previous version | Next Version -\>
3038 * @param $oldid String: revision ID of this article revision
3040 public function setOldSubtitle( $oldid = 0 ) {
3041 global $wgLang, $wgOut, $wgUser, $wgRequest;
3043 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3047 $revision = Revision
::newFromId( $oldid );
3049 $current = ( $oldid == $this->mLatest
);
3050 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3051 $sk = $wgUser->getSkin();
3053 ?
wfMsgHtml( 'currentrevisionlink' )
3054 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'currentrevisionlink' ) );
3056 ?
wfMsgHtml( 'diff' )
3057 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
3058 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3060 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
3061 : wfMsgHtml( 'previousrevision' );
3063 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
3064 : wfMsgHtml( 'diff' );
3065 $nextlink = $current
3066 ?
wfMsgHtml( 'nextrevision' )
3067 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
3068 $nextdiff = $current
3069 ?
wfMsgHtml( 'diff' )
3070 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
3073 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3074 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
3075 if( $revision->isCurrent() ) {
3076 // We don't handle top deleted edits too well
3077 $cdel = wfMsgHtml( 'rev-delundel' );
3078 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3079 // If revision was hidden from sysops
3080 $cdel = wfMsgHtml( 'rev-delundel' );
3082 $cdel = $sk->makeKnownLinkObj( $revdel,
3083 wfMsgHtml('rev-delundel'),
3085 '&target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
3086 '&ids=' . urlencode( $oldid ) );
3087 // Bolden oversighted content
3088 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
3089 $cdel = "<strong>$cdel</strong>";
3091 $cdel = "(<small>$cdel</small>) ";
3093 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3094 # Show user links if allowed to see them. If hidden, then show them only if requested...
3095 $userlinks = $sk->revUserTools( $revision, !$unhide );
3097 $m = wfMsg( 'revision-info-current' );
3098 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3099 ?
'revision-info-current'
3102 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ),
3103 $td, $userlinks, $revision->getID() ) . "</div>\n" .
3105 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3106 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3107 $wgOut->setSubtitle( $r );
3111 * This function is called right before saving the wikitext,
3112 * so we can do things like signatures and links-in-context.
3114 * @param $text String
3116 public function preSaveTransform( $text ) {
3117 global $wgParser, $wgUser;
3118 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3121 /* Caching functions */
3124 * checkLastModified returns true if it has taken care of all
3125 * output to the client that is necessary for this request.
3126 * (that is, it has sent a cached version of the page)
3128 protected function tryFileCache() {
3129 static $called = false;
3131 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3135 if( $this->isFileCacheable() ) {
3136 $cache = new HTMLFileCache( $this->mTitle
);
3137 if( $cache->isFileCacheGood( $this->mTouched
) ) {
3138 wfDebug( "Article::tryFileCache(): about to load file\n" );
3139 $cache->loadFromFileCache();
3142 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3143 ob_start( array(&$cache, 'saveToFileCache' ) );
3146 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3152 * Check if the page can be cached
3155 public function isFileCacheable() {
3157 if( HTMLFileCache
::useFileCache() ) {
3158 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3159 // Extension may have reason to disable file caching on some pages.
3161 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3168 * Loads page_touched and returns a value indicating if it should be used
3171 public function checkTouched() {
3172 if( !$this->mDataLoaded
) {
3173 $this->loadPageData();
3175 return !$this->mIsRedirect
;
3179 * Get the page_touched field
3181 public function getTouched() {
3182 # Ensure that page data has been loaded
3183 if( !$this->mDataLoaded
) {
3184 $this->loadPageData();
3186 return $this->mTouched
;
3190 * Get the page_latest field
3192 public function getLatest() {
3193 if( !$this->mDataLoaded
) {
3194 $this->loadPageData();
3196 return (int)$this->mLatest
;
3200 * Edit an article without doing all that other stuff
3201 * The article must already exist; link tables etc
3202 * are not updated, caches are not flushed.
3204 * @param $text String: text submitted
3205 * @param $comment String: comment submitted
3206 * @param $minor Boolean: whereas it's a minor modification
3208 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3209 wfProfileIn( __METHOD__
);
3211 $dbw = wfGetDB( DB_MASTER
);
3212 $revision = new Revision( array(
3213 'page' => $this->getId(),
3215 'comment' => $comment,
3216 'minor_edit' => $minor ?
1 : 0,
3218 $revision->insertOn( $dbw );
3219 $this->updateRevisionOn( $dbw, $revision );
3221 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3223 wfProfileOut( __METHOD__
);
3227 * Used to increment the view counter
3229 * @param $id Integer: article id
3231 public static function incViewCount( $id ) {
3232 $id = intval( $id );
3233 global $wgHitcounterUpdateFreq, $wgDBtype;
3235 $dbw = wfGetDB( DB_MASTER
);
3236 $pageTable = $dbw->tableName( 'page' );
3237 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3238 $acchitsTable = $dbw->tableName( 'acchits' );
3240 if( $wgHitcounterUpdateFreq <= 1 ) {
3241 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3245 # Not important enough to warrant an error page in case of failure
3246 $oldignore = $dbw->ignoreErrors( true );
3248 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3250 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3251 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3252 # Most of the time (or on SQL errors), skip row count check
3253 $dbw->ignoreErrors( $oldignore );
3257 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3258 $row = $dbw->fetchObject( $res );
3259 $rown = intval( $row->n
);
3260 if( $rown >= $wgHitcounterUpdateFreq ){
3261 wfProfileIn( 'Article::incViewCount-collect' );
3262 $old_user_abort = ignore_user_abort( true );
3264 if($wgDBtype == 'mysql')
3265 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3266 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3267 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3268 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3270 $dbw->query("DELETE FROM $hitcounterTable");
3271 if($wgDBtype == 'mysql') {
3272 $dbw->query('UNLOCK TABLES');
3273 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3274 'WHERE page_id = hc_id');
3277 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3278 "FROM $acchitsTable WHERE page_id = hc_id");
3280 $dbw->query("DROP TABLE $acchitsTable");
3282 ignore_user_abort( $old_user_abort );
3283 wfProfileOut( 'Article::incViewCount-collect' );
3285 $dbw->ignoreErrors( $oldignore );
3289 * The onArticle*() functions are supposed to be a kind of hooks
3290 * which should be called whenever any of the specified actions
3293 * This is a good place to put code to clear caches, for instance.
3295 * This is called on page move and undelete, as well as edit
3297 * @param $title a title object
3300 public static function onArticleCreate( $title ) {
3301 # Update existence markers on article/talk tabs...
3302 if( $title->isTalkPage() ) {
3303 $other = $title->getSubjectPage();
3305 $other = $title->getTalkPage();
3307 $other->invalidateCache();
3308 $other->purgeSquid();
3310 $title->touchLinks();
3311 $title->purgeSquid();
3312 $title->deleteTitleProtection();
3315 public static function onArticleDelete( $title ) {
3316 global $wgMessageCache;
3317 # Update existence markers on article/talk tabs...
3318 if( $title->isTalkPage() ) {
3319 $other = $title->getSubjectPage();
3321 $other = $title->getTalkPage();
3323 $other->invalidateCache();
3324 $other->purgeSquid();
3326 $title->touchLinks();
3327 $title->purgeSquid();
3330 HTMLFileCache
::clearFileCache( $title );
3333 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3334 $wgMessageCache->replace( $title->getDBkey(), false );
3337 if( $title->getNamespace() == NS_FILE
) {
3338 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3339 $update->doUpdate();
3342 if( $title->getNamespace() == NS_USER_TALK
) {
3343 $user = User
::newFromName( $title->getText(), false );
3344 $user->setNewtalk( false );
3347 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3351 * Purge caches on page update etc
3353 public static function onArticleEdit( $title, $flags = '' ) {
3354 global $wgDeferredUpdateList;
3356 // Invalidate caches of articles which include this page
3357 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3359 // Invalidate the caches of all pages which redirect here
3360 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3362 # Purge squid for this page only
3363 $title->purgeSquid();
3365 # Clear file cache for this page only
3366 HTMLFileCache
::clearFileCache( $title );
3372 * Overriden by ImagePage class, only present here to avoid a fatal error
3373 * Called for ?action=revert
3375 public function revert() {
3377 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3381 * Info about this page
3382 * Called for ?action=info when $wgAllowPageInfo is on.
3384 public function info() {
3385 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3387 if( !$wgAllowPageInfo ) {
3388 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3392 $page = $this->mTitle
->getSubjectPage();
3394 $wgOut->setPagetitle( $page->getPrefixedText() );
3395 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3396 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3398 if( !$this->mTitle
->exists() ) {
3399 $wgOut->addHTML( '<div class="noarticletext">' );
3400 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3401 // This doesn't quite make sense; the user is asking for
3402 // information about the _page_, not the message... -- RC
3403 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3405 $msg = $wgUser->isLoggedIn()
3407 : 'noarticletextanon';
3408 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3410 $wgOut->addHTML( '</div>' );
3412 $dbr = wfGetDB( DB_SLAVE
);
3414 'wl_title' => $page->getDBkey(),
3415 'wl_namespace' => $page->getNamespace() );
3416 $numwatchers = $dbr->selectField(
3421 $this->getSelectOptions() );
3423 $pageInfo = $this->pageCountInfo( $page );
3424 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3426 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3427 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3429 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3431 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3433 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3435 $wgOut->addHTML( '</ul>' );
3440 * Return the total number of edits and number of unique editors
3441 * on a given page. If page does not exist, returns false.
3443 * @param $title Title object
3446 public function pageCountInfo( $title ) {
3447 $id = $title->getArticleId();
3451 $dbr = wfGetDB( DB_SLAVE
);
3452 $rev_clause = array( 'rev_page' => $id );
3453 $edits = $dbr->selectField(
3458 $this->getSelectOptions()
3460 $authors = $dbr->selectField(
3462 'COUNT(DISTINCT rev_user_text)',
3465 $this->getSelectOptions()
3467 return array( 'edits' => $edits, 'authors' => $authors );
3471 * Return a list of templates used by this article.
3472 * Uses the templatelinks table
3474 * @return Array of Title objects
3476 public function getUsedTemplates() {
3478 $id = $this->mTitle
->getArticleID();
3482 $dbr = wfGetDB( DB_SLAVE
);
3483 $res = $dbr->select( array( 'templatelinks' ),
3484 array( 'tl_namespace', 'tl_title' ),
3485 array( 'tl_from' => $id ),
3487 if( $res !== false ) {
3488 foreach( $res as $row ) {
3489 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3492 $dbr->freeResult( $res );
3497 * Returns a list of hidden categories this page is a member of.
3498 * Uses the page_props and categorylinks tables.
3500 * @return Array of Title objects
3502 public function getHiddenCategories() {
3504 $id = $this->mTitle
->getArticleID();
3508 $dbr = wfGetDB( DB_SLAVE
);
3509 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3511 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3512 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3514 if( $res !== false ) {
3515 foreach( $res as $row ) {
3516 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3519 $dbr->freeResult( $res );
3524 * Return an applicable autosummary if one exists for the given edit.
3525 * @param $oldtext String: the previous text of the page.
3526 * @param $newtext String: The submitted text of the page.
3527 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3528 * @return string An appropriate autosummary, or an empty string.
3530 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3531 # Decide what kind of autosummary is needed.
3533 # Redirect autosummaries
3534 $ot = Title
::newFromRedirect( $oldtext );
3535 $rt = Title
::newFromRedirect( $newtext );
3536 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3537 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3540 # New page autosummaries
3541 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3542 # If they're making a new article, give its text, truncated, in the summary.
3544 $truncatedtext = $wgContLang->truncate(
3545 str_replace("\n", ' ', $newtext),
3546 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3547 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3550 # Blanking autosummaries
3551 if( $oldtext != '' && $newtext == '' ) {
3552 return wfMsgForContent( 'autosumm-blank' );
3553 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3554 # Removing more than 90% of the article
3556 $truncatedtext = $wgContLang->truncate(
3558 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3559 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3562 # If we reach this point, there's no applicable autosummary for our case, so our
3563 # autosummary is empty.
3568 * Add the primary page-view wikitext to the output buffer
3569 * Saves the text into the parser cache if possible.
3570 * Updates templatelinks if it is out of date.
3572 * @param $text String
3573 * @param $cache Boolean
3575 public function outputWikiText( $text, $cache = true ) {
3576 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3578 $popts = $wgOut->parserOptions();
3579 $popts->setTidy(true);
3580 $popts->enableLimitReport();
3581 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3582 $popts, true, true, $this->getRevIdFetched() );
3583 $popts->setTidy(false);
3584 $popts->enableLimitReport( false );
3585 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3586 $parserCache = ParserCache
::singleton();
3587 $parserCache->save( $parserOutput, $this, $popts );
3589 // Make sure file cache is not used on uncacheable content.
3590 // Output that has magic words in it can still use the parser cache
3591 // (if enabled), though it will generally expire sooner.
3592 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3593 $wgUseFileCache = false;
3596 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3597 // templatelinks table may have become out of sync,
3598 // especially if using variable-based transclusions.
3599 // For paranoia, check if things have changed and if
3600 // so apply updates to the database. This will ensure
3601 // that cascaded protections apply as soon as the changes
3604 # Get templates from templatelinks
3605 $id = $this->mTitle
->getArticleID();
3607 $tlTemplates = array();
3609 $dbr = wfGetDB( DB_SLAVE
);
3610 $res = $dbr->select( array( 'templatelinks' ),
3611 array( 'tl_namespace', 'tl_title' ),
3612 array( 'tl_from' => $id ),
3616 foreach( $res as $row ) {
3617 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3620 # Get templates from parser output.
3621 $poTemplates = array();
3622 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3623 foreach ( $templates as $dbk => $id ) {
3624 $poTemplates["$ns:$dbk"] = true;
3629 # Note that we simulate array_diff_key in PHP <5.0.x
3630 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3632 if( count( $templates_diff ) > 0 ) {
3633 # Whee, link updates time.
3634 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3639 $wgOut->addParserOutput( $parserOutput );
3643 * Update all the appropriate counts in the category table, given that
3644 * we've added the categories $added and deleted the categories $deleted.
3646 * @param $added array The names of categories that were added
3647 * @param $deleted array The names of categories that were deleted
3650 public function updateCategoryCounts( $added, $deleted ) {
3651 $ns = $this->mTitle
->getNamespace();
3652 $dbw = wfGetDB( DB_MASTER
);
3654 # First make sure the rows exist. If one of the "deleted" ones didn't
3655 # exist, we might legitimately not create it, but it's simpler to just
3656 # create it and then give it a negative value, since the value is bogus
3659 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3660 $insertCats = array_merge( $added, $deleted );
3661 if( !$insertCats ) {
3662 # Okay, nothing to do
3665 $insertRows = array();
3666 foreach( $insertCats as $cat ) {
3667 $insertRows[] = array( 'cat_title' => $cat );
3669 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3671 $addFields = array( 'cat_pages = cat_pages + 1' );
3672 $removeFields = array( 'cat_pages = cat_pages - 1' );
3673 if( $ns == NS_CATEGORY
) {
3674 $addFields[] = 'cat_subcats = cat_subcats + 1';
3675 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3676 } elseif( $ns == NS_FILE
) {
3677 $addFields[] = 'cat_files = cat_files + 1';
3678 $removeFields[] = 'cat_files = cat_files - 1';
3685 array( 'cat_title' => $added ),
3693 array( 'cat_title' => $deleted ),