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 = ''; //!<
43 var $mParserOptions; //!<
47 * Constructor and clear the article
48 * @param $title Reference to a Title object.
49 * @param $oldId Integer revision ID, null to fetch from request, zero for current
51 public function __construct( Title
$title, $oldId = null ) {
52 $this->mTitle
=& $title;
53 $this->mOldId
= $oldId;
57 * Constructor from an article article
58 * @param $id The article ID to load
60 public static function newFromID( $id ) {
61 $t = Title
::newFromID( $id );
62 return $t == null ?
null : new Article( $t );
66 * Tell the page view functions that this view was redirected
67 * from another page on the wiki.
68 * @param $from Title object.
70 public function setRedirectedFrom( $from ) {
71 $this->mRedirectedFrom
= $from;
75 * If this page is a redirect, get its target
77 * The target will be fetched from the redirect table if possible.
78 * If this page doesn't have an entry there, call insertRedirect()
79 * @return mixed Title object, or null if this page is not a redirect
81 public function getRedirectTarget() {
82 if( !$this->mTitle ||
!$this->mTitle
->isRedirect() )
84 if( !is_null($this->mRedirectTarget
) )
85 return $this->mRedirectTarget
;
86 # Query the redirect table
87 $dbr = wfGetDB( DB_SLAVE
);
88 $row = $dbr->selectRow( 'redirect',
89 array('rd_namespace', 'rd_title'),
90 array('rd_from' => $this->getID() ),
94 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
96 # This page doesn't have an entry in the redirect table
97 return $this->mRedirectTarget
= $this->insertRedirect();
101 * Insert an entry for this page into the redirect table.
103 * Don't call this function directly unless you know what you're doing.
104 * @return Title object
106 public function insertRedirect() {
107 $retval = Title
::newFromRedirect( $this->getContent() );
111 $dbw = wfGetDB( DB_MASTER
);
112 $dbw->replace( 'redirect', array('rd_from'),
114 'rd_from' => $this->getID(),
115 'rd_namespace' => $retval->getNamespace(),
116 'rd_title' => $retval->getDBkey()
124 * Get the Title object this page redirects to
126 * @return mixed false, Title of in-wiki target, or string with URL
128 public function followRedirect() {
129 $text = $this->getContent();
130 return $this->followRedirectText( $text );
134 * Get the Title object this text redirects to
136 * @return mixed false, Title of in-wiki target, or string with URL
138 public function followRedirectText( $text ) {
139 $rt = Title
::newFromRedirectRecurse( $text ); // recurse through to only get the final target
140 # process if title object is valid and not special:userlogout
142 if( $rt->getInterwiki() != '' ) {
143 if( $rt->isLocal() ) {
144 // Offsite wikis need an HTTP redirect.
146 // This can be hard to reverse and may produce loops,
147 // so they may be disabled in the site configuration.
148 $source = $this->mTitle
->getFullURL( 'redirect=no' );
149 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
152 if( $rt->getNamespace() == NS_SPECIAL
) {
153 // Gotta handle redirects to special pages differently:
154 // Fill the HTTP response "Location" header and ignore
155 // the rest of the page we're on.
157 // This can be hard to reverse, so they may be disabled.
158 if( $rt->isSpecial( 'Userlogout' ) ) {
161 return $rt->getFullURL();
167 // No or invalid redirect
172 * get the title object of the article
174 public function getTitle() {
175 return $this->mTitle
;
182 public function clear() {
183 $this->mDataLoaded
= false;
184 $this->mContentLoaded
= false;
186 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
187 $this->mRedirectedFrom
= null; # Title object if set
188 $this->mRedirectTarget
= null; # Title object if set
190 $this->mTimestamp
= $this->mComment
= '';
191 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
192 $this->mTouched
= '19700101000000';
193 $this->mForUpdate
= false;
194 $this->mIsRedirect
= false;
195 $this->mRevIdFetched
= 0;
196 $this->mRedirectUrl
= false;
197 $this->mLatest
= false;
198 $this->mPreparedEdit
= false;
202 * Note that getContent/loadContent do not follow redirects anymore.
203 * If you need to fetch redirectable content easily, try
204 * the shortcut in Article::followContent()
206 * @return Return the text of this revision
208 public function getContent() {
209 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
210 wfProfileIn( __METHOD__
);
211 if( $this->getID() === 0 ) {
212 # If this is a MediaWiki:x message, then load the messages
213 # and return the message value for x.
214 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
215 # If this is a system message, get the default text.
216 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
217 $wgMessageCache->loadAllMessages( $lang );
218 $text = wfMsgGetKey( $message, false, $lang, false );
219 if( wfEmptyMsg( $message, $text ) )
222 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
224 wfProfileOut( __METHOD__
);
227 $this->loadContent();
228 wfProfileOut( __METHOD__
);
229 return $this->mContent
;
234 * Get the text of the current revision. No side-effects...
236 * @return Return the text of the current revision
238 public function getRawText() {
239 // Check process cache for current revision
240 if( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
241 return $this->mContent
;
243 $rev = Revision
::newFromTitle( $this->mTitle
);
244 $text = $rev ?
$rev->getRawText() : false;
249 * This function returns the text of a section, specified by a number ($section).
250 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
251 * the first section before any such heading (section 0).
253 * If a section contains subsections, these are also returned.
255 * @param $text String: text to look in
256 * @param $section Integer: section number
257 * @return string text of the requested section
260 public function getSection( $text, $section ) {
262 return $wgParser->getSection( $text, $section );
266 * Get the text that needs to be saved in order to undo all revisions
267 * between $undo and $undoafter. Revisions must belong to the same page,
268 * must exist and must not be deleted
269 * @param $undo Revision
270 * @param $undoafter Revision Must be an earlier revision than $undo
271 * @return mixed string on success, false on failure
273 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
274 $undo_text = $undo->getText();
275 $undoafter_text = $undoafter->getText();
276 $cur_text = $this->getContent();
277 if ( $cur_text == $undo_text ) {
278 # No use doing a merge if it's just a straight revert.
279 return $undoafter_text;
282 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
288 * @return int The oldid of the article that is to be shown, 0 for the
291 public function getOldID() {
292 if( is_null( $this->mOldId
) ) {
293 $this->mOldId
= $this->getOldIDFromRequest();
295 return $this->mOldId
;
299 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
301 * @return int The old id for the request
303 public function getOldIDFromRequest() {
305 $this->mRedirectUrl
= false;
306 $oldid = $wgRequest->getVal( 'oldid' );
307 if( isset( $oldid ) ) {
308 $oldid = intval( $oldid );
309 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
310 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
314 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
316 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
317 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
330 * Load the revision (including text) into this object
332 function loadContent() {
333 if( $this->mContentLoaded
) return;
334 wfProfileIn( __METHOD__
);
336 $oldid = $this->getOldID();
337 # Pre-fill content with error message so that if something
338 # fails we'll have something telling us what we intended.
339 $this->mOldId
= $oldid;
340 $this->fetchContent( $oldid );
341 wfProfileOut( __METHOD__
);
346 * Fetch a page record with the given conditions
347 * @param $dbr Database object
348 * @param $conditions Array
350 protected function pageData( $dbr, $conditions ) {
364 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
365 $row = $dbr->selectRow(
371 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
376 * @param $dbr Database object
377 * @param $title Title object
379 public function pageDataFromTitle( $dbr, $title ) {
380 return $this->pageData( $dbr, array(
381 'page_namespace' => $title->getNamespace(),
382 'page_title' => $title->getDBkey() ) );
386 * @param $dbr Database
389 protected function pageDataFromId( $dbr, $id ) {
390 return $this->pageData( $dbr, array( 'page_id' => $id ) );
394 * Set the general counter, title etc data loaded from
397 * @param $data Database row object or "fromdb"
399 public function loadPageData( $data = 'fromdb' ) {
400 if( $data === 'fromdb' ) {
401 $dbr = wfGetDB( DB_MASTER
);
402 $data = $this->pageDataFromId( $dbr, $this->getId() );
405 $lc = LinkCache
::singleton();
407 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
409 $this->mTitle
->mArticleID
= $data->page_id
;
411 # Old-fashioned restrictions
412 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
414 $this->mCounter
= $data->page_counter
;
415 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
416 $this->mIsRedirect
= $data->page_is_redirect
;
417 $this->mLatest
= $data->page_latest
;
419 if( is_object( $this->mTitle
) ) {
420 $lc->addBadLinkObj( $this->mTitle
);
422 $this->mTitle
->mArticleID
= 0;
425 $this->mDataLoaded
= true;
429 * Get text of an article from database
430 * Does *NOT* follow redirects.
431 * @param $oldid Int: 0 for whatever the latest revision is
434 function fetchContent( $oldid = 0 ) {
435 if( $this->mContentLoaded
) {
436 return $this->mContent
;
439 $dbr = wfGetDB( DB_MASTER
);
441 # Pre-fill content with error message so that if something
442 # fails we'll have something telling us what we intended.
443 $t = $this->mTitle
->getPrefixedText();
444 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
445 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
448 $revision = Revision
::newFromId( $oldid );
449 if( is_null( $revision ) ) {
450 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
453 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
455 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
458 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
459 $this->loadPageData( $data );
461 if( !$this->mDataLoaded
) {
462 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
464 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
467 $this->loadPageData( $data );
469 $revision = Revision
::newFromId( $this->mLatest
);
470 if( is_null( $revision ) ) {
471 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
476 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
477 // We should instead work with the Revision object when we need it...
478 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
480 $this->mUser
= $revision->getUser();
481 $this->mUserText
= $revision->getUserText();
482 $this->mComment
= $revision->getComment();
483 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
485 $this->mRevIdFetched
= $revision->getId();
486 $this->mContentLoaded
= true;
487 $this->mRevision
=& $revision;
489 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
491 return $this->mContent
;
495 * Read/write accessor to select FOR UPDATE
497 * @param $x Mixed: FIXME
499 public function forUpdate( $x = NULL ) {
500 return wfSetVar( $this->mForUpdate
, $x );
504 * Get the database which should be used for reads
507 * @deprecated - just call wfGetDB( DB_MASTER ) instead
510 wfDeprecated( __METHOD__
);
511 return wfGetDB( DB_MASTER
);
515 * Get options for all SELECT statements
517 * @param $options Array: an optional options array which'll be appended to
519 * @return Array: options
521 protected function getSelectOptions( $options = '' ) {
522 if( $this->mForUpdate
) {
523 if( is_array( $options ) ) {
524 $options[] = 'FOR UPDATE';
526 $options = 'FOR UPDATE';
533 * @return int Page ID
535 public function getID() {
536 if( $this->mTitle
) {
537 return $this->mTitle
->getArticleID();
544 * @return bool Whether or not the page exists in the database
546 public function exists() {
547 return $this->getId() > 0;
551 * Check if this page is something we're going to be showing
552 * some sort of sensible content for. If we return false, page
553 * views (plain action=view) will return an HTTP 404 response,
554 * so spiders and robots can know they're following a bad link.
558 public function hasViewableContent() {
559 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
563 * @return int The view count for the page
565 public function getCount() {
566 if( -1 == $this->mCounter
) {
567 $id = $this->getID();
571 $dbr = wfGetDB( DB_SLAVE
);
572 $this->mCounter
= $dbr->selectField( 'page',
574 array( 'page_id' => $id ),
576 $this->getSelectOptions()
580 return $this->mCounter
;
584 * Determine whether a page would be suitable for being counted as an
585 * article in the site_stats table based on the title & its content
587 * @param $text String: text to analyze
590 public function isCountable( $text ) {
591 global $wgUseCommaCount;
593 $token = $wgUseCommaCount ?
',' : '[[';
594 return $this->mTitle
->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
598 * Tests if the article text represents a redirect
600 * @param $text String: FIXME
603 public function isRedirect( $text = false ) {
604 if( $text === false ) {
605 if( $this->mDataLoaded
) {
606 return $this->mIsRedirect
;
608 // Apparently loadPageData was never called
609 $this->loadContent();
610 $titleObj = Title
::newFromRedirectRecurse( $this->fetchContent() );
612 $titleObj = Title
::newFromRedirect( $text );
614 return $titleObj !== NULL;
618 * Returns true if the currently-referenced revision is the current edit
619 * to this page (and it exists).
622 public function isCurrent() {
623 # If no oldid, this is the current version.
624 if( $this->getOldID() == 0 ) {
627 return $this->exists() && isset($this->mRevision
) && $this->mRevision
->isCurrent();
631 * Loads everything except the text
632 * This isn't necessary for all uses, so it's only done if needed.
634 protected function loadLastEdit() {
635 if( -1 != $this->mUser
)
638 # New or non-existent articles have no user information
639 $id = $this->getID();
640 if( 0 == $id ) return;
642 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
643 if( !is_null( $this->mLastRevision
) ) {
644 $this->mUser
= $this->mLastRevision
->getUser();
645 $this->mUserText
= $this->mLastRevision
->getUserText();
646 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
647 $this->mComment
= $this->mLastRevision
->getComment();
648 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
649 $this->mRevIdFetched
= $this->mLastRevision
->getId();
653 public function getTimestamp() {
654 // Check if the field has been filled by ParserCache::get()
655 if( !$this->mTimestamp
) {
656 $this->loadLastEdit();
658 return wfTimestamp(TS_MW
, $this->mTimestamp
);
661 public function getUser() {
662 $this->loadLastEdit();
666 public function getUserText() {
667 $this->loadLastEdit();
668 return $this->mUserText
;
671 public function getComment() {
672 $this->loadLastEdit();
673 return $this->mComment
;
676 public function getMinorEdit() {
677 $this->loadLastEdit();
678 return $this->mMinorEdit
;
681 /* Use this to fetch the rev ID used on page views */
682 public function getRevIdFetched() {
683 $this->loadLastEdit();
684 return $this->mRevIdFetched
;
688 * @param $limit Integer: default 0.
689 * @param $offset Integer: default 0.
691 public function getContributors($limit = 0, $offset = 0) {
692 # XXX: this is expensive; cache this info somewhere.
695 $dbr = wfGetDB( DB_SLAVE
);
696 $revTable = $dbr->tableName( 'revision' );
697 $userTable = $dbr->tableName( 'user' );
698 $user = $this->getUser();
699 $pageId = $this->getId();
701 $deletedBit = $dbr->bitAnd('rev_deleted', Revision
::DELETED_USER
); // username hidden?
703 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
704 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
705 WHERE rev_page = $pageId
706 AND rev_user != $user
708 GROUP BY rev_user, rev_user_text, user_real_name
709 ORDER BY timestamp DESC";
712 $sql = $dbr->limitResult($sql, $limit, $offset);
714 $sql .= ' '. $this->getSelectOptions();
716 $res = $dbr->query($sql, __METHOD__
);
718 return new UserArrayFromResult( $res );
722 * This is the default action of the index.php entry point: just view the
723 * page of the given title.
725 public function view() {
726 global $wgUser, $wgOut, $wgRequest, $wgContLang;
727 global $wgEnableParserCache, $wgStylePath, $wgParser;
728 global $wgUseTrackbacks;
730 wfProfileIn( __METHOD__
);
732 # Get variables from query string
733 $oldid = $this->getOldID();
734 $parserCache = ParserCache
::singleton();
736 $parserOptions = clone $this->getParserOptions();
737 # Render printable version, use printable version cache
738 if ( $wgOut->isPrintable() ) {
739 $parserOptions->setIsPrintable( true );
742 # Try client and file cache
743 if( $oldid === 0 && $this->checkTouched() ) {
746 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
748 # Is is client cached?
749 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
750 wfDebug( __METHOD__
.": done 304\n" );
751 wfProfileOut( __METHOD__
);
754 } else if( $this->tryFileCache() ) {
755 wfDebug( __METHOD__
.": done file cache\n" );
756 # tell wgOut that output is taken care of
758 $this->viewUpdates();
759 wfProfileOut( __METHOD__
);
764 $sk = $wgUser->getSkin();
766 # getOldID may want us to redirect somewhere else
767 if( $this->mRedirectUrl
) {
768 $wgOut->redirect( $this->mRedirectUrl
);
769 wfDebug( __METHOD__
.": redirecting due to oldid\n" );
770 wfProfileOut( __METHOD__
);
774 $wgOut->setArticleFlag( true );
775 $wgOut->setRobotPolicy( $this->getRobotPolicyForView() );
776 # Set page title (may be overridden by DISPLAYTITLE)
777 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
779 # If we got diff in the query, we want to see a diff page instead of the article.
780 if( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
781 wfDebug( __METHOD__
.": showing diff page\n" );
782 $this->showDiffPage();
783 wfProfileOut( __METHOD__
);
787 # Should the parser cache be used?
788 $useParserCache = $this->useParserCache( $oldid );
789 wfDebug( 'Article::view using parser cache: ' . ($useParserCache ?
'yes' : 'no' ) . "\n" );
790 if( $wgUser->getOption( 'stubthreshold' ) ) {
791 wfIncrStats( 'pcache_miss_stub' );
794 # For the main page, overwrite the <title> element with the con-
795 # tents of 'pagetitle-view-mainpage' instead of the default (if
797 if( $this->mTitle
->equals( Title
::newMainPage() )
798 && wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' )
800 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
803 $wasRedirected = $this->showRedirectedFromHeader();
804 $this->showNamespaceHeader();
807 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
809 # Try the parser cache
810 if( !$outputDone && $useParserCache ) {
811 $parserOutput = $parserCache->get( $this, $parserOptions );
812 if ( $parserOutput !== false ) {
813 wfDebug( __METHOD__
.": showing parser cache contents\n" );
814 $wgOut->addParserOutput( $parserOutput );
815 // Ensure that UI elements requiring revision ID have
816 // the correct version information.
817 $wgOut->setRevisionId( $this->mLatest
);
823 $this->showViewFooter();
824 $this->viewUpdates();
825 wfProfileOut( __METHOD__
);
829 $text = $this->getContent();
830 if( $text === false ||
$this->getID() == 0 ) {
831 wfDebug( __METHOD__
.": showing missing article\n" );
832 $this->showMissingArticle();
833 wfProfileOut( __METHOD__
);
837 # Another whitelist check in case oldid is altering the title
838 if( !$this->mTitle
->userCanRead() ) {
839 wfDebug( __METHOD__
.": denied on secondary read check\n" );
840 $wgOut->loginToUse();
843 wfProfileOut( __METHOD__
);
847 # We're looking at an old revision
848 if( $oldid && !is_null( $this->mRevision
) ) {
849 $this->setOldSubtitle( $oldid );
850 if ( !$this->showDeletedRevisionHeader() ) {
851 wfDebug( __METHOD__
.": cannot view deleted revision\n" );
852 wfProfileOut( __METHOD__
);
856 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
857 $parserOutput = $parserCache->get( $this, $parserOptions );
858 if ( $parserOutput ) {
859 wfDebug( __METHOD__
.": showing parser cache for current rev permalink\n" );
860 $wgOut->addParserOutput( $parserOutput );
861 $this->showViewFooter();
862 $this->viewUpdates();
863 wfProfileOut( __METHOD__
);
869 // Ensure that UI elements requiring revision ID have
870 // the correct version information.
871 $wgOut->setRevisionId( $this->getRevIdFetched() );
873 // Pages containing custom CSS or JavaScript get special treatment
874 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
875 wfDebug( __METHOD__
.": showing CSS/JS source\n" );
876 $this->showCssOrJsPage();
878 } else if( $rt = Title
::newFromRedirectArray( $text ) ) {
879 wfDebug( __METHOD__
.": showing redirect=no page\n" );
880 # Viewing a redirect page (e.g. with parameter redirect=no)
881 # Don't append the subtitle if this was an old revision
882 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
883 # Parse just to get categories, displaytitle, etc.
884 $parserOutput = $wgParser->parse( $text, $this->mTitle
, $parserOptions );
885 $wgOut->addParserOutputNoText( $parserOutput );
889 $this->showViewFooter();
890 $this->viewUpdates();
891 wfProfileOut( __METHOD__
);
895 # Run the parse, protected by a pool counter
896 wfDebug( __METHOD__
.": doing uncached parse\n" );
897 $key = $parserCache->getKey( $this, $parserOptions );
898 $poolCounter = PoolCounter
::factory( 'Article::view', $key );
899 $dirtyCallback = $useParserCache ?
array( $this, 'tryDirtyCache' ) : false;
900 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
902 if ( !$status->isOK() ) {
903 # Connection or timeout error
904 $this->showPoolError( $status );
905 wfProfileOut( __METHOD__
);
909 $this->showViewFooter();
910 $this->viewUpdates();
911 wfProfileOut( __METHOD__
);
915 * Show a diff page according to current request variables. For use within
916 * Article::view() only, other callers should use the DifferenceEngine class.
918 public function showDiffPage() {
919 global $wgOut, $wgRequest, $wgUser;
921 $diff = $wgRequest->getVal( 'diff' );
922 $rcid = $wgRequest->getVal( 'rcid' );
923 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
924 $purge = $wgRequest->getVal( 'action' ) == 'purge';
925 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
926 $unhide = $wgRequest->getInt('unhide') == 1;
927 $oldid = $this->getOldID();
929 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
930 // DifferenceEngine directly fetched the revision:
931 $this->mRevIdFetched
= $de->mNewid
;
932 $de->showDiffPage( $diffOnly );
934 // Needed to get the page's current revision
935 $this->loadPageData();
936 if( $diff == 0 ||
$diff == $this->mLatest
) {
937 # Run view updates for current revision only
938 $this->viewUpdates();
943 * Show a page view for a page formatted as CSS or JavaScript. To be called by
944 * Article::view() only.
946 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
949 public function showCssOrJsPage() {
951 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
952 // Give hooks a chance to customise the output
953 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
954 // Wrap the whole lot in a <pre> and don't parse
956 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
957 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
958 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
959 $wgOut->addHTML( "\n</pre>\n" );
964 * Get the robot policy to be used for the current action=view request.
966 public function getRobotPolicyForView() {
967 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
968 global $wgDefaultRobotPolicy, $wgRequest;
970 $ns = $this->mTitle
->getNamespace();
971 if( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
972 # Don't index user and user talk pages for blocked users (bug 11443)
973 if( !$this->mTitle
->isSubpage() ) {
974 $block = new Block();
975 if( $block->load( $this->mTitle
->getText() ) ) {
976 return 'noindex,nofollow';
981 if( $this->getID() === 0 ||
$this->getOldID() ) {
982 return 'noindex,nofollow';
983 } elseif( $wgOut->isPrintable() ) {
984 # Discourage indexing of printable versions, but encourage following
985 return 'noindex,follow';
986 } elseif( $wgRequest->getInt('curid') ) {
987 # For ?curid=x urls, disallow indexing
988 return 'noindex,follow';
989 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
990 return $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
991 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
992 # Honour customised robot policies for this namespace
993 return $wgNamespaceRobotPolicies[$ns];
995 return $wgDefaultRobotPolicy;
1000 * If this request is a redirect view, send "redirected from" subtitle to
1001 * $wgOut. Returns true if the header was needed, false if this is not a
1002 * redirect view. Handles both local and remote redirects.
1004 public function showRedirectedFromHeader() {
1005 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1007 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1008 $sk = $wgUser->getSkin();
1009 if( isset( $this->mRedirectedFrom
) ) {
1010 // This is an internally redirected page view.
1011 // We'll need a backlink to the source page for navigation.
1012 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1014 $this->mRedirectedFrom
,
1017 array( 'redirect' => 'no' ),
1018 array( 'known', 'noclasses' )
1020 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1021 $wgOut->setSubtitle( $s );
1023 // Set the fragment if one was specified in the redirect
1024 if( strval( $this->mTitle
->getFragment() ) != '' ) {
1025 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1026 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1029 // Add a <link rel="canonical"> tag
1030 $wgOut->addLink( array( 'rel' => 'canonical',
1031 'href' => $this->mTitle
->getLocalURL() )
1035 } elseif( $rdfrom ) {
1036 // This is an externally redirected view, from some other wiki.
1037 // If it was reported from a trusted site, supply a backlink.
1038 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1039 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1040 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1041 $wgOut->setSubtitle( $s );
1049 * Show a header specific to the namespace currently being viewed, like
1050 * [[MediaWiki:Talkpagetext]]. For Article::view().
1052 public function showNamespaceHeader() {
1054 if( $this->mTitle
->isTalkPage() ) {
1055 $msg = wfMsgNoTrans( 'talkpageheader' );
1056 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1057 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1063 * Show the footer section of an ordinary page view
1065 public function showViewFooter() {
1066 global $wgOut, $wgUseTrackbacks, $wgRequest;
1067 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1068 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1069 $wgOut->addWikiMsg('anontalkpagetext');
1072 # If we have been passed an &rcid= parameter, we want to give the user a
1073 # chance to mark this new article as patrolled.
1074 $this->showPatrolFooter();
1077 if( $wgUseTrackbacks ) {
1078 $this->addTrackbacks();
1083 * If patrol is possible, output a patrol UI box. This is called from the
1084 * footer section of ordinary page views. If patrol is not possible or not
1085 * desired, does nothing.
1087 public function showPatrolFooter() {
1088 global $wgOut, $wgRequest;
1089 $rcid = $wgRequest->getVal( 'rcid' );
1091 if( !$rcid ||
!$this->mTitle
->exists() ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1096 "<div class='patrollink'>" .
1098 'markaspatrolledlink',
1101 wfMsgHtml( 'markaspatrolledtext' ),
1104 'action' => 'markpatrolled',
1107 array( 'known', 'noclasses' )
1115 * Show the error text for a missing article. For articles in the MediaWiki
1116 * namespace, show the default message text. To be called from Article::view().
1118 public function showMissingArticle() {
1119 global $wgOut, $wgRequest;
1120 # Show delete and move logs
1123 # Show error message
1124 $oldid = $this->getOldID();
1126 $text = wfMsgNoTrans( 'missing-article',
1127 $this->mTitle
->getPrefixedText(),
1128 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1129 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1130 // Use the default message text
1131 $text = $this->getContent();
1133 $text = wfMsgNoTrans( 'noarticletext' );
1135 $text = "<div class='noarticletext'>\n$text\n</div>";
1136 if( !$this->hasViewableContent() ) {
1137 // If there's no backing content, send a 404 Not Found
1138 // for better machine handling of broken links.
1139 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1141 $wgOut->addWikiText( $text );
1145 * If the revision requested for view is deleted, check permissions.
1146 * Send either an error message or a warning header to $wgOut.
1147 * Returns true if the view is allowed, false if not.
1149 public function showDeletedRevisionHeader() {
1150 global $wgOut, $wgRequest;
1152 if( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1157 // If the user is not allowed to see it...
1158 if( !$this->mRevision
->userCan(Revision
::DELETED_TEXT
) ) {
1159 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1160 'rev-deleted-text-permission' );
1162 // If the user needs to confirm that they want to see it...
1163 } else if( $wgRequest->getInt('unhide') != 1 ) {
1164 # Give explanation and add a link to view the revision...
1165 $oldid = intval( $this->getOldID() );
1166 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1167 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1168 array('rev-deleted-text-unhide',$link) );
1170 // We are allowed to see...
1172 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1173 'rev-deleted-text-view' );
1179 * Show an excerpt from the deletion and move logs. To be called from the
1180 * header section on page views of missing pages.
1182 public function showLogs() {
1183 global $wgUser, $wgOut;
1184 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1185 $pager = new LogPager( $loglist, array('move', 'delete'), false,
1186 $this->mTitle
->getPrefixedText(), '', array( "log_action != 'revision'" ) );
1187 if( $pager->getNumRows() > 0 ) {
1188 $pager->mLimit
= 10;
1189 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1190 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1192 $loglist->beginLogEventsList() .
1194 $loglist->endLogEventsList()
1196 if( $pager->getNumRows() > 10 ) {
1197 $wgOut->addHTML( $wgUser->getSkin()->link(
1198 SpecialPage
::getTitleFor( 'Log' ),
1199 wfMsgHtml( 'log-fulllog' ),
1201 array( 'page' => $this->mTitle
->getPrefixedText() )
1204 $wgOut->addHTML( '</div>' );
1209 * Should the parser cache be used?
1211 public function useParserCache( $oldid ) {
1212 global $wgUser, $wgEnableParserCache;
1214 return $wgEnableParserCache
1215 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1218 && !$this->mTitle
->isCssOrJsPage()
1219 && !$this->mTitle
->isCssJsSubpage();
1223 * Execute the uncached parse for action=view
1225 public function doViewParse() {
1227 $oldid = $this->getOldID();
1228 $useParserCache = $this->useParserCache( $oldid );
1229 $parserOptions = clone $this->getParserOptions();
1230 # Render printable version, use printable version cache
1231 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1232 # Don't show section-edit links on old revisions... this way lies madness.
1233 $parserOptions->setEditSection( $this->isCurrent() );
1234 $useParserCache = $this->useParserCache( $oldid );
1235 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1239 * Try to fetch an expired entry from the parser cache. If it is present,
1240 * output it and return true. If it is not present, output nothing and
1241 * return false. This is used as a callback function for
1242 * PoolCounter::executeProtected().
1244 public function tryDirtyCache() {
1246 $parserCache = ParserCache
::singleton();
1247 $options = $this->getParserOptions();
1248 $options->setIsPrintable( $wgOut->isPrintable() );
1249 $output = $parserCache->getDirty( $this, $options );
1251 wfDebug( __METHOD__
.": sending dirty output\n" );
1252 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1253 $wgOut->setSquidMaxage( 0 );
1254 $wgOut->addParserOutput( $output );
1255 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1258 wfDebugLog( 'dirty', "dirty missing\n" );
1259 wfDebug( __METHOD__
.": no dirty cache\n" );
1265 * Show an error page for an error from the pool counter.
1266 * @param $status Status
1268 public function showPoolError( $status ) {
1270 $wgOut->clearHTML(); // for release() errors
1271 $wgOut->enableClientCache( false );
1272 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1273 $wgOut->addWikiText(
1274 '<div class="errorbox">' .
1275 $status->getWikiText( false, 'view-pool-error' ) .
1282 * @param $target Title object or Array of destination(s) to redirect
1283 * @param $appendSubtitle Boolean [optional]
1284 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1286 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1287 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1289 if( !is_array( $target ) ) {
1290 $target = array( $target );
1292 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1293 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1294 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1295 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of entities?
1297 if( $appendSubtitle ) {
1298 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1300 $sk = $wgUser->getSkin();
1301 // the loop prepends the arrow image before the link, so the first case needs to be outside
1302 $title = array_shift( $target );
1306 htmlspecialchars( $title->getFullText() ),
1309 array( 'known', 'noclasses' )
1312 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1314 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1315 foreach( $target as $rt ) {
1317 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1320 htmlspecialchars( $rt->getFullText() ),
1323 array( 'known', 'noclasses' )
1326 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1327 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1330 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1331 '<span class="redirectText">'.$link.'</span>';
1335 public function addTrackbacks() {
1336 global $wgOut, $wgUser;
1337 $dbr = wfGetDB( DB_SLAVE
);
1338 $tbs = $dbr->select( 'trackbacks',
1339 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1340 array('tb_page' => $this->getID() )
1342 if( !$dbr->numRows($tbs) ) return;
1345 while( $o = $dbr->fetchObject($tbs) ) {
1347 if( $wgUser->isAllowed( 'trackback' ) ) {
1348 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1349 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1350 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1353 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1360 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1361 $this->mTitle
->invalidateCache();
1364 public function deletetrackback() {
1365 global $wgUser, $wgRequest, $wgOut;
1366 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1367 $wgOut->addWikiMsg( 'sessionfailure' );
1371 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1372 if( count($permission_errors) ) {
1373 $wgOut->showPermissionsErrorPage( $permission_errors );
1377 $db = wfGetDB( DB_MASTER
);
1378 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1380 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1381 $this->mTitle
->invalidateCache();
1384 public function render() {
1386 $wgOut->setArticleBodyOnly(true);
1391 * Handle action=purge
1393 public function purge() {
1394 global $wgUser, $wgRequest, $wgOut;
1395 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1396 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1401 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1402 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1403 $form = "<form method=\"post\" action=\"$action\">\n" .
1404 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1406 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1407 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1408 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1409 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1410 $wgOut->addHTML( $top . $form . $bottom );
1415 * Perform the actions of a page purging
1417 public function doPurge() {
1419 // Invalidate the cache
1420 $this->mTitle
->invalidateCache();
1423 // Commit the transaction before the purge is sent
1424 $dbw = wfGetDB( DB_MASTER
);
1425 $dbw->immediateCommit();
1428 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1429 $update->doUpdate();
1431 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1432 global $wgMessageCache;
1433 if( $this->getID() == 0 ) {
1436 $text = $this->getRawText();
1438 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1443 * Insert a new empty page record for this article.
1444 * This *must* be followed up by creating a revision
1445 * and running $this->updateToLatest( $rev_id );
1446 * or else the record will be left in a funky state.
1447 * Best if all done inside a transaction.
1449 * @param $dbw Database
1450 * @return int The newly created page_id key, or false if the title already existed
1453 public function insertOn( $dbw ) {
1454 wfProfileIn( __METHOD__
);
1456 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1457 $dbw->insert( 'page', array(
1458 'page_id' => $page_id,
1459 'page_namespace' => $this->mTitle
->getNamespace(),
1460 'page_title' => $this->mTitle
->getDBkey(),
1461 'page_counter' => 0,
1462 'page_restrictions' => '',
1463 'page_is_redirect' => 0, # Will set this shortly...
1465 'page_random' => wfRandom(),
1466 'page_touched' => $dbw->timestamp(),
1467 'page_latest' => 0, # Fill this in shortly...
1468 'page_len' => 0, # Fill this in shortly...
1469 ), __METHOD__
, 'IGNORE' );
1471 $affected = $dbw->affectedRows();
1473 $newid = $dbw->insertId();
1474 $this->mTitle
->resetArticleId( $newid );
1476 wfProfileOut( __METHOD__
);
1477 return $affected ?
$newid : false;
1481 * Update the page record to point to a newly saved revision.
1483 * @param $dbw Database object
1484 * @param $revision Revision: For ID number, and text used to set
1485 length and redirect status fields
1486 * @param $lastRevision Integer: if given, will not overwrite the page field
1487 * when different from the currently set value.
1488 * Giving 0 indicates the new page flag should be set
1490 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1491 * removing rows in redirect table.
1492 * @return bool true on success, false on failure
1495 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1496 wfProfileIn( __METHOD__
);
1498 $text = $revision->getText();
1499 $rt = Title
::newFromRedirect( $text );
1501 $conditions = array( 'page_id' => $this->getId() );
1502 if( !is_null( $lastRevision ) ) {
1503 # An extra check against threads stepping on each other
1504 $conditions['page_latest'] = $lastRevision;
1507 $dbw->update( 'page',
1509 'page_latest' => $revision->getId(),
1510 'page_touched' => $dbw->timestamp(),
1511 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1512 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1513 'page_len' => strlen( $text ),
1518 $result = $dbw->affectedRows() != 0;
1520 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1523 wfProfileOut( __METHOD__
);
1528 * Add row to the redirect table if this is a redirect, remove otherwise.
1530 * @param $dbw Database
1531 * @param $redirectTitle a title object pointing to the redirect target,
1532 * or NULL if this is not a redirect
1533 * @param $lastRevIsRedirect If given, will optimize adding and
1534 * removing rows in redirect table.
1535 * @return bool true on success, false on failure
1538 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1539 // Always update redirects (target link might have changed)
1540 // Update/Insert if we don't know if the last revision was a redirect or not
1541 // Delete if changing from redirect to non-redirect
1542 $isRedirect = !is_null($redirectTitle);
1543 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1544 wfProfileIn( __METHOD__
);
1546 // This title is a redirect, Add/Update row in the redirect table
1547 $set = array( /* SET */
1548 'rd_namespace' => $redirectTitle->getNamespace(),
1549 'rd_title' => $redirectTitle->getDBkey(),
1550 'rd_from' => $this->getId(),
1552 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1554 // This is not a redirect, remove row from redirect table
1555 $where = array( 'rd_from' => $this->getId() );
1556 $dbw->delete( 'redirect', $where, __METHOD__
);
1558 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1559 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1561 wfProfileOut( __METHOD__
);
1562 return ( $dbw->affectedRows() != 0 );
1568 * If the given revision is newer than the currently set page_latest,
1569 * update the page record. Otherwise, do nothing.
1571 * @param $dbw Database object
1572 * @param $revision Revision object
1574 public function updateIfNewerOn( &$dbw, $revision ) {
1575 wfProfileIn( __METHOD__
);
1576 $row = $dbw->selectRow(
1577 array( 'revision', 'page' ),
1578 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1580 'page_id' => $this->getId(),
1581 'page_latest=rev_id' ),
1584 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1585 wfProfileOut( __METHOD__
);
1588 $prev = $row->rev_id
;
1589 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1591 # No or missing previous revision; mark the page as new
1593 $lastRevIsRedirect = null;
1595 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1596 wfProfileOut( __METHOD__
);
1601 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1602 * @return string Complete article text, or null if error
1604 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1605 wfProfileIn( __METHOD__
);
1606 if( strval( $section ) == '' ) {
1607 // Whole-page edit; let the whole text through
1609 if( is_null($edittime) ) {
1610 $rev = Revision
::newFromTitle( $this->mTitle
);
1612 $dbw = wfGetDB( DB_MASTER
);
1613 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1616 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1617 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1620 $oldtext = $rev->getText();
1622 if( $section == 'new' ) {
1623 # Inserting a new section
1624 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1625 $text = strlen( trim( $oldtext ) ) > 0
1626 ?
"{$oldtext}\n\n{$subject}{$text}"
1627 : "{$subject}{$text}";
1629 # Replacing an existing section; roll out the big guns
1631 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1634 wfProfileOut( __METHOD__
);
1639 * This function is not deprecated until somebody fixes the core not to use
1640 * it. Nevertheless, use Article::doEdit() instead.
1642 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1643 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1644 ( $isminor ? EDIT_MINOR
: 0 ) |
1645 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1646 ( $bot ? EDIT_FORCE_BOT
: 0 );
1648 # If this is a comment, add the summary as headline
1649 if( $comment && $summary != "" ) {
1650 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1653 $this->doEdit( $text, $summary, $flags );
1655 $dbw = wfGetDB( DB_MASTER
);
1657 if(!$this->mTitle
->userIsWatching()) {
1663 if( $this->mTitle
->userIsWatching() ) {
1669 $this->doRedirect( $this->isRedirect( $text ) );
1673 * @deprecated use Article::doEdit()
1675 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1676 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1677 ( $minor ? EDIT_MINOR
: 0 ) |
1678 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1680 $status = $this->doEdit( $text, $summary, $flags );
1681 if( !$status->isOK() ) {
1685 $dbw = wfGetDB( DB_MASTER
);
1687 if(!$this->mTitle
->userIsWatching()) {
1693 if( $this->mTitle
->userIsWatching() ) {
1700 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1701 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1703 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1710 * Change an existing article or create a new article. Updates RC and all necessary caches,
1711 * optionally via the deferred update array.
1713 * $wgUser must be set before calling this function.
1715 * @param $text String: new text
1716 * @param $summary String: edit summary
1717 * @param $flags Integer bitfield:
1719 * Article is known or assumed to be non-existent, create a new one
1721 * Article is known or assumed to be pre-existing, update it
1723 * Mark this edit minor, if the user is allowed to do so
1725 * Do not log the change in recentchanges
1727 * Mark the edit a "bot" edit regardless of user rights
1728 * EDIT_DEFER_UPDATES
1729 * Defer some of the updates until the end of index.php
1731 * Fill in blank summaries with generated text where possible
1733 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1734 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1735 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1736 * edit-already-exists error will be returned. These two conditions are also possible with
1737 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1739 * @param $baseRevId the revision ID this edit was based off, if any
1740 * @param $user Optional user object, $wgUser will be used if not passed
1742 * @return Status object. Possible errors:
1743 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1744 * edit-gone-missing: In update mode, but the article didn't exist
1745 * edit-conflict: In update mode, the article changed unexpectedly
1746 * edit-no-change: Warning that the text was the same as before
1747 * edit-already-exists: In creation mode, but the article already exists
1749 * Extensions may define additional errors.
1751 * $return->value will contain an associative array with members as follows:
1752 * new: Boolean indicating if the function attempted to create a new article
1753 * revision: The revision object for the inserted revision, or null
1755 * Compatibility note: this function previously returned a boolean value indicating success/failure
1757 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1758 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1760 # Low-level sanity check
1761 if( $this->mTitle
->getText() == '' ) {
1762 throw new MWException( 'Something is trying to edit an article with an empty title' );
1765 wfProfileIn( __METHOD__
);
1767 $user = is_null($user) ?
$wgUser : $user;
1768 $status = Status
::newGood( array() );
1770 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1771 $this->loadPageData();
1773 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1774 $aid = $this->mTitle
->getArticleID();
1776 $flags |
= EDIT_UPDATE
;
1782 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1783 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1785 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1786 wfProfileOut( __METHOD__
);
1787 if( $status->isOK() ) {
1788 $status->fatal( 'edit-hook-aborted');
1793 # Silently ignore EDIT_MINOR if not allowed
1794 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1795 $bot = $flags & EDIT_FORCE_BOT
;
1797 $oldtext = $this->getRawText(); // current revision
1798 $oldsize = strlen( $oldtext );
1800 # Provide autosummaries if one is not provided and autosummaries are enabled.
1801 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1802 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1805 $editInfo = $this->prepareTextForEdit( $text );
1806 $text = $editInfo->pst
;
1807 $newsize = strlen( $text );
1809 $dbw = wfGetDB( DB_MASTER
);
1810 $now = wfTimestampNow();
1812 if( $flags & EDIT_UPDATE
) {
1813 # Update article, but only if changed.
1814 $status->value
['new'] = false;
1815 # Make sure the revision is either completely inserted or not inserted at all
1816 if( !$wgDBtransactions ) {
1817 $userAbort = ignore_user_abort( true );
1822 $changed = ( strcmp( $text, $oldtext ) != 0 );
1825 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1826 - (int)$this->isCountable( $oldtext );
1827 $this->mTotalAdjustment
= 0;
1829 if( !$this->mLatest
) {
1830 # Article gone missing
1831 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1832 $status->fatal( 'edit-gone-missing' );
1833 wfProfileOut( __METHOD__
);
1837 $revision = new Revision( array(
1838 'page' => $this->getId(),
1839 'comment' => $summary,
1840 'minor_edit' => $isminor,
1842 'parent_id' => $this->mLatest
,
1843 'user' => $user->getId(),
1844 'user_text' => $user->getName(),
1848 $revisionId = $revision->insertOn( $dbw );
1852 # Note that we use $this->mLatest instead of fetching a value from the master DB
1853 # during the course of this function. This makes sure that EditPage can detect
1854 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1855 # before this function is called. A previous function used a separate query, this
1856 # creates a window where concurrent edits can cause an ignored edit conflict.
1857 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1860 /* Belated edit conflict! Run away!! */
1861 $status->fatal( 'edit-conflict' );
1862 # Delete the invalid revision if the DB is not transactional
1863 if( !$wgDBtransactions ) {
1864 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1869 global $wgUseRCPatrol;
1870 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1871 # Update recentchanges
1872 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1873 # Mark as patrolled if the user can do so
1874 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan('autopatrol');
1875 # Add RC row to the DB
1876 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1877 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1878 $revisionId, $patrolled
1880 # Log auto-patrolled edits
1882 PatrolLog
::record( $rc, true );
1885 $user->incEditCount();
1889 $status->warning( 'edit-no-change' );
1891 // Keep the same revision ID, but do some updates on it
1892 $revisionId = $this->getRevIdFetched();
1893 // Update page_touched, this is usually implicit in the page update
1894 // Other cache updates are done in onArticleEdit()
1895 $this->mTitle
->invalidateCache();
1898 if( !$wgDBtransactions ) {
1899 ignore_user_abort( $userAbort );
1901 // Now that ignore_user_abort is restored, we can respond to fatal errors
1902 if( !$status->isOK() ) {
1903 wfProfileOut( __METHOD__
);
1907 # Invalidate cache of this article and all pages using this article
1908 # as a template. Partly deferred.
1909 Article
::onArticleEdit( $this->mTitle
);
1910 # Update links tables, site stats, etc.
1911 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1913 # Create new article
1914 $status->value
['new'] = true;
1916 # Set statistics members
1917 # We work out if it's countable after PST to avoid counter drift
1918 # when articles are created with {{subst:}}
1919 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1920 $this->mTotalAdjustment
= 1;
1924 # Add the page record; stake our claim on this title!
1925 # This will return false if the article already exists
1926 $newid = $this->insertOn( $dbw );
1928 if( $newid === false ) {
1930 $status->fatal( 'edit-already-exists' );
1931 wfProfileOut( __METHOD__
);
1935 # Save the revision text...
1936 $revision = new Revision( array(
1938 'comment' => $summary,
1939 'minor_edit' => $isminor,
1941 'user' => $user->getId(),
1942 'user_text' => $user->getName(),
1944 $revisionId = $revision->insertOn( $dbw );
1946 $this->mTitle
->resetArticleID( $newid );
1948 # Update the page record with revision data
1949 $this->updateRevisionOn( $dbw, $revision, 0 );
1951 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1952 # Update recentchanges
1953 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1954 global $wgUseRCPatrol, $wgUseNPPatrol;
1955 # Mark as patrolled if the user can do so
1956 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $this->mTitle
->userCan('autopatrol');
1957 # Add RC row to the DB
1958 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1959 '', strlen($text), $revisionId, $patrolled );
1960 # Log auto-patrolled edits
1962 PatrolLog
::record( $rc, true );
1965 $user->incEditCount();
1968 # Update links, etc.
1969 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1972 Article
::onArticleCreate( $this->mTitle
);
1974 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1975 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1978 # Do updates right now unless deferral was requested
1979 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1983 // Return the new revision (or null) to the caller
1984 $status->value
['revision'] = $revision;
1986 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1987 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1989 wfProfileOut( __METHOD__
);
1994 * @deprecated wrapper for doRedirect
1996 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1997 wfDeprecated( __METHOD__
);
1998 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2002 * Output a redirect back to the article.
2003 * This is typically used after an edit.
2005 * @param $noRedir Boolean: add redirect=no
2006 * @param $sectionAnchor String: section to redirect to, including "#"
2007 * @param $extraQuery String: extra query params
2009 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2012 $query = 'redirect=no';
2014 $query .= "&$query";
2016 $query = $extraQuery;
2018 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2022 * Mark this particular edit/page as patrolled
2024 public function markpatrolled() {
2025 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2026 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2028 # If we haven't been given an rc_id value, we can't do anything
2029 $rcid = (int) $wgRequest->getVal('rcid');
2030 $rc = RecentChange
::newFromId($rcid);
2031 if( is_null($rc) ) {
2032 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2036 #It would be nice to see where the user had actually come from, but for now just guess
2037 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2038 $return = SpecialPage
::getTitleFor( $returnto );
2040 $dbw = wfGetDB( DB_MASTER
);
2041 $errors = $rc->doMarkPatrolled();
2043 if( in_array(array('rcpatroldisabled'), $errors) ) {
2044 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2048 if( in_array(array('hookaborted'), $errors) ) {
2049 // The hook itself has handled any output
2053 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
2054 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2055 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2056 $wgOut->returnToMain( false, $return );
2060 if( !empty($errors) ) {
2061 $wgOut->showPermissionsErrorPage( $errors );
2066 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2067 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
2068 $wgOut->returnToMain( false, $return );
2072 * User-interface handler for the "watch" action
2075 public function watch() {
2076 global $wgUser, $wgOut;
2077 if( $wgUser->isAnon() ) {
2078 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2081 if( wfReadOnly() ) {
2082 $wgOut->readOnlyPage();
2085 if( $this->doWatch() ) {
2086 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2087 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2088 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
2090 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2094 * Add this page to $wgUser's watchlist
2095 * @return bool true on successful watch operation
2097 public function doWatch() {
2099 if( $wgUser->isAnon() ) {
2102 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
2103 $wgUser->addWatch( $this->mTitle
);
2104 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
2110 * User interface handler for the "unwatch" action.
2112 public function unwatch() {
2113 global $wgUser, $wgOut;
2114 if( $wgUser->isAnon() ) {
2115 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2118 if( wfReadOnly() ) {
2119 $wgOut->readOnlyPage();
2122 if( $this->doUnwatch() ) {
2123 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2124 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2125 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
2127 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2131 * Stop watching a page
2132 * @return bool true on successful unwatch
2134 public function doUnwatch() {
2136 if( $wgUser->isAnon() ) {
2139 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
2140 $wgUser->removeWatch( $this->mTitle
);
2141 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
2147 * action=protect handler
2149 public function protect() {
2150 $form = new ProtectionForm( $this );
2155 * action=unprotect handler (alias)
2157 public function unprotect() {
2162 * Update the article's restriction field, and leave a log entry.
2164 * @param $limit Array: set of restriction keys
2165 * @param $reason String
2166 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2167 * @param $expiry Array: per restriction type expiration
2168 * @return bool true on success
2170 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2171 global $wgUser, $wgRestrictionTypes, $wgContLang;
2173 $id = $this->mTitle
->getArticleID();
2175 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2179 if ( wfReadOnly() ) {
2180 wfDebug( "updateRestrictions failed: read-only\n" );
2184 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2185 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2193 // Take this opportunity to purge out expired restrictions
2194 Title
::purgeExpiredRestrictions();
2196 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2197 # we expect a single selection, but the schema allows otherwise.
2199 $updated = Article
::flattenRestrictions( $limit );
2201 foreach( $wgRestrictionTypes as $action ) {
2202 if( isset( $expiry[$action] ) ) {
2203 # Get current restrictions on $action
2204 $aLimits = $this->mTitle
->getRestrictions( $action );
2205 $current[$action] = implode( '', $aLimits );
2206 # Are any actual restrictions being dealt with here?
2207 $aRChanged = count($aLimits) ||
!empty($limit[$action]);
2208 # If something changed, we need to log it. Checking $aRChanged
2209 # assures that "unprotecting" a page that is not protected does
2210 # not log just because the expiry was "changed".
2211 if( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2217 $current = Article
::flattenRestrictions( $current );
2219 $changed = ($changed ||
$current != $updated );
2220 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
2221 $protect = ( $updated != '' );
2223 # If nothing's changed, do nothing
2225 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2227 $dbw = wfGetDB( DB_MASTER
);
2229 # Prepare a null revision to be added to the history
2230 $modified = $current != '' && $protect;
2232 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2234 $comment_type = 'unprotectedarticle';
2236 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2238 # Only restrictions with the 'protect' right can cascade...
2239 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2240 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2241 # The schema allows multiple restrictions
2242 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2244 $cascade_description = '';
2246 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2250 $comment .= ": $reason";
2252 $editComment = $comment;
2253 $encodedExpiry = array();
2254 $protect_description = '';
2255 foreach( $limit as $action => $restrictions ) {
2256 if ( !isset($expiry[$action]) )
2257 $expiry[$action] = 'infinite';
2259 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
2260 if( $restrictions != '' ) {
2261 $protect_description .= "[$action=$restrictions] (";
2262 if( $encodedExpiry[$action] != 'infinity' ) {
2263 $protect_description .= wfMsgForContent( 'protect-expiring',
2264 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2265 $wgContLang->date( $expiry[$action], false, false ) ,
2266 $wgContLang->time( $expiry[$action], false, false ) );
2268 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2270 $protect_description .= ') ';
2273 $protect_description = trim($protect_description);
2275 if( $protect_description && $protect )
2276 $editComment .= " ($protect_description)";
2278 $editComment .= "$cascade_description";
2279 # Update restrictions table
2280 foreach( $limit as $action => $restrictions ) {
2281 if($restrictions != '' ) {
2282 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2283 array( 'pr_page' => $id,
2284 'pr_type' => $action,
2285 'pr_level' => $restrictions,
2286 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
2287 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
2289 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2290 'pr_type' => $action ), __METHOD__
);
2294 # Insert a null revision
2295 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2296 $nullRevId = $nullRevision->insertOn( $dbw );
2298 $latest = $this->getLatest();
2299 # Update page record
2300 $dbw->update( 'page',
2302 'page_touched' => $dbw->timestamp(),
2303 'page_restrictions' => '',
2304 'page_latest' => $nullRevId
2305 ), array( /* WHERE */
2307 ), 'Article::protect'
2310 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2311 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2313 # Update the protection log
2314 $log = new LogPage( 'protect' );
2316 $params = array($protect_description,$cascade ?
'cascade' : '');
2317 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
2319 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2323 } # End "changed" check
2329 * Take an array of page restrictions and flatten it to a string
2330 * suitable for insertion into the page_restrictions field.
2331 * @param $limit Array
2334 protected static function flattenRestrictions( $limit ) {
2335 if( !is_array( $limit ) ) {
2336 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2340 foreach( $limit as $action => $restrictions ) {
2341 if( $restrictions != '' ) {
2342 $bits[] = "$action=$restrictions";
2345 return implode( ':', $bits );
2349 * Auto-generates a deletion reason
2350 * @param &$hasHistory Boolean: whether the page has a history
2352 public function generateReason( &$hasHistory ) {
2354 $dbw = wfGetDB( DB_MASTER
);
2355 // Get the last revision
2356 $rev = Revision
::newFromTitle( $this->mTitle
);
2357 if( is_null( $rev ) )
2360 // Get the article's contents
2361 $contents = $rev->getText();
2363 // If the page is blank, use the text from the previous revision,
2364 // which can only be blank if there's a move/import/protect dummy revision involved
2365 if( $contents == '' ) {
2366 $prev = $rev->getPrevious();
2368 $contents = $prev->getText();
2373 // Find out if there was only one contributor
2374 // Only scan the last 20 revisions
2375 $res = $dbw->select( 'revision', 'rev_user_text',
2376 array( 'rev_page' => $this->getID(), $dbw->bitAnd('rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2378 array( 'LIMIT' => 20 )
2380 if( $res === false )
2381 // This page has no revisions, which is very weird
2384 $hasHistory = ( $res->numRows() > 1 );
2385 $row = $dbw->fetchObject( $res );
2386 $onlyAuthor = $row->rev_user_text
;
2387 // Try to find a second contributor
2388 foreach( $res as $row ) {
2389 if( $row->rev_user_text
!= $onlyAuthor ) {
2390 $onlyAuthor = false;
2394 $dbw->freeResult( $res );
2396 // Generate the summary with a '$1' placeholder
2398 // The current revision is blank and the one before is also
2399 // blank. It's just not our lucky day
2400 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2403 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2405 $reason = wfMsgForContent( 'excontent', '$1' );
2408 if( $reason == '-' ) {
2409 // Allow these UI messages to be blanked out cleanly
2413 // Replace newlines with spaces to prevent uglyness
2414 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2415 // Calculate the maximum amount of chars to get
2416 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2417 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2418 $contents = $wgContLang->truncate( $contents, $maxLength );
2419 // Remove possible unfinished links
2420 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2421 // Now replace the '$1' placeholder
2422 $reason = str_replace( '$1', $contents, $reason );
2428 * UI entry point for page deletion
2430 public function delete() {
2431 global $wgUser, $wgOut, $wgRequest;
2433 $confirm = $wgRequest->wasPosted() &&
2434 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2436 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2437 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2439 $reason = $this->DeleteReasonList
;
2441 if( $reason != 'other' && $this->DeleteReason
!= '' ) {
2442 // Entry from drop down menu + additional comment
2443 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2444 } elseif( $reason == 'other' ) {
2445 $reason = $this->DeleteReason
;
2447 # Flag to hide all contents of the archived revisions
2448 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2450 # This code desperately needs to be totally rewritten
2452 # Read-only check...
2453 if( wfReadOnly() ) {
2454 $wgOut->readOnlyPage();
2459 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2461 if( count( $permission_errors ) > 0 ) {
2462 $wgOut->showPermissionsErrorPage( $permission_errors );
2466 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2468 # Better double-check that it hasn't been deleted yet!
2469 $dbw = wfGetDB( DB_MASTER
);
2470 $conds = $this->mTitle
->pageCond();
2471 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2472 if( $latest === false ) {
2473 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2474 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2475 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2479 # Hack for big sites
2480 $bigHistory = $this->isBigDeletion();
2481 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2482 global $wgLang, $wgDeleteRevisionsLimit;
2483 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2484 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2489 $this->doDelete( $reason, $suppress );
2490 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2492 } elseif( $this->mTitle
->userIsWatching() ) {
2498 // Generate deletion reason
2499 $hasHistory = false;
2500 if( !$reason ) $reason = $this->generateReason($hasHistory);
2502 // If the page has a history, insert a warning
2503 if( $hasHistory && !$confirm ) {
2504 $skin = $wgUser->getSkin();
2505 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2507 global $wgLang, $wgDeleteRevisionsLimit;
2508 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2509 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2513 return $this->confirmDelete( $reason );
2517 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2519 public function isBigDeletion() {
2520 global $wgDeleteRevisionsLimit;
2521 if( $wgDeleteRevisionsLimit ) {
2522 $revCount = $this->estimateRevisionCount();
2523 return $revCount > $wgDeleteRevisionsLimit;
2529 * @return int approximate revision count
2531 public function estimateRevisionCount() {
2532 $dbr = wfGetDB( DB_SLAVE
);
2533 // For an exact count...
2534 //return $dbr->selectField( 'revision', 'COUNT(*)',
2535 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2536 return $dbr->estimateRowCount( 'revision', '*',
2537 array( 'rev_page' => $this->getId() ), __METHOD__
);
2541 * Get the last N authors
2542 * @param $num Integer: number of revisions to get
2543 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2544 * @return array Array of authors, duplicates not removed
2546 public function getLastNAuthors( $num, $revLatest = 0 ) {
2547 wfProfileIn( __METHOD__
);
2548 // First try the slave
2549 // If that doesn't have the latest revision, try the master
2551 $db = wfGetDB( DB_SLAVE
);
2553 $res = $db->select( array( 'page', 'revision' ),
2554 array( 'rev_id', 'rev_user_text' ),
2556 'page_namespace' => $this->mTitle
->getNamespace(),
2557 'page_title' => $this->mTitle
->getDBkey(),
2558 'rev_page = page_id'
2559 ), __METHOD__
, $this->getSelectOptions( array(
2560 'ORDER BY' => 'rev_timestamp DESC',
2565 wfProfileOut( __METHOD__
);
2568 $row = $db->fetchObject( $res );
2569 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2570 $db = wfGetDB( DB_MASTER
);
2575 } while ( $continue );
2577 $authors = array( $row->rev_user_text
);
2578 while ( $row = $db->fetchObject( $res ) ) {
2579 $authors[] = $row->rev_user_text
;
2581 wfProfileOut( __METHOD__
);
2586 * Output deletion confirmation dialog
2587 * @param $reason String: prefilled reason
2589 public function confirmDelete( $reason ) {
2590 global $wgOut, $wgUser;
2592 wfDebug( "Article::confirmDelete\n" );
2594 $deleteBackLink = $wgUser->getSkin()->link(
2599 array( 'known', 'noclasses' )
2601 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2602 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2603 $wgOut->addWikiMsg( 'confirmdeletetext' );
2605 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2606 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2608 <td class='mw-input'><strong>" .
2609 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2610 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2616 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2618 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2619 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2620 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2621 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2622 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2623 "<tr id=\"wpDeleteReasonListRow\">
2624 <td class='mw-label'>" .
2625 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2627 <td class='mw-input'>" .
2628 Xml
::listDropDown( 'wpDeleteReasonList',
2629 wfMsgForContent( 'deletereason-dropdown' ),
2630 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2633 <tr id=\"wpDeleteReasonRow\">
2634 <td class='mw-label'>" .
2635 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2637 <td class='mw-input'>" .
2638 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2639 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2644 <td class='mw-input'>" .
2645 Xml
::checkLabel( wfMsg( 'watchthis' ),
2646 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2652 <td class='mw-submit'>" .
2653 Xml
::submitButton( wfMsg( 'deletepage' ),
2654 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2657 Xml
::closeElement( 'table' ) .
2658 Xml
::closeElement( 'fieldset' ) .
2659 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2660 Xml
::closeElement( 'form' );
2662 if( $wgUser->isAllowed( 'editinterface' ) ) {
2663 $skin = $wgUser->getSkin();
2664 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2665 $link = $skin->link(
2667 wfMsgHtml( 'delete-edit-reasonlist' ),
2669 array( 'action' => 'edit' )
2671 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2674 $wgOut->addHTML( $form );
2675 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2676 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2680 * Perform a deletion and output success or failure messages
2682 public function doDelete( $reason, $suppress = false ) {
2683 global $wgOut, $wgUser;
2684 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2687 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2688 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2689 $deleted = $this->mTitle
->getPrefixedText();
2691 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2692 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2694 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2696 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2697 $wgOut->returnToMain( false );
2698 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2700 if( $error == '' ) {
2701 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2702 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2703 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2705 $wgOut->showFatalError( $error );
2712 * Back-end article deletion
2713 * Deletes the article with database consistency, writes logs, purges caches
2716 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2717 global $wgUseSquid, $wgDeferredUpdateList;
2718 global $wgUseTrackbacks;
2720 wfDebug( __METHOD__
."\n" );
2722 $dbw = wfGetDB( DB_MASTER
);
2723 $ns = $this->mTitle
->getNamespace();
2724 $t = $this->mTitle
->getDBkey();
2725 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2727 if( $t == '' ||
$id == 0 ) {
2731 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2732 array_push( $wgDeferredUpdateList, $u );
2734 // Bitfields to further suppress the content
2737 // This should be 15...
2738 $bitfield |
= Revision
::DELETED_TEXT
;
2739 $bitfield |
= Revision
::DELETED_COMMENT
;
2740 $bitfield |
= Revision
::DELETED_USER
;
2741 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2743 $bitfield = 'rev_deleted';
2747 // For now, shunt the revision data into the archive table.
2748 // Text is *not* removed from the text table; bulk storage
2749 // is left intact to avoid breaking block-compression or
2750 // immutable storage schemes.
2752 // For backwards compatibility, note that some older archive
2753 // table entries will have ar_text and ar_flags fields still.
2755 // In the future, we may keep revisions and mark them with
2756 // the rev_deleted field, which is reserved for this purpose.
2757 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2759 'ar_namespace' => 'page_namespace',
2760 'ar_title' => 'page_title',
2761 'ar_comment' => 'rev_comment',
2762 'ar_user' => 'rev_user',
2763 'ar_user_text' => 'rev_user_text',
2764 'ar_timestamp' => 'rev_timestamp',
2765 'ar_minor_edit' => 'rev_minor_edit',
2766 'ar_rev_id' => 'rev_id',
2767 'ar_text_id' => 'rev_text_id',
2768 'ar_text' => '\'\'', // Be explicit to appease
2769 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2770 'ar_len' => 'rev_len',
2771 'ar_page_id' => 'page_id',
2772 'ar_deleted' => $bitfield
2775 'page_id = rev_page'
2779 # Delete restrictions for it
2780 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2782 # Now that it's safely backed up, delete it
2783 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2784 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2790 # Fix category table counts
2792 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2793 foreach( $res as $row ) {
2794 $cats []= $row->cl_to
;
2796 $this->updateCategoryCounts( array(), $cats );
2798 # If using cascading deletes, we can skip some explicit deletes
2799 if( !$dbw->cascadingDeletes() ) {
2800 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2802 if($wgUseTrackbacks)
2803 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2805 # Delete outgoing links
2806 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2807 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2808 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2809 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2810 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2811 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2812 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2815 # If using cleanup triggers, we can skip some manual deletes
2816 if( !$dbw->cleanupTriggers() ) {
2817 # Clean up recentchanges entries...
2818 $dbw->delete( 'recentchanges',
2819 array( 'rc_type != '.RC_LOG
,
2820 'rc_namespace' => $this->mTitle
->getNamespace(),
2821 'rc_title' => $this->mTitle
->getDBkey() ),
2823 $dbw->delete( 'recentchanges',
2824 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2829 Article
::onArticleDelete( $this->mTitle
);
2831 # Clear the cached article id so the interface doesn't act like we exist
2832 $this->mTitle
->resetArticleID( 0 );
2834 # Log the deletion, if the page was suppressed, log it at Oversight instead
2835 $logtype = $suppress ?
'suppress' : 'delete';
2836 $log = new LogPage( $logtype );
2838 # Make sure logging got through
2839 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2847 * Roll back the most recent consecutive set of edits to a page
2848 * from the same user; fails if there are no eligible edits to
2849 * roll back to, e.g. user is the sole contributor. This function
2850 * performs permissions checks on $wgUser, then calls commitRollback()
2851 * to do the dirty work
2853 * @param $fromP String: Name of the user whose edits to rollback.
2854 * @param $summary String: Custom summary. Set to default summary if empty.
2855 * @param $token String: Rollback token.
2856 * @param $bot Boolean: If true, mark all reverted edits as bot.
2858 * @param $resultDetails Array: contains result-specific array of additional values
2859 * 'alreadyrolled' : 'current' (rev)
2860 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2862 * @return array of errors, each error formatted as
2863 * array(messagekey, param1, param2, ...).
2864 * On success, the array is empty. This array can also be passed to
2865 * OutputPage::showPermissionsErrorPage().
2867 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2869 $resultDetails = null;
2872 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2873 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2874 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2876 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2877 $errors[] = array( 'sessionfailure' );
2879 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2880 $errors[] = array( 'actionthrottledtext' );
2882 # If there were errors, bail out now
2883 if( !empty( $errors ) )
2886 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2890 * Backend implementation of doRollback(), please refer there for parameter
2891 * and return value documentation
2893 * NOTE: This function does NOT check ANY permissions, it just commits the
2894 * rollback to the DB Therefore, you should only call this function direct-
2895 * ly if you want to use custom permissions checks. If you don't, use
2896 * doRollback() instead.
2898 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2899 global $wgUseRCPatrol, $wgUser, $wgLang;
2900 $dbw = wfGetDB( DB_MASTER
);
2902 if( wfReadOnly() ) {
2903 return array( array( 'readonlytext' ) );
2906 # Get the last editor
2907 $current = Revision
::newFromTitle( $this->mTitle
);
2908 if( is_null( $current ) ) {
2909 # Something wrong... no page?
2910 return array(array('notanarticle'));
2913 $from = str_replace( '_', ' ', $fromP );
2914 if( $from != $current->getUserText() ) {
2915 $resultDetails = array( 'current' => $current );
2916 return array(array('alreadyrolled',
2917 htmlspecialchars($this->mTitle
->getPrefixedText()),
2918 htmlspecialchars($fromP),
2919 htmlspecialchars($current->getUserText())
2923 # Get the last edit not by this guy
2924 $user = intval( $current->getUser() );
2925 $user_text = $dbw->addQuotes( $current->getUserText() );
2926 $s = $dbw->selectRow( 'revision',
2927 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2928 array( 'rev_page' => $current->getPage(),
2929 "rev_user != {$user} OR rev_user_text != {$user_text}"
2931 array( 'USE INDEX' => 'page_timestamp',
2932 'ORDER BY' => 'rev_timestamp DESC' )
2934 if( $s === false ) {
2935 # No one else ever edited this page
2936 return array(array('cantrollback'));
2937 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2938 # Only admins can see this text
2939 return array(array('notvisiblerev'));
2943 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2944 # Mark all reverted edits as bot
2947 if( $wgUseRCPatrol ) {
2948 # Mark all reverted edits as patrolled
2949 $set['rc_patrolled'] = 1;
2953 $dbw->update( 'recentchanges', $set,
2955 'rc_cur_id' => $current->getPage(),
2956 'rc_user_text' => $current->getUserText(),
2957 "rc_timestamp > '{$s->rev_timestamp}'",
2962 # Generate the edit summary if necessary
2963 $target = Revision
::newFromId( $s->rev_id
);
2964 if( empty( $summary ) ){
2965 $summary = wfMsgForContent( 'revertpage' );
2968 # Allow the custom summary to use the same args as the default message
2970 $target->getUserText(), $from, $s->rev_id
,
2971 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2972 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2974 $summary = wfMsgReplaceArgs( $summary, $args );
2977 $flags = EDIT_UPDATE
;
2979 if( $wgUser->isAllowed('minoredit') )
2980 $flags |
= EDIT_MINOR
;
2982 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2983 $flags |
= EDIT_FORCE_BOT
;
2984 # Actually store the edit
2985 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2986 if( !empty( $status->value
['revision'] ) ) {
2987 $revId = $status->value
['revision']->getId();
2992 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2994 $resultDetails = array(
2995 'summary' => $summary,
2996 'current' => $current,
2997 'target' => $target,
3004 * User interface for rollback operations
3006 public function rollback() {
3007 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3010 $result = $this->doRollback(
3011 $wgRequest->getVal( 'from' ),
3012 $wgRequest->getText( 'summary' ),
3013 $wgRequest->getVal( 'token' ),
3014 $wgRequest->getBool( 'bot' ),
3018 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
3019 $wgOut->rateLimited();
3022 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3023 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3024 $errArray = $result[0];
3025 $errMsg = array_shift( $errArray );
3026 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3027 if( isset( $details['current'] ) ){
3028 $current = $details['current'];
3029 if( $current->getComment() != '' ) {
3030 $wgOut->addWikiMsgArray( 'editcomment', array(
3031 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3036 # Display permissions errors before read-only message -- there's no
3037 # point in misleading the user into thinking the inability to rollback
3038 # is only temporary.
3039 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3040 # array_diff is completely broken for arrays of arrays, sigh. Re-
3041 # move any 'readonlytext' error manually.
3043 foreach( $result as $error ) {
3044 if( $error != array( 'readonlytext' ) ) {
3048 $wgOut->showPermissionsErrorPage( $out );
3051 if( $result == array( array( 'readonlytext' ) ) ) {
3052 $wgOut->readOnlyPage();
3056 $current = $details['current'];
3057 $target = $details['target'];
3058 $newId = $details['newid'];
3059 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3060 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3061 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3062 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3063 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3064 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3065 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3066 $wgOut->returnToMain( false, $this->mTitle
);
3068 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3069 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3070 $de->showDiff( '', '' );
3076 * Do standard deferred updates after page view
3078 public function viewUpdates() {
3079 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3080 # Don't update page view counters on views from bot users (bug 14044)
3081 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
3082 Article
::incViewCount( $this->getID() );
3083 $u = new SiteStatsUpdate( 1, 0, 0 );
3084 array_push( $wgDeferredUpdateList, $u );
3086 # Update newtalk / watchlist notification status
3087 $wgUser->clearNotification( $this->mTitle
);
3091 * Prepare text which is about to be saved.
3092 * Returns a stdclass with source, pst and output members
3094 public function prepareTextForEdit( $text, $revid=null ) {
3095 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
3097 return $this->mPreparedEdit
;
3100 $edit = (object)array();
3101 $edit->revid
= $revid;
3102 $edit->newText
= $text;
3103 $edit->pst
= $this->preSaveTransform( $text );
3104 $options = $this->getParserOptions();
3105 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
3106 $edit->oldText
= $this->getContent();
3107 $this->mPreparedEdit
= $edit;
3112 * Do standard deferred updates after page edit.
3113 * Update links tables, site stats, search index and message cache.
3114 * Purges pages that include this page if the text was changed here.
3115 * Every 100th edit, prune the recent changes table.
3118 * @param $text New text of the article
3119 * @param $summary Edit summary
3120 * @param $minoredit Minor edit
3121 * @param $timestamp_of_pagechange Timestamp associated with the page change
3122 * @param $newid rev_id value of the new revision
3123 * @param $changed Whether or not the content actually changed
3125 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3126 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
3128 wfProfileIn( __METHOD__
);
3131 # Be careful not to double-PST: $text is usually already PST-ed once
3132 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3133 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3134 $editInfo = $this->prepareTextForEdit( $text, $newid );
3136 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3137 $editInfo = $this->mPreparedEdit
;
3140 # Save it to the parser cache
3141 if( $wgEnableParserCache ) {
3142 $popts = $this->getParserOptions();
3143 $parserCache = ParserCache
::singleton();
3144 $parserCache->save( $editInfo->output
, $this, $popts );
3147 # Update the links tables
3148 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3151 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3153 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3154 if( 0 == mt_rand( 0, 99 ) ) {
3155 // Flush old entries from the `recentchanges` table; we do this on
3156 // random requests so as to avoid an increase in writes for no good reason
3158 $dbw = wfGetDB( DB_MASTER
);
3159 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3160 $recentchanges = $dbw->tableName( 'recentchanges' );
3161 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3162 $dbw->query( $sql );
3166 $id = $this->getID();
3167 $title = $this->mTitle
->getPrefixedDBkey();
3168 $shortTitle = $this->mTitle
->getDBkey();
3171 wfProfileOut( __METHOD__
);
3175 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3176 array_push( $wgDeferredUpdateList, $u );
3177 $u = new SearchUpdate( $id, $title, $text );
3178 array_push( $wgDeferredUpdateList, $u );
3180 # If this is another user's talk page, update newtalk
3181 # Don't do this if $changed = false otherwise some idiot can null-edit a
3182 # load of user talk pages and piss people off, nor if it's a minor edit
3183 # by a properly-flagged bot.
3184 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3185 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3186 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3187 $other = User
::newFromName( $shortTitle, false );
3189 wfDebug( __METHOD__
.": invalid username\n" );
3190 } elseif( User
::isIP( $shortTitle ) ) {
3191 // An anonymous user
3192 $other->setNewtalk( true );
3193 } elseif( $other->isLoggedIn() ) {
3194 $other->setNewtalk( true );
3196 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3201 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3202 $wgMessageCache->replace( $shortTitle, $text );
3205 wfProfileOut( __METHOD__
);
3209 * Perform article updates on a special page creation.
3211 * @param $rev Revision object
3213 * @todo This is a shitty interface function. Kill it and replace the
3214 * other shitty functions like editUpdates and such so it's not needed
3217 public function createUpdates( $rev ) {
3218 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3219 $this->mTotalAdjustment
= 1;
3220 $this->editUpdates( $rev->getText(), $rev->getComment(),
3221 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3225 * Generate the navigation links when browsing through an article revisions
3226 * It shows the information as:
3227 * Revision as of \<date\>; view current revision
3228 * \<- Previous version | Next Version -\>
3230 * @param $oldid String: revision ID of this article revision
3232 public function setOldSubtitle( $oldid = 0 ) {
3233 global $wgLang, $wgOut, $wgUser, $wgRequest;
3235 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3239 $revision = Revision
::newFromId( $oldid );
3241 $current = ( $oldid == $this->mLatest
);
3242 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3243 $tddate = $wgLang->date( $this->mTimestamp
, true );
3244 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3245 $sk = $wgUser->getSkin();
3247 ?
wfMsgHtml( 'currentrevisionlink' )
3250 wfMsgHtml( 'currentrevisionlink' ),
3253 array( 'known', 'noclasses' )
3256 ?
wfMsgHtml( 'diff' )
3259 wfMsgHtml( 'diff' ),
3265 array( 'known', 'noclasses' )
3267 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3271 wfMsgHtml( 'previousrevision' ),
3274 'direction' => 'prev',
3277 array( 'known', 'noclasses' )
3279 : wfMsgHtml( 'previousrevision' );
3283 wfMsgHtml( 'diff' ),
3289 array( 'known', 'noclasses' )
3291 : wfMsgHtml( 'diff' );
3292 $nextlink = $current
3293 ?
wfMsgHtml( 'nextrevision' )
3296 wfMsgHtml( 'nextrevision' ),
3299 'direction' => 'next',
3302 array( 'known', 'noclasses' )
3304 $nextdiff = $current
3305 ?
wfMsgHtml( 'diff' )
3308 wfMsgHtml( 'diff' ),
3314 array( 'known', 'noclasses' )
3318 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3319 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
3320 if( $revision->isCurrent() ) {
3321 // We don't handle top deleted edits too well
3322 $cdel = wfMsgHtml( 'rev-delundel' );
3323 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3324 // If revision was hidden from sysops
3325 $cdel = wfMsgHtml( 'rev-delundel' );
3329 wfMsgHtml('rev-delundel'),
3332 'type' => 'revision',
3333 'target' => urlencode( $this->mTitle
->getPrefixedDbkey() ),
3334 'ids' => urlencode( $oldid )
3336 array( 'known', 'noclasses' )
3338 // Bolden oversighted content
3339 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
3340 $cdel = "<strong>$cdel</strong>";
3342 $cdel = "(<small>$cdel</small>) ";
3344 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3345 # Show user links if allowed to see them. If hidden, then show them only if requested...
3346 $userlinks = $sk->revUserTools( $revision, !$unhide );
3348 $m = wfMsg( 'revision-info-current' );
3349 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3350 ?
'revision-info-current'
3353 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3356 array( 'parseinline', 'replaceafter' ),
3364 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3365 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3366 $wgOut->setSubtitle( $r );
3370 * This function is called right before saving the wikitext,
3371 * so we can do things like signatures and links-in-context.
3373 * @param $text String
3375 public function preSaveTransform( $text ) {
3376 global $wgParser, $wgUser;
3377 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3380 /* Caching functions */
3383 * checkLastModified returns true if it has taken care of all
3384 * output to the client that is necessary for this request.
3385 * (that is, it has sent a cached version of the page)
3387 protected function tryFileCache() {
3388 static $called = false;
3390 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3394 if( $this->isFileCacheable() ) {
3395 $cache = new HTMLFileCache( $this->mTitle
);
3396 if( $cache->isFileCacheGood( $this->mTouched
) ) {
3397 wfDebug( "Article::tryFileCache(): about to load file\n" );
3398 $cache->loadFromFileCache();
3401 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3402 ob_start( array(&$cache, 'saveToFileCache' ) );
3405 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3411 * Check if the page can be cached
3414 public function isFileCacheable() {
3416 if( HTMLFileCache
::useFileCache() ) {
3417 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3418 // Extension may have reason to disable file caching on some pages.
3420 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3427 * Loads page_touched and returns a value indicating if it should be used
3430 public function checkTouched() {
3431 if( !$this->mDataLoaded
) {
3432 $this->loadPageData();
3434 return !$this->mIsRedirect
;
3438 * Get the page_touched field
3440 public function getTouched() {
3441 # Ensure that page data has been loaded
3442 if( !$this->mDataLoaded
) {
3443 $this->loadPageData();
3445 return $this->mTouched
;
3449 * Get the page_latest field
3451 public function getLatest() {
3452 if( !$this->mDataLoaded
) {
3453 $this->loadPageData();
3455 return (int)$this->mLatest
;
3459 * Edit an article without doing all that other stuff
3460 * The article must already exist; link tables etc
3461 * are not updated, caches are not flushed.
3463 * @param $text String: text submitted
3464 * @param $comment String: comment submitted
3465 * @param $minor Boolean: whereas it's a minor modification
3467 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3468 wfProfileIn( __METHOD__
);
3470 $dbw = wfGetDB( DB_MASTER
);
3471 $revision = new Revision( array(
3472 'page' => $this->getId(),
3474 'comment' => $comment,
3475 'minor_edit' => $minor ?
1 : 0,
3477 $revision->insertOn( $dbw );
3478 $this->updateRevisionOn( $dbw, $revision );
3480 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3482 wfProfileOut( __METHOD__
);
3486 * Used to increment the view counter
3488 * @param $id Integer: article id
3490 public static function incViewCount( $id ) {
3491 $id = intval( $id );
3492 global $wgHitcounterUpdateFreq, $wgDBtype;
3494 $dbw = wfGetDB( DB_MASTER
);
3495 $pageTable = $dbw->tableName( 'page' );
3496 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3497 $acchitsTable = $dbw->tableName( 'acchits' );
3499 if( $wgHitcounterUpdateFreq <= 1 ) {
3500 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3504 # Not important enough to warrant an error page in case of failure
3505 $oldignore = $dbw->ignoreErrors( true );
3507 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3509 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3510 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3511 # Most of the time (or on SQL errors), skip row count check
3512 $dbw->ignoreErrors( $oldignore );
3516 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3517 $row = $dbw->fetchObject( $res );
3518 $rown = intval( $row->n
);
3519 if( $rown >= $wgHitcounterUpdateFreq ){
3520 wfProfileIn( 'Article::incViewCount-collect' );
3521 $old_user_abort = ignore_user_abort( true );
3523 if($wgDBtype == 'mysql')
3524 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3525 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3526 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3527 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3529 $dbw->query("DELETE FROM $hitcounterTable");
3530 if($wgDBtype == 'mysql') {
3531 $dbw->query('UNLOCK TABLES');
3532 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3533 'WHERE page_id = hc_id');
3536 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3537 "FROM $acchitsTable WHERE page_id = hc_id");
3539 $dbw->query("DROP TABLE $acchitsTable");
3541 ignore_user_abort( $old_user_abort );
3542 wfProfileOut( 'Article::incViewCount-collect' );
3544 $dbw->ignoreErrors( $oldignore );
3548 * The onArticle*() functions are supposed to be a kind of hooks
3549 * which should be called whenever any of the specified actions
3552 * This is a good place to put code to clear caches, for instance.
3554 * This is called on page move and undelete, as well as edit
3556 * @param $title a title object
3559 public static function onArticleCreate( $title ) {
3560 # Update existence markers on article/talk tabs...
3561 if( $title->isTalkPage() ) {
3562 $other = $title->getSubjectPage();
3564 $other = $title->getTalkPage();
3566 $other->invalidateCache();
3567 $other->purgeSquid();
3569 $title->touchLinks();
3570 $title->purgeSquid();
3571 $title->deleteTitleProtection();
3574 public static function onArticleDelete( $title ) {
3575 global $wgMessageCache;
3576 # Update existence markers on article/talk tabs...
3577 if( $title->isTalkPage() ) {
3578 $other = $title->getSubjectPage();
3580 $other = $title->getTalkPage();
3582 $other->invalidateCache();
3583 $other->purgeSquid();
3585 $title->touchLinks();
3586 $title->purgeSquid();
3589 HTMLFileCache
::clearFileCache( $title );
3592 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3593 $wgMessageCache->replace( $title->getDBkey(), false );
3596 if( $title->getNamespace() == NS_FILE
) {
3597 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3598 $update->doUpdate();
3601 if( $title->getNamespace() == NS_USER_TALK
) {
3602 $user = User
::newFromName( $title->getText(), false );
3603 $user->setNewtalk( false );
3606 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3610 * Purge caches on page update etc
3612 public static function onArticleEdit( $title, $flags = '' ) {
3613 global $wgDeferredUpdateList;
3615 // Invalidate caches of articles which include this page
3616 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3618 // Invalidate the caches of all pages which redirect here
3619 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3621 # Purge squid for this page only
3622 $title->purgeSquid();
3624 # Clear file cache for this page only
3625 HTMLFileCache
::clearFileCache( $title );
3631 * Overriden by ImagePage class, only present here to avoid a fatal error
3632 * Called for ?action=revert
3634 public function revert() {
3636 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3640 * Info about this page
3641 * Called for ?action=info when $wgAllowPageInfo is on.
3643 public function info() {
3644 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3646 if( !$wgAllowPageInfo ) {
3647 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3651 $page = $this->mTitle
->getSubjectPage();
3653 $wgOut->setPagetitle( $page->getPrefixedText() );
3654 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3655 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3657 if( !$this->mTitle
->exists() ) {
3658 $wgOut->addHTML( '<div class="noarticletext">' );
3659 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3660 // This doesn't quite make sense; the user is asking for
3661 // information about the _page_, not the message... -- RC
3662 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3664 $msg = $wgUser->isLoggedIn()
3666 : 'noarticletextanon';
3667 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3669 $wgOut->addHTML( '</div>' );
3671 $dbr = wfGetDB( DB_SLAVE
);
3673 'wl_title' => $page->getDBkey(),
3674 'wl_namespace' => $page->getNamespace() );
3675 $numwatchers = $dbr->selectField(
3680 $this->getSelectOptions() );
3682 $pageInfo = $this->pageCountInfo( $page );
3683 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3685 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3686 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3688 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3690 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3692 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3694 $wgOut->addHTML( '</ul>' );
3699 * Return the total number of edits and number of unique editors
3700 * on a given page. If page does not exist, returns false.
3702 * @param $title Title object
3705 public function pageCountInfo( $title ) {
3706 $id = $title->getArticleId();
3710 $dbr = wfGetDB( DB_SLAVE
);
3711 $rev_clause = array( 'rev_page' => $id );
3712 $edits = $dbr->selectField(
3717 $this->getSelectOptions()
3719 $authors = $dbr->selectField(
3721 'COUNT(DISTINCT rev_user_text)',
3724 $this->getSelectOptions()
3726 return array( 'edits' => $edits, 'authors' => $authors );
3730 * Return a list of templates used by this article.
3731 * Uses the templatelinks table
3733 * @return Array of Title objects
3735 public function getUsedTemplates() {
3737 $id = $this->mTitle
->getArticleID();
3741 $dbr = wfGetDB( DB_SLAVE
);
3742 $res = $dbr->select( array( 'templatelinks' ),
3743 array( 'tl_namespace', 'tl_title' ),
3744 array( 'tl_from' => $id ),
3746 if( $res !== false ) {
3747 foreach( $res as $row ) {
3748 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3751 $dbr->freeResult( $res );
3756 * Returns a list of hidden categories this page is a member of.
3757 * Uses the page_props and categorylinks tables.
3759 * @return Array of Title objects
3761 public function getHiddenCategories() {
3763 $id = $this->mTitle
->getArticleID();
3767 $dbr = wfGetDB( DB_SLAVE
);
3768 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3770 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3771 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3773 if( $res !== false ) {
3774 foreach( $res as $row ) {
3775 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3778 $dbr->freeResult( $res );
3783 * Return an applicable autosummary if one exists for the given edit.
3784 * @param $oldtext String: the previous text of the page.
3785 * @param $newtext String: The submitted text of the page.
3786 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3787 * @return string An appropriate autosummary, or an empty string.
3789 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3790 # Decide what kind of autosummary is needed.
3792 # Redirect autosummaries
3793 $ot = Title
::newFromRedirect( $oldtext );
3794 $rt = Title
::newFromRedirect( $newtext );
3795 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3796 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3799 # New page autosummaries
3800 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3801 # If they're making a new article, give its text, truncated, in the summary.
3803 $truncatedtext = $wgContLang->truncate(
3804 str_replace("\n", ' ', $newtext),
3805 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3806 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3809 # Blanking autosummaries
3810 if( $oldtext != '' && $newtext == '' ) {
3811 return wfMsgForContent( 'autosumm-blank' );
3812 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3813 # Removing more than 90% of the article
3815 $truncatedtext = $wgContLang->truncate(
3817 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3818 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3821 # If we reach this point, there's no applicable autosummary for our case, so our
3822 # autosummary is empty.
3827 * Add the primary page-view wikitext to the output buffer
3828 * Saves the text into the parser cache if possible.
3829 * Updates templatelinks if it is out of date.
3831 * @param $text String
3832 * @param $cache Boolean
3834 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
3837 $parserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
3838 $wgOut->addParserOutput( $parserOutput );
3842 * This does all the heavy lifting for outputWikitext, except it returns the parser
3843 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
3844 * say, embedding thread pages within a discussion system (LiquidThreads)
3846 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
3847 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3849 if ( !$parserOptions ) {
3850 $parserOptions = $this->getParserOptions();
3854 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3855 $parserOptions, true, true, $this->getRevIdFetched() );
3860 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3861 $this->mTitle
->getPrefixedDBkey()));
3864 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3865 $parserCache = ParserCache
::singleton();
3866 $parserCache->save( $parserOutput, $this, $parserOptions );
3868 // Make sure file cache is not used on uncacheable content.
3869 // Output that has magic words in it can still use the parser cache
3870 // (if enabled), though it will generally expire sooner.
3871 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3872 $wgUseFileCache = false;
3874 $this->doCascadeProtectionUpdates( $parserOutput );
3875 return $parserOutput;
3879 * Get parser options suitable for rendering the primary article wikitext
3881 public function getParserOptions() {
3883 if ( !$this->mParserOptions
) {
3884 $this->mParserOptions
= new ParserOptions( $wgUser );
3885 $this->mParserOptions
->setTidy( true );
3886 $this->mParserOptions
->enableLimitReport();
3888 return $this->mParserOptions
;
3891 protected function doCascadeProtectionUpdates( $parserOutput ) {
3892 if( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3896 // templatelinks table may have become out of sync,
3897 // especially if using variable-based transclusions.
3898 // For paranoia, check if things have changed and if
3899 // so apply updates to the database. This will ensure
3900 // that cascaded protections apply as soon as the changes
3903 # Get templates from templatelinks
3904 $id = $this->mTitle
->getArticleID();
3906 $tlTemplates = array();
3908 $dbr = wfGetDB( DB_SLAVE
);
3909 $res = $dbr->select( array( 'templatelinks' ),
3910 array( 'tl_namespace', 'tl_title' ),
3911 array( 'tl_from' => $id ),
3915 foreach( $res as $row ) {
3916 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3919 # Get templates from parser output.
3920 $poTemplates = array();
3921 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3922 foreach ( $templates as $dbk => $id ) {
3923 $poTemplates["$ns:$dbk"] = true;
3928 # Note that we simulate array_diff_key in PHP <5.0.x
3929 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3931 if( count( $templates_diff ) > 0 ) {
3932 # Whee, link updates time.
3933 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3939 * Update all the appropriate counts in the category table, given that
3940 * we've added the categories $added and deleted the categories $deleted.
3942 * @param $added array The names of categories that were added
3943 * @param $deleted array The names of categories that were deleted
3946 public function updateCategoryCounts( $added, $deleted ) {
3947 $ns = $this->mTitle
->getNamespace();
3948 $dbw = wfGetDB( DB_MASTER
);
3950 # First make sure the rows exist. If one of the "deleted" ones didn't
3951 # exist, we might legitimately not create it, but it's simpler to just
3952 # create it and then give it a negative value, since the value is bogus
3955 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3956 $insertCats = array_merge( $added, $deleted );
3957 if( !$insertCats ) {
3958 # Okay, nothing to do
3961 $insertRows = array();
3962 foreach( $insertCats as $cat ) {
3963 $insertRows[] = array( 'cat_title' => $cat );
3965 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3967 $addFields = array( 'cat_pages = cat_pages + 1' );
3968 $removeFields = array( 'cat_pages = cat_pages - 1' );
3969 if( $ns == NS_CATEGORY
) {
3970 $addFields[] = 'cat_subcats = cat_subcats + 1';
3971 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3972 } elseif( $ns == NS_FILE
) {
3973 $addFields[] = 'cat_files = cat_files + 1';
3974 $removeFields[] = 'cat_files = cat_files - 1';
3981 array( 'cat_title' => $added ),
3989 array( 'cat_title' => $deleted ),
3995 /** Lightweight method to get the parser output for a page, checking the parser cache
3996 * and so on. Doesn't consider most of the stuff that Article::view is forced to
3997 * consider, so it's not appropriate to use there. */
3998 function getParserOutput( $oldid = null ) {
3999 global $wgEnableParserCache, $wgUser, $wgOut;
4001 // Should the parser cache be used?
4002 $useParserCache = $wgEnableParserCache &&
4003 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4007 wfDebug( __METHOD__
.': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4008 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4009 wfIncrStats( 'pcache_miss_stub' );
4012 $parserOutput = false;
4013 if ( $useParserCache ) {
4014 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4017 if ( $parserOutput === false ) {
4018 // Cache miss; parse and output it.
4019 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4021 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4023 return $parserOutput;