8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
19 var $mComment = ''; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
37 var $mTimestamp = ''; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
46 * Constructor and clear the article
47 * @param $title Reference to a Title object.
48 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 public function __construct( Title
$title, $oldId = null ) {
51 $this->mTitle
=& $title;
52 $this->mOldId
= $oldId;
56 * Constructor from an article article
57 * @param $id The article ID to load
59 public static function newFromID( $id ) {
60 $t = Title
::newFromID( $id );
61 return $t == null ?
null : new Article( $t );
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
69 public function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom
= $from;
74 * If this page is a redirect, get its target
76 * The target will be fetched from the redirect table if possible.
77 * If this page doesn't have an entry there, call insertRedirect()
78 * @return mixed Title object, or null if this page is not a redirect
80 public function getRedirectTarget() {
81 if( !$this->mTitle ||
!$this->mTitle
->isRedirect() )
83 if( !is_null($this->mRedirectTarget
) )
84 return $this->mRedirectTarget
;
85 # Query the redirect table
86 $dbr = wfGetDB( DB_SLAVE
);
87 $res = $dbr->select( 'redirect',
88 array('rd_namespace', 'rd_title'),
89 array('rd_from' => $this->getID()),
92 if( $row = $dbr->fetchObject($res) ) {
93 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
95 # This page doesn't have an entry in the redirect table
96 return $this->mRedirectTarget
= $this->insertRedirect();
100 * Insert an entry for this page into the redirect table.
102 * Don't call this function directly unless you know what you're doing.
103 * @return Title object
105 public function insertRedirect() {
106 $retval = Title
::newFromRedirect( $this->getContent() );
110 $dbw = wfGetDB( DB_MASTER
);
111 $dbw->replace( 'redirect', array('rd_from'),
113 'rd_from' => $this->getID(),
114 'rd_namespace' => $retval->getNamespace(),
115 'rd_title' => $retval->getDBKey()
123 * Get the Title object this page redirects to
125 * @return mixed false, Title of in-wiki target, or string with URL
127 public function followRedirect() {
128 $text = $this->getContent();
129 return $this->followRedirectText( $text );
133 * Get the Title object this text redirects to
135 * @return mixed false, Title of in-wiki target, or string with URL
137 public function followRedirectText( $text ) {
138 $rt = Title
::newFromRedirect( $text );
139 # process if title object is valid and not special:userlogout
141 if( $rt->getInterwiki() != '' ) {
142 if( $rt->isLocal() ) {
143 // Offsite wikis need an HTTP redirect.
145 // This can be hard to reverse and may produce loops,
146 // so they may be disabled in the site configuration.
147 $source = $this->mTitle
->getFullURL( 'redirect=no' );
148 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
151 if( $rt->getNamespace() == NS_SPECIAL
) {
152 // Gotta handle redirects to special pages differently:
153 // Fill the HTTP response "Location" header and ignore
154 // the rest of the page we're on.
156 // This can be hard to reverse, so they may be disabled.
157 if( $rt->isSpecial( 'Userlogout' ) ) {
160 return $rt->getFullURL();
166 // No or invalid redirect
171 * get the title object of the article
173 public function getTitle() {
174 return $this->mTitle
;
181 public function clear() {
182 $this->mDataLoaded
= false;
183 $this->mContentLoaded
= false;
185 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
186 $this->mRedirectedFrom
= null; # Title object if set
187 $this->mRedirectTarget
= null; # Title object if set
189 $this->mTimestamp
= $this->mComment
= '';
190 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
191 $this->mTouched
= '19700101000000';
192 $this->mForUpdate
= false;
193 $this->mIsRedirect
= false;
194 $this->mRevIdFetched
= 0;
195 $this->mRedirectUrl
= false;
196 $this->mLatest
= false;
197 $this->mPreparedEdit
= false;
201 * Note that getContent/loadContent do not follow redirects anymore.
202 * If you need to fetch redirectable content easily, try
203 * the shortcut in Article::followContent()
205 * @return Return the text of this revision
207 public function getContent() {
208 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
209 wfProfileIn( __METHOD__
);
210 if( $this->getID() === 0 ) {
211 # If this is a MediaWiki:x message, then load the messages
212 # and return the message value for x.
213 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
214 # If this is a system message, get the default text.
215 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
216 $wgMessageCache->loadAllMessages( $lang );
217 $text = wfMsgGetKey( $message, false, $lang, false );
218 if( wfEmptyMsg( $message, $text ) )
221 $text = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
223 wfProfileOut( __METHOD__
);
226 $this->loadContent();
227 wfProfileOut( __METHOD__
);
228 return $this->mContent
;
233 * This function returns the text of a section, specified by a number ($section).
234 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
235 * the first section before any such heading (section 0).
237 * If a section contains subsections, these are also returned.
239 * @param $text String: text to look in
240 * @param $section Integer: section number
241 * @return string text of the requested section
244 public function getSection( $text, $section ) {
246 return $wgParser->getSection( $text, $section );
250 * @return int The oldid of the article that is to be shown, 0 for the
253 public function getOldID() {
254 if( is_null( $this->mOldId
) ) {
255 $this->mOldId
= $this->getOldIDFromRequest();
257 return $this->mOldId
;
261 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
263 * @return int The old id for the request
265 public function getOldIDFromRequest() {
267 $this->mRedirectUrl
= false;
268 $oldid = $wgRequest->getVal( 'oldid' );
269 if( isset( $oldid ) ) {
270 $oldid = intval( $oldid );
271 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
272 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
276 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
278 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
279 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
292 * Load the revision (including text) into this object
294 function loadContent() {
295 if( $this->mContentLoaded
) return;
296 wfProfileIn( __METHOD__
);
298 $oldid = $this->getOldID();
299 # Pre-fill content with error message so that if something
300 # fails we'll have something telling us what we intended.
301 $this->mOldId
= $oldid;
302 $this->fetchContent( $oldid );
303 wfProfileOut( __METHOD__
);
308 * Fetch a page record with the given conditions
309 * @param $dbr Database object
310 * @param $conditions Array
312 protected function pageData( $dbr, $conditions ) {
326 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
327 $row = $dbr->selectRow(
333 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
338 * @param $dbr Database object
339 * @param $title Title object
341 public function pageDataFromTitle( $dbr, $title ) {
342 return $this->pageData( $dbr, array(
343 'page_namespace' => $title->getNamespace(),
344 'page_title' => $title->getDBkey() ) );
348 * @param $dbr Database
351 protected function pageDataFromId( $dbr, $id ) {
352 return $this->pageData( $dbr, array( 'page_id' => $id ) );
356 * Set the general counter, title etc data loaded from
359 * @param $data Database row object or "fromdb"
361 public function loadPageData( $data = 'fromdb' ) {
362 if( $data === 'fromdb' ) {
363 $dbr = wfGetDB( DB_MASTER
);
364 $data = $this->pageDataFromId( $dbr, $this->getId() );
367 $lc = LinkCache
::singleton();
369 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
371 $this->mTitle
->mArticleID
= $data->page_id
;
373 # Old-fashioned restrictions
374 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
376 $this->mCounter
= $data->page_counter
;
377 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
378 $this->mIsRedirect
= $data->page_is_redirect
;
379 $this->mLatest
= $data->page_latest
;
381 if( is_object( $this->mTitle
) ) {
382 $lc->addBadLinkObj( $this->mTitle
);
384 $this->mTitle
->mArticleID
= 0;
387 $this->mDataLoaded
= true;
391 * Get text of an article from database
392 * Does *NOT* follow redirects.
393 * @param $oldid Int: 0 for whatever the latest revision is
396 function fetchContent( $oldid = 0 ) {
397 if( $this->mContentLoaded
) {
398 return $this->mContent
;
401 $dbr = wfGetDB( DB_MASTER
);
403 # Pre-fill content with error message so that if something
404 # fails we'll have something telling us what we intended.
405 $t = $this->mTitle
->getPrefixedText();
406 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
407 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
410 $revision = Revision
::newFromId( $oldid );
411 if( is_null( $revision ) ) {
412 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
415 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
417 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
420 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
421 $this->loadPageData( $data );
423 if( !$this->mDataLoaded
) {
424 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
426 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
429 $this->loadPageData( $data );
431 $revision = Revision
::newFromId( $this->mLatest
);
432 if( is_null( $revision ) ) {
433 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
438 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
439 // We should instead work with the Revision object when we need it...
440 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
442 $this->mUser
= $revision->getUser();
443 $this->mUserText
= $revision->getUserText();
444 $this->mComment
= $revision->getComment();
445 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
447 $this->mRevIdFetched
= $revision->getId();
448 $this->mContentLoaded
= true;
449 $this->mRevision
=& $revision;
451 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
453 return $this->mContent
;
457 * Read/write accessor to select FOR UPDATE
459 * @param $x Mixed: FIXME
461 public function forUpdate( $x = NULL ) {
462 return wfSetVar( $this->mForUpdate
, $x );
466 * Get the database which should be used for reads
469 * @deprecated - just call wfGetDB( DB_MASTER ) instead
472 wfDeprecated( __METHOD__
);
473 return wfGetDB( DB_MASTER
);
477 * Get options for all SELECT statements
479 * @param $options Array: an optional options array which'll be appended to
481 * @return Array: options
483 protected function getSelectOptions( $options = '' ) {
484 if( $this->mForUpdate
) {
485 if( is_array( $options ) ) {
486 $options[] = 'FOR UPDATE';
488 $options = 'FOR UPDATE';
495 * @return int Page ID
497 public function getID() {
498 if( $this->mTitle
) {
499 return $this->mTitle
->getArticleID();
506 * @return bool Whether or not the page exists in the database
508 public function exists() {
509 return $this->getId() > 0;
513 * @return int The view count for the page
515 public function getCount() {
516 if( -1 == $this->mCounter
) {
517 $id = $this->getID();
521 $dbr = wfGetDB( DB_SLAVE
);
522 $this->mCounter
= $dbr->selectField( 'page',
524 array( 'page_id' => $id ),
526 $this->getSelectOptions()
530 return $this->mCounter
;
534 * Determine whether a page would be suitable for being counted as an
535 * article in the site_stats table based on the title & its content
537 * @param $text String: text to analyze
540 public function isCountable( $text ) {
541 global $wgUseCommaCount;
543 $token = $wgUseCommaCount ?
',' : '[[';
544 return $this->mTitle
->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
548 * Tests if the article text represents a redirect
550 * @param $text String: FIXME
553 public function isRedirect( $text = false ) {
554 if( $text === false ) {
555 if( $this->mDataLoaded
) {
556 return $this->mIsRedirect
;
558 // Apparently loadPageData was never called
559 $this->loadContent();
560 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
562 $titleObj = Title
::newFromRedirect( $text );
564 return $titleObj !== NULL;
568 * Returns true if the currently-referenced revision is the current edit
569 * to this page (and it exists).
572 public function isCurrent() {
573 # If no oldid, this is the current version.
574 if( $this->getOldID() == 0 ) {
577 return $this->exists() && isset($this->mRevision
) && $this->mRevision
->isCurrent();
581 * Loads everything except the text
582 * This isn't necessary for all uses, so it's only done if needed.
584 protected function loadLastEdit() {
585 if( -1 != $this->mUser
)
588 # New or non-existent articles have no user information
589 $id = $this->getID();
590 if( 0 == $id ) return;
592 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
593 if( !is_null( $this->mLastRevision
) ) {
594 $this->mUser
= $this->mLastRevision
->getUser();
595 $this->mUserText
= $this->mLastRevision
->getUserText();
596 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
597 $this->mComment
= $this->mLastRevision
->getComment();
598 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
599 $this->mRevIdFetched
= $this->mLastRevision
->getId();
603 public function getTimestamp() {
604 // Check if the field has been filled by ParserCache::get()
605 if( !$this->mTimestamp
) {
606 $this->loadLastEdit();
608 return wfTimestamp(TS_MW
, $this->mTimestamp
);
611 public function getUser() {
612 $this->loadLastEdit();
616 public function getUserText() {
617 $this->loadLastEdit();
618 return $this->mUserText
;
621 public function getComment() {
622 $this->loadLastEdit();
623 return $this->mComment
;
626 public function getMinorEdit() {
627 $this->loadLastEdit();
628 return $this->mMinorEdit
;
631 /* Use this to fetch the rev ID used on page views */
632 public function getRevIdFetched() {
633 $this->loadLastEdit();
634 return $this->mRevIdFetched
;
638 * @param $limit Integer: default 0.
639 * @param $offset Integer: default 0.
641 public function getContributors($limit = 0, $offset = 0) {
642 # XXX: this is expensive; cache this info somewhere.
645 $dbr = wfGetDB( DB_SLAVE
);
646 $revTable = $dbr->tableName( 'revision' );
647 $userTable = $dbr->tableName( 'user' );
648 $user = $this->getUser();
649 $pageId = $this->getId();
651 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
652 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
653 WHERE rev_page = $pageId
654 AND rev_user != $user
655 GROUP BY rev_user, rev_user_text, user_real_name
656 ORDER BY timestamp DESC";
658 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
659 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
661 $sql .= ' '. $this->getSelectOptions();
663 $res = $dbr->query($sql, __METHOD__
);
665 return new UserArrayFromResult( $res );
669 * This is the default action of the script: just view the page of
672 public function view() {
673 global $wgUser, $wgOut, $wgRequest, $wgContLang;
674 global $wgEnableParserCache, $wgStylePath, $wgParser;
675 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
676 global $wgDefaultRobotPolicy;
678 wfProfileIn( __METHOD__
);
680 # Get variables from query string
681 $oldid = $this->getOldID();
684 if( $oldid === 0 && $this->checkTouched() ) {
687 $parserCache = ParserCache
::singleton();
688 $wgOut->setETag( $parserCache->getETag($this,$wgUser) );
690 if( $wgOut->checkLastModified( $this->getTouched() ) ){
691 wfProfileOut( __METHOD__
);
693 } else if( $this->tryFileCache() ) {
694 # tell wgOut that output is taken care of
696 $this->viewUpdates();
697 wfProfileOut( __METHOD__
);
702 $ns = $this->mTitle
->getNamespace(); # shortcut
703 $sk = $wgUser->getSkin();
705 # getOldID may want us to redirect somewhere else
706 if( $this->mRedirectUrl
) {
707 $wgOut->redirect( $this->mRedirectUrl
);
708 wfProfileOut( __METHOD__
);
712 $diff = $wgRequest->getVal( 'diff' );
713 $rcid = $wgRequest->getVal( 'rcid' );
714 $rdfrom = $wgRequest->getVal( 'rdfrom' );
715 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
716 $purge = $wgRequest->getVal( 'action' ) == 'purge';
718 $wgOut->setArticleFlag( true );
720 # Discourage indexing of printable versions, but encourage following
721 if( $wgOut->isPrintable() ) {
722 $policy = 'noindex,follow';
723 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
724 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
725 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
726 # Honour customised robot policies for this namespace
727 $policy = $wgNamespaceRobotPolicies[$ns];
729 $policy = $wgDefaultRobotPolicy;
731 $wgOut->setRobotPolicy( $policy );
733 # If we got diff and oldid in the query, we want to see a
734 # diff page instead of the article.
736 if( !is_null( $diff ) ) {
737 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
739 $diff = $wgRequest->getVal( 'diff' );
740 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
741 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
742 // DifferenceEngine directly fetched the revision:
743 $this->mRevIdFetched
= $de->mNewid
;
744 $de->showDiffPage( $diffOnly );
746 // Needed to get the page's current revision
747 $this->loadPageData();
748 if( $diff == 0 ||
$diff == $this->mLatest
) {
749 # Run view updates for current revision only
750 $this->viewUpdates();
752 wfProfileOut( __METHOD__
);
756 # Should the parser cache be used?
757 $pcache = $this->useParserCache( $oldid );
758 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
759 if( $wgUser->getOption( 'stubthreshold' ) ) {
760 wfIncrStats( 'pcache_miss_stub' );
763 $wasRedirected = false;
764 if( isset( $this->mRedirectedFrom
) ) {
765 // This is an internally redirected page view.
766 // We'll need a backlink to the source page for navigation.
767 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
768 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
769 $s = wfMsg( 'redirectedfrom', $redir );
770 $wgOut->setSubtitle( $s );
772 // Set the fragment if one was specified in the redirect
773 if( strval( $this->mTitle
->getFragment() ) != '' ) {
774 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
775 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
777 $wasRedirected = true;
779 } elseif( !empty( $rdfrom ) ) {
780 // This is an externally redirected view, from some other wiki.
781 // If it was reported from a trusted site, supply a backlink.
782 global $wgRedirectSources;
783 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
784 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
785 $s = wfMsg( 'redirectedfrom', $redir );
786 $wgOut->setSubtitle( $s );
787 $wasRedirected = true;
792 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
793 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
794 // Ensure that UI elements requiring revision ID have
795 // the correct version information.
796 $wgOut->setRevisionId( $this->mLatest
);
799 # Fetch content and check for errors
801 # If the article does not exist and was deleted, show the log
802 if( $this->getID() == 0 ) {
803 $this->showDeletionLog();
805 $text = $this->getContent();
806 if( $text === false ) {
807 # Failed to load, replace text with error message
808 $t = $this->mTitle
->getPrefixedText();
810 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
811 $text = wfMsg( 'missing-article', $t, $d );
813 $text = wfMsg( 'noarticletext' );
817 if( $this->getID() === 0 ) {
818 $wgOut->setRobotPolicy( 'noindex,nofollow' );
819 $text = "<div class='noarticletext'>\n$text\n</div>";
822 # Another whitelist check in case oldid is altering the title
823 if( !$this->mTitle
->userCanRead() ) {
824 $wgOut->loginToUse();
826 wfProfileOut( __METHOD__
);
830 # We're looking at an old revision
831 if( !empty( $oldid ) ) {
832 $wgOut->setRobotPolicy( 'noindex,nofollow' );
833 if( is_null( $this->mRevision
) ) {
834 // FIXME: This would be a nice place to load the 'no such page' text.
836 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
837 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
838 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
839 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
840 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
841 wfProfileOut( __METHOD__
);
844 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
845 // and we are allowed to see...
851 $wgOut->setRevisionId( $this->getRevIdFetched() );
853 // Pages containing custom CSS or JavaScript get special treatment
854 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
855 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
856 // Give hooks a chance to customise the output
857 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
858 // Wrap the whole lot in a <pre> and don't parse
860 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
861 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
862 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
863 $wgOut->addHTML( "\n</pre>\n" );
865 } else if( $rt = Title
::newFromRedirect( $text ) ) {
866 # Don't append the subtitle if this was an old revision
867 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
868 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
869 $wgOut->addParserOutputNoText( $parseout );
870 } else if( $pcache ) {
871 # Display content and save to parser cache
872 $this->outputWikiText( $text );
874 # Display content, don't attempt to save to parser cache
875 # Don't show section-edit links on old revisions... this way lies madness.
876 if( !$this->isCurrent() ) {
877 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
879 # Display content and don't save to parser cache
880 # With timing hack -- TS 2006-07-26
882 $this->outputWikiText( $text, false );
887 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
888 $this->mTitle
->getPrefixedDBkey()));
891 if( !$this->isCurrent() ) {
892 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
896 /* title may have been set from the cache */
897 $t = $wgOut->getPageTitle();
899 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
901 # For the main page, overwrite the <title> element with the con-
902 # tents of 'pagetitle-view-mainpage' instead of the default (if
904 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
905 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
906 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
910 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
911 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
912 $wgOut->addWikiMsg('anontalkpagetext');
915 # If we have been passed an &rcid= parameter, we want to give the user a
916 # chance to mark this new article as patrolled.
917 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
919 "<div class='patrollink'>" .
920 wfMsgHtml( 'markaspatrolledlink',
921 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
922 "action=markpatrolled&rcid=$rcid" )
929 if( $wgUseTrackbacks ) {
930 $this->addTrackbacks();
933 $this->viewUpdates();
934 wfProfileOut( __METHOD__
);
937 protected function showDeletionLog() {
938 global $wgUser, $wgOut;
939 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
940 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
941 if( $pager->getNumRows() > 0 ) {
943 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
944 $wgOut->addWikiMsg( 'deleted-notice' );
946 $loglist->beginLogEventsList() .
948 $loglist->endLogEventsList()
950 if( $pager->getNumRows() > 10 ) {
951 $wgOut->addHTML( $wgUser->getSkin()->link(
952 SpecialPage
::getTitleFor( 'Log' ),
953 wfMsgHtml( 'deletelog-fulllog' ),
955 array( 'type' => 'delete', 'page' => $this->mTitle
->getPrefixedText() )
958 $wgOut->addHTML( '</div>' );
963 * Should the parser cache be used?
965 protected function useParserCache( $oldid ) {
966 global $wgUser, $wgEnableParserCache;
968 return $wgEnableParserCache
969 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
972 && !$this->mTitle
->isCssOrJsPage()
973 && !$this->mTitle
->isCssJsSubpage();
978 * @param $target Title object of destination to redirect
979 * @param $appendSubtitle Boolean [optional]
980 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
982 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
983 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
985 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
986 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
988 if( $appendSubtitle ) {
989 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
991 $sk = $wgUser->getSkin();
993 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
995 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
997 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
998 '<span class="redirectText">'.$link.'</span>';
1002 public function addTrackbacks() {
1003 global $wgOut, $wgUser;
1004 $dbr = wfGetDB( DB_SLAVE
);
1005 $tbs = $dbr->select( 'trackbacks',
1006 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1007 array('tb_page' => $this->getID() )
1009 if( !$dbr->numRows($tbs) ) return;
1012 while( $o = $dbr->fetchObject($tbs) ) {
1014 if( $wgUser->isAllowed( 'trackback' ) ) {
1015 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1016 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1017 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1020 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1027 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1028 $this->mTitle
->invalidateCache();
1031 public function deletetrackback() {
1032 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1033 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1034 $wgOut->addWikiMsg( 'sessionfailure' );
1038 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1039 if( count($permission_errors) ) {
1040 $wgOut->showPermissionsErrorPage( $permission_errors );
1044 $db = wfGetDB( DB_MASTER
);
1045 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1047 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1048 $this->mTitle
->invalidateCache();
1051 public function render() {
1053 $wgOut->setArticleBodyOnly(true);
1058 * Handle action=purge
1060 public function purge() {
1061 global $wgUser, $wgRequest, $wgOut;
1062 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1063 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1068 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1069 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1070 $form = "<form method=\"post\" action=\"$action\">\n" .
1071 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1073 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1074 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1075 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1076 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1077 $wgOut->addHTML( $top . $form . $bottom );
1082 * Perform the actions of a page purging
1084 public function doPurge() {
1086 // Invalidate the cache
1087 $this->mTitle
->invalidateCache();
1090 // Commit the transaction before the purge is sent
1091 $dbw = wfGetDB( DB_MASTER
);
1092 $dbw->immediateCommit();
1095 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1096 $update->doUpdate();
1098 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1099 global $wgMessageCache;
1100 if( $this->getID() == 0 ) {
1103 $text = $this->getContent();
1105 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1110 * Insert a new empty page record for this article.
1111 * This *must* be followed up by creating a revision
1112 * and running $this->updateToLatest( $rev_id );
1113 * or else the record will be left in a funky state.
1114 * Best if all done inside a transaction.
1116 * @param $dbw Database
1117 * @return int The newly created page_id key, or false if the title already existed
1120 public function insertOn( $dbw ) {
1121 wfProfileIn( __METHOD__
);
1123 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1124 $dbw->insert( 'page', array(
1125 'page_id' => $page_id,
1126 'page_namespace' => $this->mTitle
->getNamespace(),
1127 'page_title' => $this->mTitle
->getDBkey(),
1128 'page_counter' => 0,
1129 'page_restrictions' => '',
1130 'page_is_redirect' => 0, # Will set this shortly...
1132 'page_random' => wfRandom(),
1133 'page_touched' => $dbw->timestamp(),
1134 'page_latest' => 0, # Fill this in shortly...
1135 'page_len' => 0, # Fill this in shortly...
1136 ), __METHOD__
, 'IGNORE' );
1138 $affected = $dbw->affectedRows();
1140 $newid = $dbw->insertId();
1141 $this->mTitle
->resetArticleId( $newid );
1143 wfProfileOut( __METHOD__
);
1144 return $affected ?
$newid : false;
1148 * Update the page record to point to a newly saved revision.
1150 * @param $dbw Database object
1151 * @param $revision Revision: For ID number, and text used to set
1152 length and redirect status fields
1153 * @param $lastRevision Integer: if given, will not overwrite the page field
1154 * when different from the currently set value.
1155 * Giving 0 indicates the new page flag should be set
1157 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1158 * removing rows in redirect table.
1159 * @return bool true on success, false on failure
1162 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1163 wfProfileIn( __METHOD__
);
1165 $text = $revision->getText();
1166 $rt = Title
::newFromRedirect( $text );
1168 $conditions = array( 'page_id' => $this->getId() );
1169 if( !is_null( $lastRevision ) ) {
1170 # An extra check against threads stepping on each other
1171 $conditions['page_latest'] = $lastRevision;
1174 $dbw->update( 'page',
1176 'page_latest' => $revision->getId(),
1177 'page_touched' => $dbw->timestamp(),
1178 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1179 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1180 'page_len' => strlen( $text ),
1185 $result = $dbw->affectedRows() != 0;
1187 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1190 wfProfileOut( __METHOD__
);
1195 * Add row to the redirect table if this is a redirect, remove otherwise.
1197 * @param $dbw Database
1198 * @param $redirectTitle a title object pointing to the redirect target,
1199 * or NULL if this is not a redirect
1200 * @param $lastRevIsRedirect If given, will optimize adding and
1201 * removing rows in redirect table.
1202 * @return bool true on success, false on failure
1205 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1206 // Always update redirects (target link might have changed)
1207 // Update/Insert if we don't know if the last revision was a redirect or not
1208 // Delete if changing from redirect to non-redirect
1209 $isRedirect = !is_null($redirectTitle);
1210 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1211 wfProfileIn( __METHOD__
);
1213 // This title is a redirect, Add/Update row in the redirect table
1214 $set = array( /* SET */
1215 'rd_namespace' => $redirectTitle->getNamespace(),
1216 'rd_title' => $redirectTitle->getDBkey(),
1217 'rd_from' => $this->getId(),
1219 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1221 // This is not a redirect, remove row from redirect table
1222 $where = array( 'rd_from' => $this->getId() );
1223 $dbw->delete( 'redirect', $where, __METHOD__
);
1225 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1226 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1228 wfProfileOut( __METHOD__
);
1229 return ( $dbw->affectedRows() != 0 );
1235 * If the given revision is newer than the currently set page_latest,
1236 * update the page record. Otherwise, do nothing.
1238 * @param $dbw Database object
1239 * @param $revision Revision object
1241 public function updateIfNewerOn( &$dbw, $revision ) {
1242 wfProfileIn( __METHOD__
);
1243 $row = $dbw->selectRow(
1244 array( 'revision', 'page' ),
1245 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1247 'page_id' => $this->getId(),
1248 'page_latest=rev_id' ),
1251 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1252 wfProfileOut( __METHOD__
);
1255 $prev = $row->rev_id
;
1256 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1258 # No or missing previous revision; mark the page as new
1260 $lastRevIsRedirect = null;
1262 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1263 wfProfileOut( __METHOD__
);
1268 * @return string Complete article text, or null if error
1270 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1271 wfProfileIn( __METHOD__
);
1272 if( $section === '' ) {
1273 // Whole-page edit; let the whole text through
1275 if( is_null($edittime) ) {
1276 $rev = Revision
::newFromTitle( $this->mTitle
);
1278 $dbw = wfGetDB( DB_MASTER
);
1279 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1282 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1283 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1286 $oldtext = $rev->getText();
1288 if( $section == 'new' ) {
1289 # Inserting a new section
1290 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1291 $text = strlen( trim( $oldtext ) ) > 0
1292 ?
"{$oldtext}\n\n{$subject}{$text}"
1293 : "{$subject}{$text}";
1295 # Replacing an existing section; roll out the big guns
1297 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1300 wfProfileOut( __METHOD__
);
1305 * @deprecated use Article::doEdit()
1307 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1308 wfDeprecated( __METHOD__
);
1309 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1310 ( $isminor ? EDIT_MINOR
: 0 ) |
1311 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1312 ( $bot ? EDIT_FORCE_BOT
: 0 );
1314 # If this is a comment, add the summary as headline
1315 if( $comment && $summary != "" ) {
1316 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1319 $this->doEdit( $text, $summary, $flags );
1321 $dbw = wfGetDB( DB_MASTER
);
1323 if(!$this->mTitle
->userIsWatching()) {
1329 if( $this->mTitle
->userIsWatching() ) {
1335 $this->doRedirect( $this->isRedirect( $text ) );
1339 * @deprecated use Article::doEdit()
1341 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1342 wfDeprecated( __METHOD__
);
1343 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1344 ( $minor ? EDIT_MINOR
: 0 ) |
1345 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1347 $status = $this->doEdit( $text, $summary, $flags );
1348 if( !$status->isOK() ) {
1352 $dbw = wfGetDB( DB_MASTER
);
1354 if(!$this->mTitle
->userIsWatching()) {
1360 if( $this->mTitle
->userIsWatching() ) {
1367 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1368 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1370 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1377 * Change an existing article or create a new article. Updates RC and all necessary caches,
1378 * optionally via the deferred update array.
1380 * $wgUser must be set before calling this function.
1382 * @param $text String: new text
1383 * @param $summary String: edit summary
1384 * @param $flags Integer bitfield:
1386 * Article is known or assumed to be non-existent, create a new one
1388 * Article is known or assumed to be pre-existing, update it
1390 * Mark this edit minor, if the user is allowed to do so
1392 * Do not log the change in recentchanges
1394 * Mark the edit a "bot" edit regardless of user rights
1395 * EDIT_DEFER_UPDATES
1396 * Defer some of the updates until the end of index.php
1398 * Fill in blank summaries with generated text where possible
1400 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1401 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1402 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1403 * edit-already-exists error will be returned. These two conditions are also possible with
1404 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1406 * @param $baseRevId the revision ID this edit was based off, if any
1407 * @param $user Optional user object, $wgUser will be used if not passed
1409 * @return Status object. Possible errors:
1410 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1411 * edit-gone-missing: In update mode, but the article didn't exist
1412 * edit-conflict: In update mode, the article changed unexpectedly
1413 * edit-no-change: Warning that the text was the same as before
1414 * edit-already-exists: In creation mode, but the article already exists
1416 * Extensions may define additional errors.
1418 * $return->value will contain an associative array with members as follows:
1419 * new: Boolean indicating if the function attempted to create a new article
1420 * revision: The revision object for the inserted revision, or null
1422 * Compatibility note: this function previously returned a boolean value indicating success/failure
1424 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1425 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1427 # Low-level sanity check
1428 if( $this->mTitle
->getText() == '' ) {
1429 throw new MWException( 'Something is trying to edit an article with an empty title' );
1432 wfProfileIn( __METHOD__
);
1434 $user = is_null($user) ?
$wgUser : $user;
1435 $status = Status
::newGood( array() );
1437 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1438 $this->loadPageData();
1440 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1441 $aid = $this->mTitle
->getArticleID();
1443 $flags |
= EDIT_UPDATE
;
1449 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1450 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1452 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1453 wfProfileOut( __METHOD__
);
1454 if( $status->isOK() ) {
1455 $status->fatal( 'edit-hook-aborted');
1460 # Silently ignore EDIT_MINOR if not allowed
1461 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1462 $bot = $flags & EDIT_FORCE_BOT
;
1464 $oldtext = $this->getContent();
1465 $oldsize = strlen( $oldtext );
1467 # Provide autosummaries if one is not provided and autosummaries are enabled.
1468 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1469 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1472 $editInfo = $this->prepareTextForEdit( $text );
1473 $text = $editInfo->pst
;
1474 $newsize = strlen( $text );
1476 $dbw = wfGetDB( DB_MASTER
);
1477 $now = wfTimestampNow();
1479 if( $flags & EDIT_UPDATE
) {
1480 # Update article, but only if changed.
1481 $status->value
['new'] = false;
1482 # Make sure the revision is either completely inserted or not inserted at all
1483 if( !$wgDBtransactions ) {
1484 $userAbort = ignore_user_abort( true );
1489 $changed = ( strcmp( $text, $oldtext ) != 0 );
1492 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1493 - (int)$this->isCountable( $oldtext );
1494 $this->mTotalAdjustment
= 0;
1496 if( !$this->mLatest
) {
1497 # Article gone missing
1498 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1499 $status->fatal( 'edit-gone-missing' );
1500 wfProfileOut( __METHOD__
);
1504 $revision = new Revision( array(
1505 'page' => $this->getId(),
1506 'comment' => $summary,
1507 'minor_edit' => $isminor,
1509 'parent_id' => $this->mLatest
,
1510 'user' => $user->getId(),
1511 'user_text' => $user->getName(),
1515 $revisionId = $revision->insertOn( $dbw );
1519 # Note that we use $this->mLatest instead of fetching a value from the master DB
1520 # during the course of this function. This makes sure that EditPage can detect
1521 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1522 # before this function is called. A previous function used a separate query, this
1523 # creates a window where concurrent edits can cause an ignored edit conflict.
1524 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1527 /* Belated edit conflict! Run away!! */
1528 $status->fatal( 'edit-conflict' );
1529 # Delete the invalid revision if the DB is not transactional
1530 if( !$wgDBtransactions ) {
1531 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1536 global $wgUseRCPatrol;
1537 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1538 # Update recentchanges
1539 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1540 # Mark as patrolled if the user can do so
1541 $patrolled = $wgUseRCPatrol && $user->isAllowed('autopatrol');
1542 # Add RC row to the DB
1543 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1544 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1545 $revisionId, $patrolled
1547 # Log auto-patrolled edits
1549 PatrolLog
::record( $rc, true );
1552 $user->incEditCount();
1556 $status->warning( 'edit-no-change' );
1558 // Keep the same revision ID, but do some updates on it
1559 $revisionId = $this->getRevIdFetched();
1560 // Update page_touched, this is usually implicit in the page update
1561 // Other cache updates are done in onArticleEdit()
1562 $this->mTitle
->invalidateCache();
1565 if( !$wgDBtransactions ) {
1566 ignore_user_abort( $userAbort );
1568 // Now that ignore_user_abort is restored, we can respond to fatal errors
1569 if( !$status->isOK() ) {
1570 wfProfileOut( __METHOD__
);
1574 # Invalidate cache of this article and all pages using this article
1575 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1576 Article
::onArticleEdit( $this->mTitle
, 'skiptransclusions' );
1577 # Update links tables, site stats, etc.
1578 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1580 # Create new article
1581 $status->value
['new'] = true;
1583 # Set statistics members
1584 # We work out if it's countable after PST to avoid counter drift
1585 # when articles are created with {{subst:}}
1586 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1587 $this->mTotalAdjustment
= 1;
1591 # Add the page record; stake our claim on this title!
1592 # This will return false if the article already exists
1593 $newid = $this->insertOn( $dbw );
1595 if( $newid === false ) {
1597 $status->fatal( 'edit-already-exists' );
1598 wfProfileOut( __METHOD__
);
1602 # Save the revision text...
1603 $revision = new Revision( array(
1605 'comment' => $summary,
1606 'minor_edit' => $isminor,
1608 'user' => $user->getId(),
1609 'user_text' => $user->getName(),
1611 $revisionId = $revision->insertOn( $dbw );
1613 $this->mTitle
->resetArticleID( $newid );
1615 # Update the page record with revision data
1616 $this->updateRevisionOn( $dbw, $revision, 0 );
1618 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1619 # Update recentchanges
1620 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1621 global $wgUseRCPatrol, $wgUseNPPatrol;
1622 # Mark as patrolled if the user can do so
1623 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $user->isAllowed('autopatrol');
1624 # Add RC row to the DB
1625 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1626 '', strlen($text), $revisionId, $patrolled );
1627 # Log auto-patrolled edits
1629 PatrolLog
::record( $rc, true );
1632 $user->incEditCount();
1635 # Update links, etc.
1636 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1639 Article
::onArticleCreate( $this->mTitle
);
1641 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1642 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1645 # Do updates right now unless deferral was requested
1646 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1650 // Return the new revision (or null) to the caller
1651 $status->value
['revision'] = $revision;
1653 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1654 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status ) );
1656 wfProfileOut( __METHOD__
);
1661 * @deprecated wrapper for doRedirect
1663 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1664 wfDeprecated( __METHOD__
);
1665 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1669 * Output a redirect back to the article.
1670 * This is typically used after an edit.
1672 * @param $noRedir Boolean: add redirect=no
1673 * @param $sectionAnchor String: section to redirect to, including "#"
1674 * @param $extraQuery String: extra query params
1676 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1679 $query = 'redirect=no';
1681 $query .= "&$query";
1683 $query = $extraQuery;
1685 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1689 * Mark this particular edit/page as patrolled
1691 public function markpatrolled() {
1692 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1693 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1695 # If we haven't been given an rc_id value, we can't do anything
1696 $rcid = (int) $wgRequest->getVal('rcid');
1697 $rc = RecentChange
::newFromId($rcid);
1698 if( is_null($rc) ) {
1699 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1703 #It would be nice to see where the user had actually come from, but for now just guess
1704 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1705 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1707 $dbw = wfGetDB( DB_MASTER
);
1708 $errors = $rc->doMarkPatrolled();
1710 if( in_array(array('rcpatroldisabled'), $errors) ) {
1711 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1715 if( in_array(array('hookaborted'), $errors) ) {
1716 // The hook itself has handled any output
1720 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1721 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1722 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1723 $wgOut->returnToMain( false, $return );
1727 if( !empty($errors) ) {
1728 $wgOut->showPermissionsErrorPage( $errors );
1733 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1734 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1735 $wgOut->returnToMain( false, $return );
1739 * User-interface handler for the "watch" action
1742 public function watch() {
1743 global $wgUser, $wgOut;
1744 if( $wgUser->isAnon() ) {
1745 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1748 if( wfReadOnly() ) {
1749 $wgOut->readOnlyPage();
1752 if( $this->doWatch() ) {
1753 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1754 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1755 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1757 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1761 * Add this page to $wgUser's watchlist
1762 * @return bool true on successful watch operation
1764 public function doWatch() {
1766 if( $wgUser->isAnon() ) {
1769 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1770 $wgUser->addWatch( $this->mTitle
);
1771 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1777 * User interface handler for the "unwatch" action.
1779 public function unwatch() {
1780 global $wgUser, $wgOut;
1781 if( $wgUser->isAnon() ) {
1782 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1785 if( wfReadOnly() ) {
1786 $wgOut->readOnlyPage();
1789 if( $this->doUnwatch() ) {
1790 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1791 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1792 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1794 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1798 * Stop watching a page
1799 * @return bool true on successful unwatch
1801 public function doUnwatch() {
1803 if( $wgUser->isAnon() ) {
1806 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1807 $wgUser->removeWatch( $this->mTitle
);
1808 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1814 * action=protect handler
1816 public function protect() {
1817 $form = new ProtectionForm( $this );
1822 * action=unprotect handler (alias)
1824 public function unprotect() {
1829 * Update the article's restriction field, and leave a log entry.
1831 * @param $limit Array: set of restriction keys
1832 * @param $reason String
1833 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1834 * @param $expiry Array: per restriction type expiration
1835 * @return bool true on success
1837 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1838 global $wgUser, $wgRestrictionTypes, $wgContLang;
1840 $id = $this->mTitle
->getArticleID();
1841 if( $id <= 0 ||
wfReadOnly() ||
!$this->mTitle
->userCan('protect') ) {
1849 // Take this opportunity to purge out expired restrictions
1850 Title
::purgeExpiredRestrictions();
1852 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1853 # we expect a single selection, but the schema allows otherwise.
1855 $updated = Article
::flattenRestrictions( $limit );
1857 foreach( $wgRestrictionTypes as $action ) {
1858 if( isset( $expiry[$action] ) ) {
1859 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1860 $changed = ($changed ||
($this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action]) );
1864 $current = Article
::flattenRestrictions( $current );
1866 $changed = ($changed ||
( $current != $updated ) );
1867 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1868 $protect = ( $updated != '' );
1870 # If nothing's changed, do nothing
1872 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1874 $dbw = wfGetDB( DB_MASTER
);
1876 # Prepare a null revision to be added to the history
1877 $modified = $current != '' && $protect;
1879 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1881 $comment_type = 'unprotectedarticle';
1883 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1885 # Only restrictions with the 'protect' right can cascade...
1886 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1887 foreach( $limit as $action => $restriction ) {
1888 # FIXME: can $restriction be an array or what? (same as fixme above)
1889 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1894 $cascade_description = '';
1896 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1900 $comment .= ": $reason";
1902 $editComment = $comment;
1903 $encodedExpiry = array();
1904 $protect_description = '';
1905 foreach( $limit as $action => $restrictions ) {
1906 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
1907 if( $restrictions != '' ) {
1908 $protect_description .= "[$action=$restrictions] (";
1909 if( $encodedExpiry[$action] != 'infinity' ) {
1910 $protect_description .= wfMsgForContent( 'protect-expiring',
1911 $wgContLang->timeanddate( $expiry[$action], false, false ) );
1913 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1915 $protect_description .= ') ';
1918 $protect_description = trim($protect_description);
1920 if( $protect_description && $protect )
1921 $editComment .= " ($protect_description)";
1923 $editComment .= "$cascade_description";
1924 # Update restrictions table
1925 foreach( $limit as $action => $restrictions ) {
1926 if($restrictions != '' ) {
1927 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1928 array( 'pr_page' => $id,
1929 'pr_type' => $action,
1930 'pr_level' => $restrictions,
1931 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
1932 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
1934 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1935 'pr_type' => $action ), __METHOD__
);
1939 # Insert a null revision
1940 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1941 $nullRevId = $nullRevision->insertOn( $dbw );
1943 $latest = $this->getLatest();
1944 # Update page record
1945 $dbw->update( 'page',
1947 'page_touched' => $dbw->timestamp(),
1948 'page_restrictions' => '',
1949 'page_latest' => $nullRevId
1950 ), array( /* WHERE */
1952 ), 'Article::protect'
1955 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
1956 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1958 # Update the protection log
1959 $log = new LogPage( 'protect' );
1961 $params = array($protect_description,$cascade ?
'cascade' : '');
1962 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
1964 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1968 } # End "changed" check
1974 * Take an array of page restrictions and flatten it to a string
1975 * suitable for insertion into the page_restrictions field.
1976 * @param $limit Array
1979 protected static function flattenRestrictions( $limit ) {
1980 if( !is_array( $limit ) ) {
1981 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1985 foreach( $limit as $action => $restrictions ) {
1986 if( $restrictions != '' ) {
1987 $bits[] = "$action=$restrictions";
1990 return implode( ':', $bits );
1994 * Auto-generates a deletion reason
1995 * @param &$hasHistory Boolean: whether the page has a history
1997 public function generateReason( &$hasHistory ) {
1999 $dbw = wfGetDB( DB_MASTER
);
2000 // Get the last revision
2001 $rev = Revision
::newFromTitle( $this->mTitle
);
2002 if( is_null( $rev ) )
2005 // Get the article's contents
2006 $contents = $rev->getText();
2008 // If the page is blank, use the text from the previous revision,
2009 // which can only be blank if there's a move/import/protect dummy revision involved
2010 if( $contents == '' ) {
2011 $prev = $rev->getPrevious();
2013 $contents = $prev->getText();
2018 // Find out if there was only one contributor
2019 // Only scan the last 20 revisions
2021 $res = $dbw->select( 'revision', 'rev_user_text',
2022 array( 'rev_page' => $this->getID() ), __METHOD__
,
2023 array( 'LIMIT' => $limit )
2025 if( $res === false )
2026 // This page has no revisions, which is very weird
2028 if( $res->numRows() > 1 )
2031 $hasHistory = false;
2032 $row = $dbw->fetchObject( $res );
2033 $onlyAuthor = $row->rev_user_text
;
2034 // Try to find a second contributor
2035 foreach( $res as $row ) {
2036 if( $row->rev_user_text
!= $onlyAuthor ) {
2037 $onlyAuthor = false;
2041 $dbw->freeResult( $res );
2043 // Generate the summary with a '$1' placeholder
2045 // The current revision is blank and the one before is also
2046 // blank. It's just not our lucky day
2047 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2050 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2052 $reason = wfMsgForContent( 'excontent', '$1' );
2055 if( $reason == '-' ) {
2056 // Allow these UI messages to be blanked out cleanly
2060 // Replace newlines with spaces to prevent uglyness
2061 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2062 // Calculate the maximum amount of chars to get
2063 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2064 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2065 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2066 // Remove possible unfinished links
2067 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2068 // Now replace the '$1' placeholder
2069 $reason = str_replace( '$1', $contents, $reason );
2075 * UI entry point for page deletion
2077 public function delete() {
2078 global $wgUser, $wgOut, $wgRequest;
2080 $confirm = $wgRequest->wasPosted() &&
2081 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2083 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2084 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2086 $reason = $this->DeleteReasonList
;
2088 if( $reason != 'other' && $this->DeleteReason
!= '') {
2089 // Entry from drop down menu + additional comment
2090 $reason .= ': ' . $this->DeleteReason
;
2091 } elseif( $reason == 'other' ) {
2092 $reason = $this->DeleteReason
;
2094 # Flag to hide all contents of the archived revisions
2095 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2097 # This code desperately needs to be totally rewritten
2099 # Read-only check...
2100 if( wfReadOnly() ) {
2101 $wgOut->readOnlyPage();
2106 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2108 if(count($permission_errors)>0) {
2109 $wgOut->showPermissionsErrorPage( $permission_errors );
2113 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2115 # Better double-check that it hasn't been deleted yet!
2116 $dbw = wfGetDB( DB_MASTER
);
2117 $conds = $this->mTitle
->pageCond();
2118 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2119 if( $latest === false ) {
2120 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2124 # Hack for big sites
2125 $bigHistory = $this->isBigDeletion();
2126 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2127 global $wgLang, $wgDeleteRevisionsLimit;
2128 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2129 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2134 $this->doDelete( $reason, $suppress );
2135 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2137 } elseif( $this->mTitle
->userIsWatching() ) {
2143 // Generate deletion reason
2144 $hasHistory = false;
2145 if( !$reason ) $reason = $this->generateReason($hasHistory);
2147 // If the page has a history, insert a warning
2148 if( $hasHistory && !$confirm ) {
2149 $skin=$wgUser->getSkin();
2150 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2152 global $wgLang, $wgDeleteRevisionsLimit;
2153 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2154 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2158 return $this->confirmDelete( $reason );
2162 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2164 public function isBigDeletion() {
2165 global $wgDeleteRevisionsLimit;
2166 if( $wgDeleteRevisionsLimit ) {
2167 $revCount = $this->estimateRevisionCount();
2168 return $revCount > $wgDeleteRevisionsLimit;
2174 * @return int approximate revision count
2176 public function estimateRevisionCount() {
2177 $dbr = wfGetDB( DB_SLAVE
);
2178 // For an exact count...
2179 //return $dbr->selectField( 'revision', 'COUNT(*)',
2180 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2181 return $dbr->estimateRowCount( 'revision', '*',
2182 array( 'rev_page' => $this->getId() ), __METHOD__
);
2186 * Get the last N authors
2187 * @param $num Integer: number of revisions to get
2188 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2189 * @return array Array of authors, duplicates not removed
2191 public function getLastNAuthors( $num, $revLatest = 0 ) {
2192 wfProfileIn( __METHOD__
);
2193 // First try the slave
2194 // If that doesn't have the latest revision, try the master
2196 $db = wfGetDB( DB_SLAVE
);
2198 $res = $db->select( array( 'page', 'revision' ),
2199 array( 'rev_id', 'rev_user_text' ),
2201 'page_namespace' => $this->mTitle
->getNamespace(),
2202 'page_title' => $this->mTitle
->getDBkey(),
2203 'rev_page = page_id'
2204 ), __METHOD__
, $this->getSelectOptions( array(
2205 'ORDER BY' => 'rev_timestamp DESC',
2210 wfProfileOut( __METHOD__
);
2213 $row = $db->fetchObject( $res );
2214 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2215 $db = wfGetDB( DB_MASTER
);
2220 } while ( $continue );
2222 $authors = array( $row->rev_user_text
);
2223 while ( $row = $db->fetchObject( $res ) ) {
2224 $authors[] = $row->rev_user_text
;
2226 wfProfileOut( __METHOD__
);
2231 * Output deletion confirmation dialog
2232 * @param $reason String: prefilled reason
2234 public function confirmDelete( $reason ) {
2235 global $wgOut, $wgUser;
2237 wfDebug( "Article::confirmDelete\n" );
2239 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2240 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2241 $wgOut->addWikiMsg( 'confirmdeletetext' );
2243 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2244 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2246 <td class='mw-input'>" .
2247 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2248 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2254 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2256 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2257 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2258 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2259 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2260 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2261 "<tr id=\"wpDeleteReasonListRow\">
2262 <td class='mw-label'>" .
2263 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2265 <td class='mw-input'>" .
2266 Xml
::listDropDown( 'wpDeleteReasonList',
2267 wfMsgForContent( 'deletereason-dropdown' ),
2268 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2271 <tr id=\"wpDeleteReasonRow\">
2272 <td class='mw-label'>" .
2273 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2275 <td class='mw-input'>" .
2276 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2277 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2282 <td class='mw-input'>" .
2283 Xml
::checkLabel( wfMsg( 'watchthis' ),
2284 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2290 <td class='mw-submit'>" .
2291 Xml
::submitButton( wfMsg( 'deletepage' ),
2292 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2295 Xml
::closeElement( 'table' ) .
2296 Xml
::closeElement( 'fieldset' ) .
2297 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2298 Xml
::closeElement( 'form' );
2300 if( $wgUser->isAllowed( 'editinterface' ) ) {
2301 $skin = $wgUser->getSkin();
2302 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2303 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2306 $wgOut->addHTML( $form );
2307 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2311 * Perform a deletion and output success or failure messages
2313 public function doDelete( $reason, $suppress = false ) {
2314 global $wgOut, $wgUser;
2315 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2318 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2319 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2320 $deleted = $this->mTitle
->getPrefixedText();
2322 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2323 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2325 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2327 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2328 $wgOut->returnToMain( false );
2329 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2332 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2334 $wgOut->showFatalError( $error );
2340 * Back-end article deletion
2341 * Deletes the article with database consistency, writes logs, purges caches
2344 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2345 global $wgUseSquid, $wgDeferredUpdateList;
2346 global $wgUseTrackbacks;
2348 wfDebug( __METHOD__
."\n" );
2350 $dbw = wfGetDB( DB_MASTER
);
2351 $ns = $this->mTitle
->getNamespace();
2352 $t = $this->mTitle
->getDBkey();
2353 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2355 if( $t == '' ||
$id == 0 ) {
2359 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2360 array_push( $wgDeferredUpdateList, $u );
2362 // Bitfields to further suppress the content
2365 // This should be 15...
2366 $bitfield |
= Revision
::DELETED_TEXT
;
2367 $bitfield |
= Revision
::DELETED_COMMENT
;
2368 $bitfield |
= Revision
::DELETED_USER
;
2369 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2371 $bitfield = 'rev_deleted';
2375 // For now, shunt the revision data into the archive table.
2376 // Text is *not* removed from the text table; bulk storage
2377 // is left intact to avoid breaking block-compression or
2378 // immutable storage schemes.
2380 // For backwards compatibility, note that some older archive
2381 // table entries will have ar_text and ar_flags fields still.
2383 // In the future, we may keep revisions and mark them with
2384 // the rev_deleted field, which is reserved for this purpose.
2385 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2387 'ar_namespace' => 'page_namespace',
2388 'ar_title' => 'page_title',
2389 'ar_comment' => 'rev_comment',
2390 'ar_user' => 'rev_user',
2391 'ar_user_text' => 'rev_user_text',
2392 'ar_timestamp' => 'rev_timestamp',
2393 'ar_minor_edit' => 'rev_minor_edit',
2394 'ar_rev_id' => 'rev_id',
2395 'ar_text_id' => 'rev_text_id',
2396 'ar_text' => '\'\'', // Be explicit to appease
2397 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2398 'ar_len' => 'rev_len',
2399 'ar_page_id' => 'page_id',
2400 'ar_deleted' => $bitfield
2403 'page_id = rev_page'
2407 # Delete restrictions for it
2408 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2410 # Now that it's safely backed up, delete it
2411 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2412 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2418 # If using cascading deletes, we can skip some explicit deletes
2419 if( !$dbw->cascadingDeletes() ) {
2420 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2422 if($wgUseTrackbacks)
2423 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2425 # Delete outgoing links
2426 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2427 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2428 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2429 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2430 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2431 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2432 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2435 # If using cleanup triggers, we can skip some manual deletes
2436 if( !$dbw->cleanupTriggers() ) {
2437 # Clean up recentchanges entries...
2438 $dbw->delete( 'recentchanges',
2439 array( 'rc_type != '.RC_LOG
,
2440 'rc_namespace' => $this->mTitle
->getNamespace(),
2441 'rc_title' => $this->mTitle
->getDBKey() ),
2443 $dbw->delete( 'recentchanges',
2444 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2449 Article
::onArticleDelete( $this->mTitle
);
2451 # Fix category table counts
2453 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2454 foreach( $res as $row ) {
2455 $cats []= $row->cl_to
;
2457 $this->updateCategoryCounts( array(), $cats );
2459 # Clear the cached article id so the interface doesn't act like we exist
2460 $this->mTitle
->resetArticleID( 0 );
2461 $this->mTitle
->mArticleID
= 0;
2463 # Log the deletion, if the page was suppressed, log it at Oversight instead
2464 $logtype = $suppress ?
'suppress' : 'delete';
2465 $log = new LogPage( $logtype );
2467 # Make sure logging got through
2468 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2476 * Roll back the most recent consecutive set of edits to a page
2477 * from the same user; fails if there are no eligible edits to
2478 * roll back to, e.g. user is the sole contributor. This function
2479 * performs permissions checks on $wgUser, then calls commitRollback()
2480 * to do the dirty work
2482 * @param $fromP String: Name of the user whose edits to rollback.
2483 * @param $summary String: Custom summary. Set to default summary if empty.
2484 * @param $token String: Rollback token.
2485 * @param $bot Boolean: If true, mark all reverted edits as bot.
2487 * @param $resultDetails Array: contains result-specific array of additional values
2488 * 'alreadyrolled' : 'current' (rev)
2489 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2491 * @return array of errors, each error formatted as
2492 * array(messagekey, param1, param2, ...).
2493 * On success, the array is empty. This array can also be passed to
2494 * OutputPage::showPermissionsErrorPage().
2496 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2498 $resultDetails = null;
2501 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2502 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2503 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2505 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2506 $errors[] = array( 'sessionfailure' );
2508 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2509 $errors[] = array( 'actionthrottledtext' );
2511 # If there were errors, bail out now
2512 if( !empty( $errors ) )
2515 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2519 * Backend implementation of doRollback(), please refer there for parameter
2520 * and return value documentation
2522 * NOTE: This function does NOT check ANY permissions, it just commits the
2523 * rollback to the DB Therefore, you should only call this function direct-
2524 * ly if you want to use custom permissions checks. If you don't, use
2525 * doRollback() instead.
2527 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2528 global $wgUseRCPatrol, $wgUser, $wgLang;
2529 $dbw = wfGetDB( DB_MASTER
);
2531 if( wfReadOnly() ) {
2532 return array( array( 'readonlytext' ) );
2535 # Get the last editor
2536 $current = Revision
::newFromTitle( $this->mTitle
);
2537 if( is_null( $current ) ) {
2538 # Something wrong... no page?
2539 return array(array('notanarticle'));
2542 $from = str_replace( '_', ' ', $fromP );
2543 if( $from != $current->getUserText() ) {
2544 $resultDetails = array( 'current' => $current );
2545 return array(array('alreadyrolled',
2546 htmlspecialchars($this->mTitle
->getPrefixedText()),
2547 htmlspecialchars($fromP),
2548 htmlspecialchars($current->getUserText())
2552 # Get the last edit not by this guy
2553 $user = intval( $current->getUser() );
2554 $user_text = $dbw->addQuotes( $current->getUserText() );
2555 $s = $dbw->selectRow( 'revision',
2556 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2557 array( 'rev_page' => $current->getPage(),
2558 "rev_user != {$user} OR rev_user_text != {$user_text}"
2560 array( 'USE INDEX' => 'page_timestamp',
2561 'ORDER BY' => 'rev_timestamp DESC' )
2563 if( $s === false ) {
2564 # No one else ever edited this page
2565 return array(array('cantrollback'));
2566 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2567 # Only admins can see this text
2568 return array(array('notvisiblerev'));
2572 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2573 # Mark all reverted edits as bot
2576 if( $wgUseRCPatrol ) {
2577 # Mark all reverted edits as patrolled
2578 $set['rc_patrolled'] = 1;
2582 $dbw->update( 'recentchanges', $set,
2584 'rc_cur_id' => $current->getPage(),
2585 'rc_user_text' => $current->getUserText(),
2586 "rc_timestamp > '{$s->rev_timestamp}'",
2591 # Generate the edit summary if necessary
2592 $target = Revision
::newFromId( $s->rev_id
);
2593 if( empty( $summary ) ){
2594 $summary = wfMsgForContent( 'revertpage' );
2597 # Allow the custom summary to use the same args as the default message
2599 $target->getUserText(), $from, $s->rev_id
,
2600 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2601 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2603 $summary = wfMsgReplaceArgs( $summary, $args );
2606 $flags = EDIT_UPDATE
;
2608 if( $wgUser->isAllowed('minoredit') )
2609 $flags |
= EDIT_MINOR
;
2611 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2612 $flags |
= EDIT_FORCE_BOT
;
2613 # Actually store the edit
2614 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2615 if( !empty( $status->value
['revision'] ) ) {
2616 $revId = $status->value
['revision']->getId();
2621 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2623 $resultDetails = array(
2624 'summary' => $summary,
2625 'current' => $current,
2626 'target' => $target,
2633 * User interface for rollback operations
2635 public function rollback() {
2636 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2639 $result = $this->doRollback(
2640 $wgRequest->getVal( 'from' ),
2641 $wgRequest->getText( 'summary' ),
2642 $wgRequest->getVal( 'token' ),
2643 $wgRequest->getBool( 'bot' ),
2647 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2648 $wgOut->rateLimited();
2651 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2652 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2653 $errArray = $result[0];
2654 $errMsg = array_shift( $errArray );
2655 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2656 if( isset( $details['current'] ) ){
2657 $current = $details['current'];
2658 if( $current->getComment() != '' ) {
2659 $wgOut->addWikiMsgArray( 'editcomment', array(
2660 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2665 # Display permissions errors before read-only message -- there's no
2666 # point in misleading the user into thinking the inability to rollback
2667 # is only temporary.
2668 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2669 # array_diff is completely broken for arrays of arrays, sigh. Re-
2670 # move any 'readonlytext' error manually.
2672 foreach( $result as $error ) {
2673 if( $error != array( 'readonlytext' ) ) {
2677 $wgOut->showPermissionsErrorPage( $out );
2680 if( $result == array( array( 'readonlytext' ) ) ) {
2681 $wgOut->readOnlyPage();
2685 $current = $details['current'];
2686 $target = $details['target'];
2687 $newId = $details['newid'];
2688 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2689 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2690 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2691 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2692 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2693 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2694 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2695 $wgOut->returnToMain( false, $this->mTitle
);
2697 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2698 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2699 $de->showDiff( '', '' );
2705 * Do standard deferred updates after page view
2707 protected function viewUpdates() {
2708 global $wgDeferredUpdateList, $wgUser;
2709 if( 0 != $this->getID() ) {
2710 # Don't update page view counters on views from bot users (bug 14044)
2711 global $wgDisableCounters;
2712 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2713 Article
::incViewCount( $this->getID() );
2714 $u = new SiteStatsUpdate( 1, 0, 0 );
2715 array_push( $wgDeferredUpdateList, $u );
2718 # Update newtalk / watchlist notification status
2719 $wgUser->clearNotification( $this->mTitle
);
2723 * Prepare text which is about to be saved.
2724 * Returns a stdclass with source, pst and output members
2726 public function prepareTextForEdit( $text, $revid=null ) {
2727 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2729 return $this->mPreparedEdit
;
2732 $edit = (object)array();
2733 $edit->revid
= $revid;
2734 $edit->newText
= $text;
2735 $edit->pst
= $this->preSaveTransform( $text );
2736 $options = new ParserOptions
;
2737 $options->setTidy( true );
2738 $options->enableLimitReport();
2739 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2740 $edit->oldText
= $this->getContent();
2741 $this->mPreparedEdit
= $edit;
2746 * Do standard deferred updates after page edit.
2747 * Update links tables, site stats, search index and message cache.
2748 * Purges pages that include this page if the text was changed here.
2749 * Every 100th edit, prune the recent changes table.
2752 * @param $text New text of the article
2753 * @param $summary Edit summary
2754 * @param $minoredit Minor edit
2755 * @param $timestamp_of_pagechange Timestamp associated with the page change
2756 * @param $newid rev_id value of the new revision
2757 * @param $changed Whether or not the content actually changed
2759 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2760 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2762 wfProfileIn( __METHOD__
);
2765 # Be careful not to double-PST: $text is usually already PST-ed once
2766 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2767 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2768 $editInfo = $this->prepareTextForEdit( $text, $newid );
2770 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2771 $editInfo = $this->mPreparedEdit
;
2774 # Save it to the parser cache
2775 if( $wgEnableParserCache ) {
2776 $parserCache = ParserCache
::singleton();
2777 $parserCache->save( $editInfo->output
, $this, $wgUser );
2780 # Update the links tables
2781 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
, false );
2782 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2785 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2787 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2788 if( 0 == mt_rand( 0, 99 ) ) {
2789 // Flush old entries from the `recentchanges` table; we do this on
2790 // random requests so as to avoid an increase in writes for no good reason
2792 $dbw = wfGetDB( DB_MASTER
);
2793 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2794 $recentchanges = $dbw->tableName( 'recentchanges' );
2795 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2796 $dbw->query( $sql );
2800 $id = $this->getID();
2801 $title = $this->mTitle
->getPrefixedDBkey();
2802 $shortTitle = $this->mTitle
->getDBkey();
2805 wfProfileOut( __METHOD__
);
2809 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2810 array_push( $wgDeferredUpdateList, $u );
2811 $u = new SearchUpdate( $id, $title, $text );
2812 array_push( $wgDeferredUpdateList, $u );
2814 # If this is another user's talk page, update newtalk
2815 # Don't do this if $changed = false otherwise some idiot can null-edit a
2816 # load of user talk pages and piss people off, nor if it's a minor edit
2817 # by a properly-flagged bot.
2818 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2819 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2820 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2821 $other = User
::newFromName( $shortTitle, false );
2823 wfDebug( __METHOD__
.": invalid username\n" );
2824 } elseif( User
::isIP( $shortTitle ) ) {
2825 // An anonymous user
2826 $other->setNewtalk( true );
2827 } elseif( $other->isLoggedIn() ) {
2828 $other->setNewtalk( true );
2830 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2835 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2836 $wgMessageCache->replace( $shortTitle, $text );
2839 wfProfileOut( __METHOD__
);
2843 * Perform article updates on a special page creation.
2845 * @param $rev Revision object
2847 * @todo This is a shitty interface function. Kill it and replace the
2848 * other shitty functions like editUpdates and such so it's not needed
2851 public function createUpdates( $rev ) {
2852 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2853 $this->mTotalAdjustment
= 1;
2854 $this->editUpdates( $rev->getText(), $rev->getComment(),
2855 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2859 * Generate the navigation links when browsing through an article revisions
2860 * It shows the information as:
2861 * Revision as of \<date\>; view current revision
2862 * \<- Previous version | Next Version -\>
2864 * @param $oldid String: revision ID of this article revision
2866 public function setOldSubtitle( $oldid=0 ) {
2867 global $wgLang, $wgOut, $wgUser;
2869 if( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2873 $revision = Revision
::newFromId( $oldid );
2875 $current = ( $oldid == $this->mLatest
);
2876 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2877 $sk = $wgUser->getSkin();
2879 ?
wfMsg( 'currentrevisionlink' )
2880 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2883 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2884 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2886 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2887 : wfMsg( 'previousrevision' );
2889 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2891 $nextlink = $current
2892 ?
wfMsg( 'nextrevision' )
2893 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2894 $nextdiff = $current
2896 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2899 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2900 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2901 if( $revision->isCurrent() ) {
2902 // We don't handle top deleted edits too well
2903 $cdel = wfMsgHtml('rev-delundel');
2904 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2905 // If revision was hidden from sysops
2906 $cdel = wfMsgHtml('rev-delundel');
2908 $cdel = $sk->makeKnownLinkObj( $revdel,
2909 wfMsgHtml('rev-delundel'),
2910 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2911 '&oldid=' . urlencode( $oldid ) );
2912 // Bolden oversighted content
2913 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2914 $cdel = "<strong>$cdel</strong>";
2916 $cdel = "(<small>$cdel</small>) ";
2918 # Show user links if allowed to see them. Normally they
2919 # are hidden regardless, but since we can already see the text here...
2920 $userlinks = $sk->revUserTools( $revision, false );
2922 $m = wfMsg( 'revision-info-current' );
2923 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2924 ?
'revision-info-current'
2927 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks, $revision->getID() ) . "</div>\n" .
2929 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff,
2930 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2931 $wgOut->setSubtitle( $r );
2935 * This function is called right before saving the wikitext,
2936 * so we can do things like signatures and links-in-context.
2938 * @param $text String
2940 public function preSaveTransform( $text ) {
2941 global $wgParser, $wgUser;
2942 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2945 /* Caching functions */
2948 * checkLastModified returns true if it has taken care of all
2949 * output to the client that is necessary for this request.
2950 * (that is, it has sent a cached version of the page)
2952 protected function tryFileCache() {
2953 static $called = false;
2955 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2959 if( $this->isFileCacheable() ) {
2960 $cache = new HTMLFileCache( $this->mTitle
);
2961 if( $cache->isFileCacheGood( $this->mTouched
) ) {
2962 wfDebug( "Article::tryFileCache(): about to load file\n" );
2963 $cache->loadFromFileCache();
2966 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2967 ob_start( array(&$cache, 'saveToFileCache' ) );
2970 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2976 * Check if the page can be cached
2979 public function isFileCacheable() {
2980 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2981 // Get all query values
2982 $queryVals = $wgRequest->getValues();
2983 foreach( $queryVals as $query => $val ) {
2984 // Normal page view in query form can have action=view
2985 if( $query !== 'title' && $query !== 'curid' && !($query == 'action' && $val == 'view') ) {
2989 // Check for non-standard user language; this covers uselang,
2990 // and extensions for auto-detecting user language.
2991 $ulang = $wgLang->getCode();
2992 $clang = $wgContLang->getCode();
2994 $cacheable = $wgUseFileCache
2995 && !$wgShowIPinHeader
2996 && $this->getID() > 0
2997 && $wgUser->isAnon()
2998 && !$wgUser->getNewtalk()
2999 && !$this->mRedirectedFrom
3000 && $ulang === $clang;
3001 // Extension may have reason to disable file caching on some pages.
3003 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3009 * Loads page_touched and returns a value indicating if it should be used
3012 public function checkTouched() {
3013 if( !$this->mDataLoaded
) {
3014 $this->loadPageData();
3016 return !$this->mIsRedirect
;
3020 * Get the page_touched field
3022 public function getTouched() {
3023 # Ensure that page data has been loaded
3024 if( !$this->mDataLoaded
) {
3025 $this->loadPageData();
3027 return $this->mTouched
;
3031 * Get the page_latest field
3033 public function getLatest() {
3034 if( !$this->mDataLoaded
) {
3035 $this->loadPageData();
3037 return $this->mLatest
;
3041 * Edit an article without doing all that other stuff
3042 * The article must already exist; link tables etc
3043 * are not updated, caches are not flushed.
3045 * @param $text String: text submitted
3046 * @param $comment String: comment submitted
3047 * @param $minor Boolean: whereas it's a minor modification
3049 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3050 wfProfileIn( __METHOD__
);
3052 $dbw = wfGetDB( DB_MASTER
);
3053 $revision = new Revision( array(
3054 'page' => $this->getId(),
3056 'comment' => $comment,
3057 'minor_edit' => $minor ?
1 : 0,
3059 $revision->insertOn( $dbw );
3060 $this->updateRevisionOn( $dbw, $revision );
3062 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3064 wfProfileOut( __METHOD__
);
3068 * Used to increment the view counter
3070 * @param $id Integer: article id
3072 public static function incViewCount( $id ) {
3073 $id = intval( $id );
3074 global $wgHitcounterUpdateFreq, $wgDBtype;
3076 $dbw = wfGetDB( DB_MASTER
);
3077 $pageTable = $dbw->tableName( 'page' );
3078 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3079 $acchitsTable = $dbw->tableName( 'acchits' );
3081 if( $wgHitcounterUpdateFreq <= 1 ) {
3082 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3086 # Not important enough to warrant an error page in case of failure
3087 $oldignore = $dbw->ignoreErrors( true );
3089 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3091 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3092 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3093 # Most of the time (or on SQL errors), skip row count check
3094 $dbw->ignoreErrors( $oldignore );
3098 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3099 $row = $dbw->fetchObject( $res );
3100 $rown = intval( $row->n
);
3101 if( $rown >= $wgHitcounterUpdateFreq ){
3102 wfProfileIn( 'Article::incViewCount-collect' );
3103 $old_user_abort = ignore_user_abort( true );
3105 if($wgDBtype == 'mysql')
3106 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3107 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3108 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3109 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3111 $dbw->query("DELETE FROM $hitcounterTable");
3112 if($wgDBtype == 'mysql') {
3113 $dbw->query('UNLOCK TABLES');
3114 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3115 'WHERE page_id = hc_id');
3118 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3119 "FROM $acchitsTable WHERE page_id = hc_id");
3121 $dbw->query("DROP TABLE $acchitsTable");
3123 ignore_user_abort( $old_user_abort );
3124 wfProfileOut( 'Article::incViewCount-collect' );
3126 $dbw->ignoreErrors( $oldignore );
3130 * The onArticle*() functions are supposed to be a kind of hooks
3131 * which should be called whenever any of the specified actions
3134 * This is a good place to put code to clear caches, for instance.
3136 * This is called on page move and undelete, as well as edit
3138 * @param $title a title object
3141 public static function onArticleCreate( $title ) {
3142 # Update existence markers on article/talk tabs...
3143 if( $title->isTalkPage() ) {
3144 $other = $title->getSubjectPage();
3146 $other = $title->getTalkPage();
3148 $other->invalidateCache();
3149 $other->purgeSquid();
3151 $title->touchLinks();
3152 $title->purgeSquid();
3153 $title->deleteTitleProtection();
3156 public static function onArticleDelete( $title ) {
3157 global $wgUseFileCache, $wgMessageCache;
3158 # Update existence markers on article/talk tabs...
3159 if( $title->isTalkPage() ) {
3160 $other = $title->getSubjectPage();
3162 $other = $title->getTalkPage();
3164 $other->invalidateCache();
3165 $other->purgeSquid();
3167 $title->touchLinks();
3168 $title->purgeSquid();
3171 if( $wgUseFileCache ) {
3172 $cm = new HTMLFileCache( $title );
3173 @unlink
( $cm->fileCacheName() );
3177 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3178 $wgMessageCache->replace( $title->getDBkey(), false );
3181 if( $title->getNamespace() == NS_FILE
) {
3182 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3183 $update->doUpdate();
3186 if( $title->getNamespace() == NS_USER_TALK
) {
3187 $user = User
::newFromName( $title->getText(), false );
3188 $user->setNewtalk( false );
3193 * Purge caches on page update etc
3195 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3196 global $wgDeferredUpdateList, $wgUseFileCache;
3198 // Invalidate caches of articles which include this page
3199 if( $transclusions !== 'skiptransclusions' )
3200 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3202 // Invalidate the caches of all pages which redirect here
3203 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3205 # Purge squid for this page only
3206 $title->purgeSquid();
3208 # Clear file cache for this page only
3209 if( $wgUseFileCache ) {
3210 $cm = new HTMLFileCache( $title );
3211 @unlink
( $cm->fileCacheName() );
3218 * Overriden by ImagePage class, only present here to avoid a fatal error
3219 * Called for ?action=revert
3221 public function revert() {
3223 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3227 * Info about this page
3228 * Called for ?action=info when $wgAllowPageInfo is on.
3230 public function info() {
3231 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3233 if( !$wgAllowPageInfo ) {
3234 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3238 $page = $this->mTitle
->getSubjectPage();
3240 $wgOut->setPagetitle( $page->getPrefixedText() );
3241 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3242 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3244 if( !$this->mTitle
->exists() ) {
3245 $wgOut->addHTML( '<div class="noarticletext">' );
3246 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3247 // This doesn't quite make sense; the user is asking for
3248 // information about the _page_, not the message... -- RC
3249 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3251 $msg = $wgUser->isLoggedIn()
3253 : 'noarticletextanon';
3254 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3256 $wgOut->addHTML( '</div>' );
3258 $dbr = wfGetDB( DB_SLAVE
);
3260 'wl_title' => $page->getDBkey(),
3261 'wl_namespace' => $page->getNamespace() );
3262 $numwatchers = $dbr->selectField(
3267 $this->getSelectOptions() );
3269 $pageInfo = $this->pageCountInfo( $page );
3270 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3272 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3273 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3275 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3277 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3279 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3281 $wgOut->addHTML( '</ul>' );
3286 * Return the total number of edits and number of unique editors
3287 * on a given page. If page does not exist, returns false.
3289 * @param $title Title object
3292 protected function pageCountInfo( $title ) {
3293 $id = $title->getArticleId();
3297 $dbr = wfGetDB( DB_SLAVE
);
3298 $rev_clause = array( 'rev_page' => $id );
3299 $edits = $dbr->selectField(
3304 $this->getSelectOptions()
3306 $authors = $dbr->selectField(
3308 'COUNT(DISTINCT rev_user_text)',
3311 $this->getSelectOptions()
3313 return array( 'edits' => $edits, 'authors' => $authors );
3317 * Return a list of templates used by this article.
3318 * Uses the templatelinks table
3320 * @return Array of Title objects
3322 public function getUsedTemplates() {
3324 $id = $this->mTitle
->getArticleID();
3328 $dbr = wfGetDB( DB_SLAVE
);
3329 $res = $dbr->select( array( 'templatelinks' ),
3330 array( 'tl_namespace', 'tl_title' ),
3331 array( 'tl_from' => $id ),
3333 if( $res !== false ) {
3334 foreach( $res as $row ) {
3335 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3338 $dbr->freeResult( $res );
3343 * Returns a list of hidden categories this page is a member of.
3344 * Uses the page_props and categorylinks tables.
3346 * @return Array of Title objects
3348 public function getHiddenCategories() {
3350 $id = $this->mTitle
->getArticleID();
3354 $dbr = wfGetDB( DB_SLAVE
);
3355 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3357 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3358 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3360 if( $res !== false ) {
3361 foreach( $res as $row ) {
3362 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3365 $dbr->freeResult( $res );
3370 * Return an applicable autosummary if one exists for the given edit.
3371 * @param $oldtext String: the previous text of the page.
3372 * @param $newtext String: The submitted text of the page.
3373 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3374 * @return string An appropriate autosummary, or an empty string.
3376 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3377 # Decide what kind of autosummary is needed.
3379 # Redirect autosummaries
3380 $ot = Title
::newFromRedirect( $oldtext );
3381 $rt = Title
::newFromRedirect( $newtext );
3382 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3383 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3386 # New page autosummaries
3387 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3388 # If they're making a new article, give its text, truncated, in the summary.
3390 $truncatedtext = $wgContLang->truncate(
3391 str_replace("\n", ' ', $newtext),
3392 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3394 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3397 # Blanking autosummaries
3398 if( $oldtext != '' && $newtext == '' ) {
3399 return wfMsgForContent( 'autosumm-blank' );
3400 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3401 # Removing more than 90% of the article
3403 $truncatedtext = $wgContLang->truncate(
3405 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3408 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3411 # If we reach this point, there's no applicable autosummary for our case, so our
3412 # autosummary is empty.
3417 * Add the primary page-view wikitext to the output buffer
3418 * Saves the text into the parser cache if possible.
3419 * Updates templatelinks if it is out of date.
3421 * @param $text String
3422 * @param $cache Boolean
3424 public function outputWikiText( $text, $cache = true ) {
3425 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3427 $popts = $wgOut->parserOptions();
3428 $popts->setTidy(true);
3429 $popts->enableLimitReport();
3430 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3431 $popts, true, true, $this->getRevIdFetched() );
3432 $popts->setTidy(false);
3433 $popts->enableLimitReport( false );
3434 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3435 $parserCache = ParserCache
::singleton();
3436 $parserCache->save( $parserOutput, $this, $wgUser );
3438 // Make sure file cache is not used on uncacheable content.
3439 // Output that has magic words in it can still use the parser cache
3440 // (if enabled), though it will generally expire sooner.
3441 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3442 $wgUseFileCache = false;
3445 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3446 // templatelinks table may have become out of sync,
3447 // especially if using variable-based transclusions.
3448 // For paranoia, check if things have changed and if
3449 // so apply updates to the database. This will ensure
3450 // that cascaded protections apply as soon as the changes
3453 # Get templates from templatelinks
3454 $id = $this->mTitle
->getArticleID();
3456 $tlTemplates = array();
3458 $dbr = wfGetDB( DB_SLAVE
);
3459 $res = $dbr->select( array( 'templatelinks' ),
3460 array( 'tl_namespace', 'tl_title' ),
3461 array( 'tl_from' => $id ),
3466 if( $res !== false ) {
3467 foreach( $res as $row ) {
3468 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3472 # Get templates from parser output.
3473 $poTemplates_allns = $parserOutput->getTemplates();
3475 $poTemplates = array ();
3476 foreach ( $poTemplates_allns as $ns_templates ) {
3477 $poTemplates = array_merge( $poTemplates, $ns_templates );
3481 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3483 if( count( $templates_diff ) > 0 ) {
3484 # Whee, link updates time.
3485 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3490 $wgOut->addParserOutput( $parserOutput );
3494 * Update all the appropriate counts in the category table, given that
3495 * we've added the categories $added and deleted the categories $deleted.
3497 * @param $added array The names of categories that were added
3498 * @param $deleted array The names of categories that were deleted
3501 public function updateCategoryCounts( $added, $deleted ) {
3502 $ns = $this->mTitle
->getNamespace();
3503 $dbw = wfGetDB( DB_MASTER
);
3505 # First make sure the rows exist. If one of the "deleted" ones didn't
3506 # exist, we might legitimately not create it, but it's simpler to just
3507 # create it and then give it a negative value, since the value is bogus
3510 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3511 $insertCats = array_merge( $added, $deleted );
3512 if( !$insertCats ) {
3513 # Okay, nothing to do
3516 $insertRows = array();
3517 foreach( $insertCats as $cat ) {
3518 $insertRows[] = array( 'cat_title' => $cat );
3520 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3522 $addFields = array( 'cat_pages = cat_pages + 1' );
3523 $removeFields = array( 'cat_pages = cat_pages - 1' );
3524 if( $ns == NS_CATEGORY
) {
3525 $addFields[] = 'cat_subcats = cat_subcats + 1';
3526 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3527 } elseif( $ns == NS_FILE
) {
3528 $addFields[] = 'cat_files = cat_files + 1';
3529 $removeFields[] = 'cat_files = cat_files - 1';
3536 array( 'cat_title' => $added ),
3544 array( 'cat_title' => $deleted ),