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
;
372 $this->mTitle
->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
374 # Old-fashioned restrictions.
375 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
377 $this->mCounter
= $data->page_counter
;
378 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
379 $this->mIsRedirect
= $data->page_is_redirect
;
380 $this->mLatest
= $data->page_latest
;
382 if( is_object( $this->mTitle
) ) {
383 $lc->addBadLinkObj( $this->mTitle
);
385 $this->mTitle
->mArticleID
= 0;
388 $this->mDataLoaded
= true;
392 * Get text of an article from database
393 * Does *NOT* follow redirects.
394 * @param $oldid Int: 0 for whatever the latest revision is
397 function fetchContent( $oldid = 0 ) {
398 if( $this->mContentLoaded
) {
399 return $this->mContent
;
402 $dbr = wfGetDB( DB_MASTER
);
404 # Pre-fill content with error message so that if something
405 # fails we'll have something telling us what we intended.
406 $t = $this->mTitle
->getPrefixedText();
407 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
408 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
411 $revision = Revision
::newFromId( $oldid );
412 if( is_null( $revision ) ) {
413 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
416 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
418 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
421 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
422 $this->loadPageData( $data );
424 if( !$this->mDataLoaded
) {
425 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
427 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
430 $this->loadPageData( $data );
432 $revision = Revision
::newFromId( $this->mLatest
);
433 if( is_null( $revision ) ) {
434 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
439 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
440 // We should instead work with the Revision object when we need it...
441 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
443 $this->mUser
= $revision->getUser();
444 $this->mUserText
= $revision->getUserText();
445 $this->mComment
= $revision->getComment();
446 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
448 $this->mRevIdFetched
= $revision->getId();
449 $this->mContentLoaded
= true;
450 $this->mRevision
=& $revision;
452 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
454 return $this->mContent
;
458 * Read/write accessor to select FOR UPDATE
460 * @param $x Mixed: FIXME
462 public function forUpdate( $x = NULL ) {
463 return wfSetVar( $this->mForUpdate
, $x );
467 * Get the database which should be used for reads
470 * @deprecated - just call wfGetDB( DB_MASTER ) instead
473 wfDeprecated( __METHOD__
);
474 return wfGetDB( DB_MASTER
);
478 * Get options for all SELECT statements
480 * @param $options Array: an optional options array which'll be appended to
482 * @return Array: options
484 protected function getSelectOptions( $options = '' ) {
485 if( $this->mForUpdate
) {
486 if( is_array( $options ) ) {
487 $options[] = 'FOR UPDATE';
489 $options = 'FOR UPDATE';
496 * @return int Page ID
498 public function getID() {
499 if( $this->mTitle
) {
500 return $this->mTitle
->getArticleID();
507 * @return bool Whether or not the page exists in the database
509 public function exists() {
510 return $this->getId() > 0;
514 * @return int The view count for the page
516 public function getCount() {
517 if( -1 == $this->mCounter
) {
518 $id = $this->getID();
522 $dbr = wfGetDB( DB_SLAVE
);
523 $this->mCounter
= $dbr->selectField( 'page',
525 array( 'page_id' => $id ),
527 $this->getSelectOptions()
531 return $this->mCounter
;
535 * Determine whether a page would be suitable for being counted as an
536 * article in the site_stats table based on the title & its content
538 * @param $text String: text to analyze
541 public function isCountable( $text ) {
542 global $wgUseCommaCount;
544 $token = $wgUseCommaCount ?
',' : '[[';
545 return $this->mTitle
->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
549 * Tests if the article text represents a redirect
551 * @param $text String: FIXME
554 public function isRedirect( $text = false ) {
555 if( $text === false ) {
556 if( $this->mDataLoaded
) {
557 return $this->mIsRedirect
;
559 // Apparently loadPageData was never called
560 $this->loadContent();
561 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
563 $titleObj = Title
::newFromRedirect( $text );
565 return $titleObj !== NULL;
569 * Returns true if the currently-referenced revision is the current edit
570 * to this page (and it exists).
573 public function isCurrent() {
574 # If no oldid, this is the current version.
575 if( $this->getOldID() == 0 ) {
578 return $this->exists() && isset($this->mRevision
) && $this->mRevision
->isCurrent();
582 * Loads everything except the text
583 * This isn't necessary for all uses, so it's only done if needed.
585 protected function loadLastEdit() {
586 if( -1 != $this->mUser
)
589 # New or non-existent articles have no user information
590 $id = $this->getID();
591 if( 0 == $id ) return;
593 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
594 if( !is_null( $this->mLastRevision
) ) {
595 $this->mUser
= $this->mLastRevision
->getUser();
596 $this->mUserText
= $this->mLastRevision
->getUserText();
597 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
598 $this->mComment
= $this->mLastRevision
->getComment();
599 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
600 $this->mRevIdFetched
= $this->mLastRevision
->getId();
604 public function getTimestamp() {
605 // Check if the field has been filled by ParserCache::get()
606 if( !$this->mTimestamp
) {
607 $this->loadLastEdit();
609 return wfTimestamp(TS_MW
, $this->mTimestamp
);
612 public function getUser() {
613 $this->loadLastEdit();
617 public function getUserText() {
618 $this->loadLastEdit();
619 return $this->mUserText
;
622 public function getComment() {
623 $this->loadLastEdit();
624 return $this->mComment
;
627 public function getMinorEdit() {
628 $this->loadLastEdit();
629 return $this->mMinorEdit
;
632 /* Use this to fetch the rev ID used on page views */
633 public function getRevIdFetched() {
634 $this->loadLastEdit();
635 return $this->mRevIdFetched
;
639 * @param $limit Integer: default 0.
640 * @param $offset Integer: default 0.
642 public function getContributors($limit = 0, $offset = 0) {
643 # XXX: this is expensive; cache this info somewhere.
646 $dbr = wfGetDB( DB_SLAVE
);
647 $revTable = $dbr->tableName( 'revision' );
648 $userTable = $dbr->tableName( 'user' );
649 $user = $this->getUser();
650 $pageId = $this->getId();
652 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
653 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
654 WHERE rev_page = $pageId
655 AND rev_user != $user
656 GROUP BY rev_user, rev_user_text, user_real_name
657 ORDER BY timestamp DESC";
659 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
660 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
662 $sql .= ' '. $this->getSelectOptions();
664 $res = $dbr->query($sql, __METHOD__
);
666 return new UserArrayFromResult( $res );
670 * This is the default action of the script: just view the page of
673 public function view() {
674 global $wgUser, $wgOut, $wgRequest, $wgContLang;
675 global $wgEnableParserCache, $wgStylePath, $wgParser;
676 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
677 global $wgDefaultRobotPolicy;
679 wfProfileIn( __METHOD__
);
681 $parserCache = ParserCache
::singleton();
682 $ns = $this->mTitle
->getNamespace(); # shortcut
684 # Get variables from query string
685 $oldid = $this->getOldID();
688 if( $oldid === 0 && $this->checkTouched() ) {
689 $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 $sk = $wgUser->getSkin();
704 # getOldID may want us to redirect somewhere else
705 if( $this->mRedirectUrl
) {
706 $wgOut->redirect( $this->mRedirectUrl
);
707 wfProfileOut( __METHOD__
);
711 $diff = $wgRequest->getVal( 'diff' );
712 $rcid = $wgRequest->getVal( 'rcid' );
713 $rdfrom = $wgRequest->getVal( 'rdfrom' );
714 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
715 $purge = $wgRequest->getVal( 'action' ) == 'purge';
717 $wgOut->setArticleFlag( true );
719 # Discourage indexing of printable versions, but encourage following
720 if( $wgOut->isPrintable() ) {
721 $policy = 'noindex,follow';
722 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
723 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
724 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
725 # Honour customised robot policies for this namespace
726 $policy = $wgNamespaceRobotPolicies[$ns];
728 $policy = $wgDefaultRobotPolicy;
730 $wgOut->setRobotPolicy( $policy );
732 # If we got diff and oldid in the query, we want to see a
733 # diff page instead of the article.
735 if( !is_null( $diff ) ) {
736 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
738 $diff = $wgRequest->getVal( 'diff' );
739 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
740 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
741 // DifferenceEngine directly fetched the revision:
742 $this->mRevIdFetched
= $de->mNewid
;
743 $de->showDiffPage( $diffOnly );
745 // Needed to get the page's current revision
746 $this->loadPageData();
747 if( $diff == 0 ||
$diff == $this->mLatest
) {
748 # Run view updates for current revision only
749 $this->viewUpdates();
751 wfProfileOut( __METHOD__
);
755 # Should the parser cache be used?
756 $pcache = $this->useParserCache( $oldid );
757 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
758 if( $wgUser->getOption( 'stubthreshold' ) ) {
759 wfIncrStats( 'pcache_miss_stub' );
762 $wasRedirected = false;
763 if( isset( $this->mRedirectedFrom
) ) {
764 // This is an internally redirected page view.
765 // We'll need a backlink to the source page for navigation.
766 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
767 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
768 $s = wfMsg( 'redirectedfrom', $redir );
769 $wgOut->setSubtitle( $s );
771 // Set the fragment if one was specified in the redirect
772 if( strval( $this->mTitle
->getFragment() ) != '' ) {
773 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
774 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
776 $wasRedirected = true;
778 } elseif( !empty( $rdfrom ) ) {
779 // This is an externally redirected view, from some other wiki.
780 // If it was reported from a trusted site, supply a backlink.
781 global $wgRedirectSources;
782 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
783 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
784 $s = wfMsg( 'redirectedfrom', $redir );
785 $wgOut->setSubtitle( $s );
786 $wasRedirected = true;
791 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
792 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
793 // Ensure that UI elements requiring revision ID have
794 // the correct version information.
795 $wgOut->setRevisionId( $this->mLatest
);
798 # Fetch content and check for errors
800 # If the article does not exist and was deleted, show the log
801 if( $this->getID() == 0 ) {
802 $this->showDeletionLog();
804 $text = $this->getContent();
805 if( $text === false ) {
806 # Failed to load, replace text with error message
807 $t = $this->mTitle
->getPrefixedText();
809 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
810 $text = wfMsg( 'missing-article', $t, $d );
812 $text = wfMsg( 'noarticletext' );
816 if( $this->getID() === 0 ) {
817 $wgOut->setRobotPolicy( 'noindex,nofollow' );
818 $text = "<div class='noarticletext'>\n$text\n</div>";
821 # Another whitelist check in case oldid is altering the title
822 if( !$this->mTitle
->userCanRead() ) {
823 $wgOut->loginToUse();
825 wfProfileOut( __METHOD__
);
829 # We're looking at an old revision
830 if( !empty( $oldid ) ) {
831 $wgOut->setRobotPolicy( 'noindex,nofollow' );
832 if( is_null( $this->mRevision
) ) {
833 // FIXME: This would be a nice place to load the 'no such page' text.
835 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
836 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
837 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
838 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
839 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
840 wfProfileOut( __METHOD__
);
843 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
844 // and we are allowed to see...
850 $wgOut->setRevisionId( $this->getRevIdFetched() );
852 // Pages containing custom CSS or JavaScript get special treatment
853 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
854 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
855 // Give hooks a chance to customise the output
856 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
857 // Wrap the whole lot in a <pre> and don't parse
859 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
860 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
861 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
862 $wgOut->addHTML( "\n</pre>\n" );
864 } else if( $rt = Title
::newFromRedirect( $text ) ) {
865 # Don't append the subtitle if this was an old revision
866 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
867 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
868 $wgOut->addParserOutputNoText( $parseout );
869 } else if( $pcache ) {
870 # Display content and save to parser cache
871 $this->outputWikiText( $text );
873 # Display content, don't attempt to save to parser cache
874 # Don't show section-edit links on old revisions... this way lies madness.
875 if( !$this->isCurrent() ) {
876 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
878 # Display content and don't save to parser cache
879 # With timing hack -- TS 2006-07-26
881 $this->outputWikiText( $text, false );
886 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
887 $this->mTitle
->getPrefixedDBkey()));
890 if( !$this->isCurrent() ) {
891 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
895 /* title may have been set from the cache */
896 $t = $wgOut->getPageTitle();
898 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
900 # For the main page, overwrite the <title> element with the con-
901 # tents of 'pagetitle-view-mainpage' instead of the default (if
903 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
904 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
905 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
909 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
910 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
911 $wgOut->addWikiMsg('anontalkpagetext');
914 # If we have been passed an &rcid= parameter, we want to give the user a
915 # chance to mark this new article as patrolled.
916 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
918 "<div class='patrollink'>" .
919 wfMsgHtml( 'markaspatrolledlink',
920 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
921 "action=markpatrolled&rcid=$rcid" )
928 if( $wgUseTrackbacks ) {
929 $this->addTrackbacks();
932 $this->viewUpdates();
933 wfProfileOut( __METHOD__
);
936 protected function showDeletionLog() {
937 global $wgUser, $wgOut;
938 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
939 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
940 if( $pager->getNumRows() > 0 ) {
942 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
943 $wgOut->addWikiMsg( 'deleted-notice' );
945 $loglist->beginLogEventsList() .
947 $loglist->endLogEventsList()
949 if( $pager->getNumRows() > 10 ) {
950 $wgOut->addHTML( $wgUser->getSkin()->link(
951 SpecialPage
::getTitleFor( 'Log' ),
952 wfMsgHtml( 'deletelog-fulllog' ),
954 array( 'type' => 'delete', 'page' => $this->mTitle
->getPrefixedText() )
957 $wgOut->addHTML( '</div>' );
962 * Should the parser cache be used?
964 protected function useParserCache( $oldid ) {
965 global $wgUser, $wgEnableParserCache;
967 return $wgEnableParserCache
968 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
971 && !$this->mTitle
->isCssOrJsPage()
972 && !$this->mTitle
->isCssJsSubpage();
977 * @param $target Title object of destination to redirect
978 * @param $appendSubtitle Boolean [optional]
979 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
981 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
982 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
984 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
985 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
987 if( $appendSubtitle ) {
988 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
990 $sk = $wgUser->getSkin();
992 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
994 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
996 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
997 '<span class="redirectText">'.$link.'</span>';
1001 public function addTrackbacks() {
1002 global $wgOut, $wgUser;
1003 $dbr = wfGetDB( DB_SLAVE
);
1004 $tbs = $dbr->select( 'trackbacks',
1005 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1006 array('tb_page' => $this->getID() )
1008 if( !$dbr->numRows($tbs) ) return;
1011 while( $o = $dbr->fetchObject($tbs) ) {
1013 if( $wgUser->isAllowed( 'trackback' ) ) {
1014 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1015 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1016 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1019 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1026 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1027 $this->mTitle
->invalidateCache();
1030 public function deletetrackback() {
1031 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1032 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1033 $wgOut->addWikiMsg( 'sessionfailure' );
1037 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1038 if( count($permission_errors) ) {
1039 $wgOut->showPermissionsErrorPage( $permission_errors );
1043 $db = wfGetDB( DB_MASTER
);
1044 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1046 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1047 $this->mTitle
->invalidateCache();
1050 public function render() {
1052 $wgOut->setArticleBodyOnly(true);
1057 * Handle action=purge
1059 public function purge() {
1060 global $wgUser, $wgRequest, $wgOut;
1061 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1062 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1067 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1068 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1069 $form = "<form method=\"post\" action=\"$action\">\n" .
1070 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1072 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1073 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1074 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1075 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1076 $wgOut->addHTML( $top . $form . $bottom );
1081 * Perform the actions of a page purging
1083 public function doPurge() {
1085 // Invalidate the cache
1086 $this->mTitle
->invalidateCache();
1089 // Commit the transaction before the purge is sent
1090 $dbw = wfGetDB( DB_MASTER
);
1091 $dbw->immediateCommit();
1094 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1095 $update->doUpdate();
1097 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1098 global $wgMessageCache;
1099 if( $this->getID() == 0 ) {
1102 $text = $this->getContent();
1104 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1109 * Insert a new empty page record for this article.
1110 * This *must* be followed up by creating a revision
1111 * and running $this->updateToLatest( $rev_id );
1112 * or else the record will be left in a funky state.
1113 * Best if all done inside a transaction.
1115 * @param $dbw Database
1116 * @return int The newly created page_id key, or false if the title already existed
1119 public function insertOn( $dbw ) {
1120 wfProfileIn( __METHOD__
);
1122 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1123 $dbw->insert( 'page', array(
1124 'page_id' => $page_id,
1125 'page_namespace' => $this->mTitle
->getNamespace(),
1126 'page_title' => $this->mTitle
->getDBkey(),
1127 'page_counter' => 0,
1128 'page_restrictions' => '',
1129 'page_is_redirect' => 0, # Will set this shortly...
1131 'page_random' => wfRandom(),
1132 'page_touched' => $dbw->timestamp(),
1133 'page_latest' => 0, # Fill this in shortly...
1134 'page_len' => 0, # Fill this in shortly...
1135 ), __METHOD__
, 'IGNORE' );
1137 $affected = $dbw->affectedRows();
1139 $newid = $dbw->insertId();
1140 $this->mTitle
->resetArticleId( $newid );
1142 wfProfileOut( __METHOD__
);
1143 return $affected ?
$newid : false;
1147 * Update the page record to point to a newly saved revision.
1149 * @param $dbw Database object
1150 * @param $revision Revision: For ID number, and text used to set
1151 length and redirect status fields
1152 * @param $lastRevision Integer: if given, will not overwrite the page field
1153 * when different from the currently set value.
1154 * Giving 0 indicates the new page flag should be set
1156 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1157 * removing rows in redirect table.
1158 * @return bool true on success, false on failure
1161 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1162 wfProfileIn( __METHOD__
);
1164 $text = $revision->getText();
1165 $rt = Title
::newFromRedirect( $text );
1167 $conditions = array( 'page_id' => $this->getId() );
1168 if( !is_null( $lastRevision ) ) {
1169 # An extra check against threads stepping on each other
1170 $conditions['page_latest'] = $lastRevision;
1173 $dbw->update( 'page',
1175 'page_latest' => $revision->getId(),
1176 'page_touched' => $dbw->timestamp(),
1177 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1178 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1179 'page_len' => strlen( $text ),
1184 $result = $dbw->affectedRows() != 0;
1186 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1189 wfProfileOut( __METHOD__
);
1194 * Add row to the redirect table if this is a redirect, remove otherwise.
1196 * @param $dbw Database
1197 * @param $redirectTitle a title object pointing to the redirect target,
1198 * or NULL if this is not a redirect
1199 * @param $lastRevIsRedirect If given, will optimize adding and
1200 * removing rows in redirect table.
1201 * @return bool true on success, false on failure
1204 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1205 // Always update redirects (target link might have changed)
1206 // Update/Insert if we don't know if the last revision was a redirect or not
1207 // Delete if changing from redirect to non-redirect
1208 $isRedirect = !is_null($redirectTitle);
1209 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1210 wfProfileIn( __METHOD__
);
1212 // This title is a redirect, Add/Update row in the redirect table
1213 $set = array( /* SET */
1214 'rd_namespace' => $redirectTitle->getNamespace(),
1215 'rd_title' => $redirectTitle->getDBkey(),
1216 'rd_from' => $this->getId(),
1218 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1220 // This is not a redirect, remove row from redirect table
1221 $where = array( 'rd_from' => $this->getId() );
1222 $dbw->delete( 'redirect', $where, __METHOD__
);
1224 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1225 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1227 wfProfileOut( __METHOD__
);
1228 return ( $dbw->affectedRows() != 0 );
1234 * If the given revision is newer than the currently set page_latest,
1235 * update the page record. Otherwise, do nothing.
1237 * @param $dbw Database object
1238 * @param $revision Revision object
1240 public function updateIfNewerOn( &$dbw, $revision ) {
1241 wfProfileIn( __METHOD__
);
1242 $row = $dbw->selectRow(
1243 array( 'revision', 'page' ),
1244 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1246 'page_id' => $this->getId(),
1247 'page_latest=rev_id' ),
1250 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1251 wfProfileOut( __METHOD__
);
1254 $prev = $row->rev_id
;
1255 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1257 # No or missing previous revision; mark the page as new
1259 $lastRevIsRedirect = null;
1261 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1262 wfProfileOut( __METHOD__
);
1267 * @return string Complete article text, or null if error
1269 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1270 wfProfileIn( __METHOD__
);
1271 if( $section === '' ) {
1272 // Whole-page edit; let the whole text through
1274 if( is_null($edittime) ) {
1275 $rev = Revision
::newFromTitle( $this->mTitle
);
1277 $dbw = wfGetDB( DB_MASTER
);
1278 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1281 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1282 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1285 $oldtext = $rev->getText();
1287 if( $section == 'new' ) {
1288 # Inserting a new section
1289 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1290 $text = strlen( trim( $oldtext ) ) > 0
1291 ?
"{$oldtext}\n\n{$subject}{$text}"
1292 : "{$subject}{$text}";
1294 # Replacing an existing section; roll out the big guns
1296 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1299 wfProfileOut( __METHOD__
);
1304 * @deprecated use Article::doEdit()
1306 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1307 wfDeprecated( __METHOD__
);
1308 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1309 ( $isminor ? EDIT_MINOR
: 0 ) |
1310 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1311 ( $bot ? EDIT_FORCE_BOT
: 0 );
1313 # If this is a comment, add the summary as headline
1314 if( $comment && $summary != "" ) {
1315 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1318 $this->doEdit( $text, $summary, $flags );
1320 $dbw = wfGetDB( DB_MASTER
);
1322 if(!$this->mTitle
->userIsWatching()) {
1328 if( $this->mTitle
->userIsWatching() ) {
1334 $this->doRedirect( $this->isRedirect( $text ) );
1338 * @deprecated use Article::doEdit()
1340 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1341 wfDeprecated( __METHOD__
);
1342 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1343 ( $minor ? EDIT_MINOR
: 0 ) |
1344 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1346 $status = $this->doEdit( $text, $summary, $flags );
1347 if( !$status->isOK() ) {
1351 $dbw = wfGetDB( DB_MASTER
);
1353 if(!$this->mTitle
->userIsWatching()) {
1359 if( $this->mTitle
->userIsWatching() ) {
1366 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1367 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1369 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1376 * Change an existing article or create a new article. Updates RC and all necessary caches,
1377 * optionally via the deferred update array.
1379 * $wgUser must be set before calling this function.
1381 * @param $text String: new text
1382 * @param $summary String: edit summary
1383 * @param $flags Integer bitfield:
1385 * Article is known or assumed to be non-existent, create a new one
1387 * Article is known or assumed to be pre-existing, update it
1389 * Mark this edit minor, if the user is allowed to do so
1391 * Do not log the change in recentchanges
1393 * Mark the edit a "bot" edit regardless of user rights
1394 * EDIT_DEFER_UPDATES
1395 * Defer some of the updates until the end of index.php
1397 * Fill in blank summaries with generated text where possible
1399 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1400 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1401 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1402 * edit-already-exists error will be returned. These two conditions are also possible with
1403 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1405 * @param $baseRevId the revision ID this edit was based off, if any
1406 * @param $user Optional user object, $wgUser will be used if not passed
1408 * @return Status object. Possible errors:
1409 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1410 * edit-gone-missing: In update mode, but the article didn't exist
1411 * edit-conflict: In update mode, the article changed unexpectedly
1412 * edit-no-change: Warning that the text was the same as before
1413 * edit-already-exists: In creation mode, but the article already exists
1415 * Extensions may define additional errors.
1417 * $return->value will contain an associative array with members as follows:
1418 * new: Boolean indicating if the function attempted to create a new article
1419 * revision: The revision object for the inserted revision, or null
1421 * Compatibility note: this function previously returned a boolean value indicating success/failure
1423 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1424 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1426 # Low-level sanity check
1427 if( $this->mTitle
->getText() == '' ) {
1428 throw new MWException( 'Something is trying to edit an article with an empty title' );
1431 wfProfileIn( __METHOD__
);
1433 $user = is_null($user) ?
$wgUser : $user;
1434 $status = Status
::newGood( array() );
1436 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1437 $this->loadPageData();
1439 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1440 $aid = $this->mTitle
->getArticleID();
1442 $flags |
= EDIT_UPDATE
;
1448 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1449 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1451 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1452 wfProfileOut( __METHOD__
);
1453 if( $status->isOK() ) {
1454 $status->fatal( 'edit-hook-aborted');
1459 # Silently ignore EDIT_MINOR if not allowed
1460 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1461 $bot = $flags & EDIT_FORCE_BOT
;
1463 $oldtext = $this->getContent();
1464 $oldsize = strlen( $oldtext );
1466 # Provide autosummaries if one is not provided and autosummaries are enabled.
1467 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1468 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1471 $editInfo = $this->prepareTextForEdit( $text );
1472 $text = $editInfo->pst
;
1473 $newsize = strlen( $text );
1475 $dbw = wfGetDB( DB_MASTER
);
1476 $now = wfTimestampNow();
1478 if( $flags & EDIT_UPDATE
) {
1479 # Update article, but only if changed.
1480 $status->value
['new'] = false;
1481 # Make sure the revision is either completely inserted or not inserted at all
1482 if( !$wgDBtransactions ) {
1483 $userAbort = ignore_user_abort( true );
1488 $changed = ( strcmp( $text, $oldtext ) != 0 );
1491 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1492 - (int)$this->isCountable( $oldtext );
1493 $this->mTotalAdjustment
= 0;
1495 if( !$this->mLatest
) {
1496 # Article gone missing
1497 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1498 $status->fatal( 'edit-gone-missing' );
1499 wfProfileOut( __METHOD__
);
1503 $revision = new Revision( array(
1504 'page' => $this->getId(),
1505 'comment' => $summary,
1506 'minor_edit' => $isminor,
1508 'parent_id' => $this->mLatest
,
1509 'user' => $user->getId(),
1510 'user_text' => $user->getName(),
1514 $revisionId = $revision->insertOn( $dbw );
1518 # Note that we use $this->mLatest instead of fetching a value from the master DB
1519 # during the course of this function. This makes sure that EditPage can detect
1520 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1521 # before this function is called. A previous function used a separate query, this
1522 # creates a window where concurrent edits can cause an ignored edit conflict.
1523 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1526 /* Belated edit conflict! Run away!! */
1527 $status->fatal( 'edit-conflict' );
1528 # Delete the invalid revision if the DB is not transactional
1529 if( !$wgDBtransactions ) {
1530 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1535 global $wgUseRCPatrol;
1536 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1537 # Update recentchanges
1538 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1539 # Mark as patrolled if the user can do so
1540 $patrolled = $wgUseRCPatrol && $user->isAllowed('autopatrol');
1541 # Add RC row to the DB
1542 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1543 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1544 $revisionId, $patrolled
1546 # Log auto-patrolled edits
1548 PatrolLog
::record( $rc, true );
1551 $user->incEditCount();
1555 $status->warning( 'edit-no-change' );
1557 // Keep the same revision ID, but do some updates on it
1558 $revisionId = $this->getRevIdFetched();
1559 // Update page_touched, this is usually implicit in the page update
1560 // Other cache updates are done in onArticleEdit()
1561 $this->mTitle
->invalidateCache();
1564 if( !$wgDBtransactions ) {
1565 ignore_user_abort( $userAbort );
1567 // Now that ignore_user_abort is restored, we can respond to fatal errors
1568 if( !$status->isOK() ) {
1569 wfProfileOut( __METHOD__
);
1573 # Invalidate cache of this article and all pages using this article
1574 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1575 Article
::onArticleEdit( $this->mTitle
, 'skiptransclusions' );
1576 # Update links tables, site stats, etc.
1577 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1579 # Create new article
1580 $status->value
['new'] = true;
1582 # Set statistics members
1583 # We work out if it's countable after PST to avoid counter drift
1584 # when articles are created with {{subst:}}
1585 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1586 $this->mTotalAdjustment
= 1;
1590 # Add the page record; stake our claim on this title!
1591 # This will return false if the article already exists
1592 $newid = $this->insertOn( $dbw );
1594 if( $newid === false ) {
1596 $status->fatal( 'edit-already-exists' );
1597 wfProfileOut( __METHOD__
);
1601 # Save the revision text...
1602 $revision = new Revision( array(
1604 'comment' => $summary,
1605 'minor_edit' => $isminor,
1607 'user' => $user->getId(),
1608 'user_text' => $user->getName(),
1610 $revisionId = $revision->insertOn( $dbw );
1612 $this->mTitle
->resetArticleID( $newid );
1614 # Update the page record with revision data
1615 $this->updateRevisionOn( $dbw, $revision, 0 );
1617 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1618 # Update recentchanges
1619 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1620 global $wgUseRCPatrol, $wgUseNPPatrol;
1621 # Mark as patrolled if the user can do so
1622 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $user->isAllowed('autopatrol');
1623 # Add RC row to the DB
1624 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1625 '', strlen($text), $revisionId, $patrolled );
1626 # Log auto-patrolled edits
1628 PatrolLog
::record( $rc, true );
1631 $user->incEditCount();
1634 # Update links, etc.
1635 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1638 Article
::onArticleCreate( $this->mTitle
);
1640 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1641 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1644 # Do updates right now unless deferral was requested
1645 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1649 // Return the new revision (or null) to the caller
1650 $status->value
['revision'] = $revision;
1652 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1653 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status ) );
1655 wfProfileOut( __METHOD__
);
1660 * @deprecated wrapper for doRedirect
1662 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1663 wfDeprecated( __METHOD__
);
1664 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1668 * Output a redirect back to the article.
1669 * This is typically used after an edit.
1671 * @param $noRedir Boolean: add redirect=no
1672 * @param $sectionAnchor String: section to redirect to, including "#"
1673 * @param $extraQuery String: extra query params
1675 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1678 $query = 'redirect=no';
1680 $query .= "&$query";
1682 $query = $extraQuery;
1684 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1688 * Mark this particular edit/page as patrolled
1690 public function markpatrolled() {
1691 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1692 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1694 # If we haven't been given an rc_id value, we can't do anything
1695 $rcid = (int) $wgRequest->getVal('rcid');
1696 $rc = RecentChange
::newFromId($rcid);
1697 if( is_null($rc) ) {
1698 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1702 #It would be nice to see where the user had actually come from, but for now just guess
1703 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1704 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1706 $dbw = wfGetDB( DB_MASTER
);
1707 $errors = $rc->doMarkPatrolled();
1709 if( in_array(array('rcpatroldisabled'), $errors) ) {
1710 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1714 if( in_array(array('hookaborted'), $errors) ) {
1715 // The hook itself has handled any output
1719 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1720 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1721 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1722 $wgOut->returnToMain( false, $return );
1726 if( !empty($errors) ) {
1727 $wgOut->showPermissionsErrorPage( $errors );
1732 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1733 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1734 $wgOut->returnToMain( false, $return );
1738 * User-interface handler for the "watch" action
1741 public function watch() {
1742 global $wgUser, $wgOut;
1743 if( $wgUser->isAnon() ) {
1744 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1747 if( wfReadOnly() ) {
1748 $wgOut->readOnlyPage();
1751 if( $this->doWatch() ) {
1752 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1753 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1754 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1756 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1760 * Add this page to $wgUser's watchlist
1761 * @return bool true on successful watch operation
1763 public function doWatch() {
1765 if( $wgUser->isAnon() ) {
1768 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1769 $wgUser->addWatch( $this->mTitle
);
1770 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1776 * User interface handler for the "unwatch" action.
1778 public function unwatch() {
1779 global $wgUser, $wgOut;
1780 if( $wgUser->isAnon() ) {
1781 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1784 if( wfReadOnly() ) {
1785 $wgOut->readOnlyPage();
1788 if( $this->doUnwatch() ) {
1789 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1790 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1791 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1793 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1797 * Stop watching a page
1798 * @return bool true on successful unwatch
1800 public function doUnwatch() {
1802 if( $wgUser->isAnon() ) {
1805 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1806 $wgUser->removeWatch( $this->mTitle
);
1807 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1813 * action=protect handler
1815 public function protect() {
1816 $form = new ProtectionForm( $this );
1821 * action=unprotect handler (alias)
1823 public function unprotect() {
1828 * Update the article's restriction field, and leave a log entry.
1830 * @param $limit Array: set of restriction keys
1831 * @param $reason String
1832 * @param $cascade Integer
1833 * @param $expiry Array: per restriction type expiration
1834 * @return bool true on success
1836 public function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = array() ) {
1837 global $wgUser, $wgRestrictionTypes, $wgContLang;
1839 $id = $this->mTitle
->getArticleID();
1840 if( $id <= 0 ||
wfReadOnly() ||
!$this->mTitle
->userCan('protect') ) {
1848 // Take this opportunity to purge out expired restrictions
1849 Title
::purgeExpiredRestrictions();
1851 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1852 # we expect a single selection, but the schema allows otherwise.
1854 $updated = Article
::flattenRestrictions( $limit );
1856 foreach( $wgRestrictionTypes as $action ) {
1857 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1858 $changed = ($changed ||
($this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action]) );
1861 $current = Article
::flattenRestrictions( $current );
1863 $changed = ($changed ||
( $current != $updated ) );
1864 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1865 $protect = ( $updated != '' );
1867 # If nothing's changed, do nothing
1869 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1871 $dbw = wfGetDB( DB_MASTER
);
1873 # Prepare a null revision to be added to the history
1874 $modified = $current != '' && $protect;
1876 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1878 $comment_type = 'unprotectedarticle';
1880 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1882 # Only restrictions with the 'protect' right can cascade...
1883 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1884 foreach( $limit as $action => $restriction ) {
1885 # FIXME: can $restriction be an array or what? (same as fixme above)
1886 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1891 $cascade_description = '';
1893 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1897 $comment .= ": $reason";
1899 $editComment = $comment;
1900 $encodedExpiry = array();
1901 $protect_description = '';
1902 foreach( $limit as $action => $restrictions ) {
1903 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
1904 if( $restrictions != '' ) {
1905 $protect_description .= "[$action=$restrictions] (";
1906 if( $encodedExpiry[$action] != 'infinity' ) {
1907 $protect_description .= wfMsgForContent( 'protect-expiring',
1908 $wgContLang->timeanddate( $expiry[$action], false, false ) );
1910 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1912 $protect_description .= ') ';
1915 $protect_description = trim($protect_description);
1917 if( $protect_description && $protect )
1918 $editComment .= " ($protect_description)";
1920 $editComment .= "$cascade_description";
1921 # Update restrictions table
1922 foreach( $limit as $action => $restrictions ) {
1923 if($restrictions != '' ) {
1924 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1925 array( 'pr_page' => $id,
1926 'pr_type' => $action,
1927 'pr_level' => $restrictions,
1928 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
1929 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
1931 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1932 'pr_type' => $action ), __METHOD__
);
1936 # Insert a null revision
1937 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1938 $nullRevId = $nullRevision->insertOn( $dbw );
1940 $latest = $this->getLatest();
1941 # Update page record
1942 $dbw->update( 'page',
1944 'page_touched' => $dbw->timestamp(),
1945 'page_restrictions' => '',
1946 'page_latest' => $nullRevId
1947 ), array( /* WHERE */
1949 ), 'Article::protect'
1952 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
1953 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1955 # Update the protection log
1956 $log = new LogPage( 'protect' );
1958 $params = array($protect_description,$cascade ?
'cascade' : '');
1959 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
1961 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1965 } # End "changed" check
1971 * Take an array of page restrictions and flatten it to a string
1972 * suitable for insertion into the page_restrictions field.
1973 * @param $limit Array
1976 protected static function flattenRestrictions( $limit ) {
1977 if( !is_array( $limit ) ) {
1978 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1982 foreach( $limit as $action => $restrictions ) {
1983 if( $restrictions != '' ) {
1984 $bits[] = "$action=$restrictions";
1987 return implode( ':', $bits );
1991 * Auto-generates a deletion reason
1992 * @param &$hasHistory Boolean: whether the page has a history
1994 public function generateReason( &$hasHistory ) {
1996 $dbw = wfGetDB( DB_MASTER
);
1997 // Get the last revision
1998 $rev = Revision
::newFromTitle( $this->mTitle
);
1999 if( is_null( $rev ) )
2002 // Get the article's contents
2003 $contents = $rev->getText();
2005 // If the page is blank, use the text from the previous revision,
2006 // which can only be blank if there's a move/import/protect dummy revision involved
2007 if( $contents == '' ) {
2008 $prev = $rev->getPrevious();
2010 $contents = $prev->getText();
2015 // Find out if there was only one contributor
2016 // Only scan the last 20 revisions
2018 $res = $dbw->select( 'revision', 'rev_user_text',
2019 array( 'rev_page' => $this->getID() ), __METHOD__
,
2020 array( 'LIMIT' => $limit )
2022 if( $res === false )
2023 // This page has no revisions, which is very weird
2025 if( $res->numRows() > 1 )
2028 $hasHistory = false;
2029 $row = $dbw->fetchObject( $res );
2030 $onlyAuthor = $row->rev_user_text
;
2031 // Try to find a second contributor
2032 foreach( $res as $row ) {
2033 if( $row->rev_user_text
!= $onlyAuthor ) {
2034 $onlyAuthor = false;
2038 $dbw->freeResult( $res );
2040 // Generate the summary with a '$1' placeholder
2042 // The current revision is blank and the one before is also
2043 // blank. It's just not our lucky day
2044 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2047 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2049 $reason = wfMsgForContent( 'excontent', '$1' );
2052 if( $reason == '-' ) {
2053 // Allow these UI messages to be blanked out cleanly
2057 // Replace newlines with spaces to prevent uglyness
2058 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2059 // Calculate the maximum amount of chars to get
2060 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2061 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2062 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2063 // Remove possible unfinished links
2064 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2065 // Now replace the '$1' placeholder
2066 $reason = str_replace( '$1', $contents, $reason );
2072 * UI entry point for page deletion
2074 public function delete() {
2075 global $wgUser, $wgOut, $wgRequest;
2077 $confirm = $wgRequest->wasPosted() &&
2078 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2080 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2081 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2083 $reason = $this->DeleteReasonList
;
2085 if( $reason != 'other' && $this->DeleteReason
!= '') {
2086 // Entry from drop down menu + additional comment
2087 $reason .= ': ' . $this->DeleteReason
;
2088 } elseif( $reason == 'other' ) {
2089 $reason = $this->DeleteReason
;
2091 # Flag to hide all contents of the archived revisions
2092 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2094 # This code desperately needs to be totally rewritten
2096 # Read-only check...
2097 if( wfReadOnly() ) {
2098 $wgOut->readOnlyPage();
2103 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2105 if(count($permission_errors)>0) {
2106 $wgOut->showPermissionsErrorPage( $permission_errors );
2110 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2112 # Better double-check that it hasn't been deleted yet!
2113 $dbw = wfGetDB( DB_MASTER
);
2114 $conds = $this->mTitle
->pageCond();
2115 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2116 if( $latest === false ) {
2117 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2121 # Hack for big sites
2122 $bigHistory = $this->isBigDeletion();
2123 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2124 global $wgLang, $wgDeleteRevisionsLimit;
2125 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2126 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2131 $this->doDelete( $reason, $suppress );
2132 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2134 } elseif( $this->mTitle
->userIsWatching() ) {
2140 // Generate deletion reason
2141 $hasHistory = false;
2142 if( !$reason ) $reason = $this->generateReason($hasHistory);
2144 // If the page has a history, insert a warning
2145 if( $hasHistory && !$confirm ) {
2146 $skin=$wgUser->getSkin();
2147 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2149 global $wgLang, $wgDeleteRevisionsLimit;
2150 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2151 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2155 return $this->confirmDelete( $reason );
2159 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2161 public function isBigDeletion() {
2162 global $wgDeleteRevisionsLimit;
2163 if( $wgDeleteRevisionsLimit ) {
2164 $revCount = $this->estimateRevisionCount();
2165 return $revCount > $wgDeleteRevisionsLimit;
2171 * @return int approximate revision count
2173 public function estimateRevisionCount() {
2174 $dbr = wfGetDB( DB_SLAVE
);
2175 // For an exact count...
2176 //return $dbr->selectField( 'revision', 'COUNT(*)',
2177 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2178 return $dbr->estimateRowCount( 'revision', '*',
2179 array( 'rev_page' => $this->getId() ), __METHOD__
);
2183 * Get the last N authors
2184 * @param $num Integer: number of revisions to get
2185 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2186 * @return array Array of authors, duplicates not removed
2188 public function getLastNAuthors( $num, $revLatest = 0 ) {
2189 wfProfileIn( __METHOD__
);
2190 // First try the slave
2191 // If that doesn't have the latest revision, try the master
2193 $db = wfGetDB( DB_SLAVE
);
2195 $res = $db->select( array( 'page', 'revision' ),
2196 array( 'rev_id', 'rev_user_text' ),
2198 'page_namespace' => $this->mTitle
->getNamespace(),
2199 'page_title' => $this->mTitle
->getDBkey(),
2200 'rev_page = page_id'
2201 ), __METHOD__
, $this->getSelectOptions( array(
2202 'ORDER BY' => 'rev_timestamp DESC',
2207 wfProfileOut( __METHOD__
);
2210 $row = $db->fetchObject( $res );
2211 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2212 $db = wfGetDB( DB_MASTER
);
2217 } while ( $continue );
2219 $authors = array( $row->rev_user_text
);
2220 while ( $row = $db->fetchObject( $res ) ) {
2221 $authors[] = $row->rev_user_text
;
2223 wfProfileOut( __METHOD__
);
2228 * Output deletion confirmation dialog
2229 * @param $reason String: prefilled reason
2231 public function confirmDelete( $reason ) {
2232 global $wgOut, $wgUser;
2234 wfDebug( "Article::confirmDelete\n" );
2236 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2237 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2238 $wgOut->addWikiMsg( 'confirmdeletetext' );
2240 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2241 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2243 <td class='mw-input'>" .
2244 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2245 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2251 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2253 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2254 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2255 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2256 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2257 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2258 "<tr id=\"wpDeleteReasonListRow\">
2259 <td class='mw-label'>" .
2260 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2262 <td class='mw-input'>" .
2263 Xml
::listDropDown( 'wpDeleteReasonList',
2264 wfMsgForContent( 'deletereason-dropdown' ),
2265 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2268 <tr id=\"wpDeleteReasonRow\">
2269 <td class='mw-label'>" .
2270 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2272 <td class='mw-input'>" .
2273 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2274 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2279 <td class='mw-input'>" .
2280 Xml
::checkLabel( wfMsg( 'watchthis' ),
2281 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2287 <td class='mw-submit'>" .
2288 Xml
::submitButton( wfMsg( 'deletepage' ),
2289 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2292 Xml
::closeElement( 'table' ) .
2293 Xml
::closeElement( 'fieldset' ) .
2294 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2295 Xml
::closeElement( 'form' );
2297 if( $wgUser->isAllowed( 'editinterface' ) ) {
2298 $skin = $wgUser->getSkin();
2299 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2300 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2303 $wgOut->addHTML( $form );
2304 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2308 * Perform a deletion and output success or failure messages
2310 public function doDelete( $reason, $suppress = false ) {
2311 global $wgOut, $wgUser;
2312 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2315 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2316 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2317 $deleted = $this->mTitle
->getPrefixedText();
2319 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2320 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2322 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2324 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2325 $wgOut->returnToMain( false );
2326 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2329 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2331 $wgOut->showFatalError( $error );
2337 * Back-end article deletion
2338 * Deletes the article with database consistency, writes logs, purges caches
2341 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2342 global $wgUseSquid, $wgDeferredUpdateList;
2343 global $wgUseTrackbacks;
2345 wfDebug( __METHOD__
."\n" );
2347 $dbw = wfGetDB( DB_MASTER
);
2348 $ns = $this->mTitle
->getNamespace();
2349 $t = $this->mTitle
->getDBkey();
2350 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2352 if( $t == '' ||
$id == 0 ) {
2356 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2357 array_push( $wgDeferredUpdateList, $u );
2359 // Bitfields to further suppress the content
2362 // This should be 15...
2363 $bitfield |
= Revision
::DELETED_TEXT
;
2364 $bitfield |
= Revision
::DELETED_COMMENT
;
2365 $bitfield |
= Revision
::DELETED_USER
;
2366 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2368 $bitfield = 'rev_deleted';
2372 // For now, shunt the revision data into the archive table.
2373 // Text is *not* removed from the text table; bulk storage
2374 // is left intact to avoid breaking block-compression or
2375 // immutable storage schemes.
2377 // For backwards compatibility, note that some older archive
2378 // table entries will have ar_text and ar_flags fields still.
2380 // In the future, we may keep revisions and mark them with
2381 // the rev_deleted field, which is reserved for this purpose.
2382 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2384 'ar_namespace' => 'page_namespace',
2385 'ar_title' => 'page_title',
2386 'ar_comment' => 'rev_comment',
2387 'ar_user' => 'rev_user',
2388 'ar_user_text' => 'rev_user_text',
2389 'ar_timestamp' => 'rev_timestamp',
2390 'ar_minor_edit' => 'rev_minor_edit',
2391 'ar_rev_id' => 'rev_id',
2392 'ar_text_id' => 'rev_text_id',
2393 'ar_text' => '\'\'', // Be explicit to appease
2394 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2395 'ar_len' => 'rev_len',
2396 'ar_page_id' => 'page_id',
2397 'ar_deleted' => $bitfield
2400 'page_id = rev_page'
2404 # Delete restrictions for it
2405 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2407 # Now that it's safely backed up, delete it
2408 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2409 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2415 # If using cascading deletes, we can skip some explicit deletes
2416 if( !$dbw->cascadingDeletes() ) {
2417 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2419 if($wgUseTrackbacks)
2420 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2422 # Delete outgoing links
2423 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2424 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2425 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2426 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2427 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2428 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2429 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2432 # If using cleanup triggers, we can skip some manual deletes
2433 if( !$dbw->cleanupTriggers() ) {
2434 # Clean up recentchanges entries...
2435 $dbw->delete( 'recentchanges',
2436 array( 'rc_type != '.RC_LOG
,
2437 'rc_namespace' => $this->mTitle
->getNamespace(),
2438 'rc_title' => $this->mTitle
->getDBKey() ),
2440 $dbw->delete( 'recentchanges',
2441 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2446 Article
::onArticleDelete( $this->mTitle
);
2448 # Fix category table counts
2450 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2451 foreach( $res as $row ) {
2452 $cats []= $row->cl_to
;
2454 $this->updateCategoryCounts( array(), $cats );
2456 # Clear the cached article id so the interface doesn't act like we exist
2457 $this->mTitle
->resetArticleID( 0 );
2458 $this->mTitle
->mArticleID
= 0;
2460 # Log the deletion, if the page was suppressed, log it at Oversight instead
2461 $logtype = $suppress ?
'suppress' : 'delete';
2462 $log = new LogPage( $logtype );
2464 # Make sure logging got through
2465 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2473 * Roll back the most recent consecutive set of edits to a page
2474 * from the same user; fails if there are no eligible edits to
2475 * roll back to, e.g. user is the sole contributor. This function
2476 * performs permissions checks on $wgUser, then calls commitRollback()
2477 * to do the dirty work
2479 * @param $fromP String: Name of the user whose edits to rollback.
2480 * @param $summary String: Custom summary. Set to default summary if empty.
2481 * @param $token String: Rollback token.
2482 * @param $bot Boolean: If true, mark all reverted edits as bot.
2484 * @param $resultDetails Array: contains result-specific array of additional values
2485 * 'alreadyrolled' : 'current' (rev)
2486 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2488 * @return array of errors, each error formatted as
2489 * array(messagekey, param1, param2, ...).
2490 * On success, the array is empty. This array can also be passed to
2491 * OutputPage::showPermissionsErrorPage().
2493 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2495 $resultDetails = null;
2498 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2499 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2500 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2502 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2503 $errors[] = array( 'sessionfailure' );
2505 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2506 $errors[] = array( 'actionthrottledtext' );
2508 # If there were errors, bail out now
2509 if( !empty( $errors ) )
2512 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2516 * Backend implementation of doRollback(), please refer there for parameter
2517 * and return value documentation
2519 * NOTE: This function does NOT check ANY permissions, it just commits the
2520 * rollback to the DB Therefore, you should only call this function direct-
2521 * ly if you want to use custom permissions checks. If you don't, use
2522 * doRollback() instead.
2524 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2525 global $wgUseRCPatrol, $wgUser, $wgLang;
2526 $dbw = wfGetDB( DB_MASTER
);
2528 if( wfReadOnly() ) {
2529 return array( array( 'readonlytext' ) );
2532 # Get the last editor
2533 $current = Revision
::newFromTitle( $this->mTitle
);
2534 if( is_null( $current ) ) {
2535 # Something wrong... no page?
2536 return array(array('notanarticle'));
2539 $from = str_replace( '_', ' ', $fromP );
2540 if( $from != $current->getUserText() ) {
2541 $resultDetails = array( 'current' => $current );
2542 return array(array('alreadyrolled',
2543 htmlspecialchars($this->mTitle
->getPrefixedText()),
2544 htmlspecialchars($fromP),
2545 htmlspecialchars($current->getUserText())
2549 # Get the last edit not by this guy
2550 $user = intval( $current->getUser() );
2551 $user_text = $dbw->addQuotes( $current->getUserText() );
2552 $s = $dbw->selectRow( 'revision',
2553 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2554 array( 'rev_page' => $current->getPage(),
2555 "rev_user != {$user} OR rev_user_text != {$user_text}"
2557 array( 'USE INDEX' => 'page_timestamp',
2558 'ORDER BY' => 'rev_timestamp DESC' )
2560 if( $s === false ) {
2561 # No one else ever edited this page
2562 return array(array('cantrollback'));
2563 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2564 # Only admins can see this text
2565 return array(array('notvisiblerev'));
2569 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2570 # Mark all reverted edits as bot
2573 if( $wgUseRCPatrol ) {
2574 # Mark all reverted edits as patrolled
2575 $set['rc_patrolled'] = 1;
2579 $dbw->update( 'recentchanges', $set,
2581 'rc_cur_id' => $current->getPage(),
2582 'rc_user_text' => $current->getUserText(),
2583 "rc_timestamp > '{$s->rev_timestamp}'",
2588 # Generate the edit summary if necessary
2589 $target = Revision
::newFromId( $s->rev_id
);
2590 if( empty( $summary ) ){
2591 $summary = wfMsgForContent( 'revertpage' );
2594 # Allow the custom summary to use the same args as the default message
2596 $target->getUserText(), $from, $s->rev_id
,
2597 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2598 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2600 $summary = wfMsgReplaceArgs( $summary, $args );
2603 $flags = EDIT_UPDATE
;
2605 if( $wgUser->isAllowed('minoredit') )
2606 $flags |
= EDIT_MINOR
;
2608 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2609 $flags |
= EDIT_FORCE_BOT
;
2610 # Actually store the edit
2611 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2612 if( !empty( $status->value
['revision'] ) ) {
2613 $revId = $status->value
['revision']->getId();
2618 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2620 $resultDetails = array(
2621 'summary' => $summary,
2622 'current' => $current,
2623 'target' => $target,
2630 * User interface for rollback operations
2632 public function rollback() {
2633 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2636 $result = $this->doRollback(
2637 $wgRequest->getVal( 'from' ),
2638 $wgRequest->getText( 'summary' ),
2639 $wgRequest->getVal( 'token' ),
2640 $wgRequest->getBool( 'bot' ),
2644 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2645 $wgOut->rateLimited();
2648 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2649 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2650 $errArray = $result[0];
2651 $errMsg = array_shift( $errArray );
2652 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2653 if( isset( $details['current'] ) ){
2654 $current = $details['current'];
2655 if( $current->getComment() != '' ) {
2656 $wgOut->addWikiMsgArray( 'editcomment', array(
2657 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2662 # Display permissions errors before read-only message -- there's no
2663 # point in misleading the user into thinking the inability to rollback
2664 # is only temporary.
2665 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2666 # array_diff is completely broken for arrays of arrays, sigh. Re-
2667 # move any 'readonlytext' error manually.
2669 foreach( $result as $error ) {
2670 if( $error != array( 'readonlytext' ) ) {
2674 $wgOut->showPermissionsErrorPage( $out );
2677 if( $result == array( array( 'readonlytext' ) ) ) {
2678 $wgOut->readOnlyPage();
2682 $current = $details['current'];
2683 $target = $details['target'];
2684 $newId = $details['newid'];
2685 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2686 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2687 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2688 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2689 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2690 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2691 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2692 $wgOut->returnToMain( false, $this->mTitle
);
2694 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2695 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2696 $de->showDiff( '', '' );
2702 * Do standard deferred updates after page view
2704 protected function viewUpdates() {
2705 global $wgDeferredUpdateList, $wgUser;
2706 if( 0 != $this->getID() ) {
2707 # Don't update page view counters on views from bot users (bug 14044)
2708 global $wgDisableCounters;
2709 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2710 Article
::incViewCount( $this->getID() );
2711 $u = new SiteStatsUpdate( 1, 0, 0 );
2712 array_push( $wgDeferredUpdateList, $u );
2715 # Update newtalk / watchlist notification status
2716 $wgUser->clearNotification( $this->mTitle
);
2720 * Prepare text which is about to be saved.
2721 * Returns a stdclass with source, pst and output members
2723 public function prepareTextForEdit( $text, $revid=null ) {
2724 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2726 return $this->mPreparedEdit
;
2729 $edit = (object)array();
2730 $edit->revid
= $revid;
2731 $edit->newText
= $text;
2732 $edit->pst
= $this->preSaveTransform( $text );
2733 $options = new ParserOptions
;
2734 $options->setTidy( true );
2735 $options->enableLimitReport();
2736 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2737 $edit->oldText
= $this->getContent();
2738 $this->mPreparedEdit
= $edit;
2743 * Do standard deferred updates after page edit.
2744 * Update links tables, site stats, search index and message cache.
2745 * Purges pages that include this page if the text was changed here.
2746 * Every 100th edit, prune the recent changes table.
2749 * @param $text New text of the article
2750 * @param $summary Edit summary
2751 * @param $minoredit Minor edit
2752 * @param $timestamp_of_pagechange Timestamp associated with the page change
2753 * @param $newid rev_id value of the new revision
2754 * @param $changed Whether or not the content actually changed
2756 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2757 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2759 wfProfileIn( __METHOD__
);
2762 # Be careful not to double-PST: $text is usually already PST-ed once
2763 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2764 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2765 $editInfo = $this->prepareTextForEdit( $text, $newid );
2767 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2768 $editInfo = $this->mPreparedEdit
;
2771 # Save it to the parser cache
2772 if( $wgEnableParserCache ) {
2773 $parserCache = ParserCache
::singleton();
2774 $parserCache->save( $editInfo->output
, $this, $wgUser );
2777 # Update the links tables
2778 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
, false );
2779 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2782 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2784 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2785 if( 0 == mt_rand( 0, 99 ) ) {
2786 // Flush old entries from the `recentchanges` table; we do this on
2787 // random requests so as to avoid an increase in writes for no good reason
2789 $dbw = wfGetDB( DB_MASTER
);
2790 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2791 $recentchanges = $dbw->tableName( 'recentchanges' );
2792 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2793 $dbw->query( $sql );
2797 $id = $this->getID();
2798 $title = $this->mTitle
->getPrefixedDBkey();
2799 $shortTitle = $this->mTitle
->getDBkey();
2802 wfProfileOut( __METHOD__
);
2806 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2807 array_push( $wgDeferredUpdateList, $u );
2808 $u = new SearchUpdate( $id, $title, $text );
2809 array_push( $wgDeferredUpdateList, $u );
2811 # If this is another user's talk page, update newtalk
2812 # Don't do this if $changed = false otherwise some idiot can null-edit a
2813 # load of user talk pages and piss people off, nor if it's a minor edit
2814 # by a properly-flagged bot.
2815 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2816 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2817 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2818 $other = User
::newFromName( $shortTitle, false );
2820 wfDebug( __METHOD__
.": invalid username\n" );
2821 } elseif( User
::isIP( $shortTitle ) ) {
2822 // An anonymous user
2823 $other->setNewtalk( true );
2824 } elseif( $other->isLoggedIn() ) {
2825 $other->setNewtalk( true );
2827 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2832 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2833 $wgMessageCache->replace( $shortTitle, $text );
2836 wfProfileOut( __METHOD__
);
2840 * Perform article updates on a special page creation.
2842 * @param $rev Revision object
2844 * @todo This is a shitty interface function. Kill it and replace the
2845 * other shitty functions like editUpdates and such so it's not needed
2848 public function createUpdates( $rev ) {
2849 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2850 $this->mTotalAdjustment
= 1;
2851 $this->editUpdates( $rev->getText(), $rev->getComment(),
2852 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2856 * Generate the navigation links when browsing through an article revisions
2857 * It shows the information as:
2858 * Revision as of \<date\>; view current revision
2859 * \<- Previous version | Next Version -\>
2861 * @param $oldid String: revision ID of this article revision
2863 public function setOldSubtitle( $oldid=0 ) {
2864 global $wgLang, $wgOut, $wgUser;
2866 if( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2870 $revision = Revision
::newFromId( $oldid );
2872 $current = ( $oldid == $this->mLatest
);
2873 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2874 $sk = $wgUser->getSkin();
2876 ?
wfMsg( 'currentrevisionlink' )
2877 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2880 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2881 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2883 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2884 : wfMsg( 'previousrevision' );
2886 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2888 $nextlink = $current
2889 ?
wfMsg( 'nextrevision' )
2890 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2891 $nextdiff = $current
2893 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2896 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2897 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2898 if( $revision->isCurrent() ) {
2899 // We don't handle top deleted edits too well
2900 $cdel = wfMsgHtml('rev-delundel');
2901 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2902 // If revision was hidden from sysops
2903 $cdel = wfMsgHtml('rev-delundel');
2905 $cdel = $sk->makeKnownLinkObj( $revdel,
2906 wfMsgHtml('rev-delundel'),
2907 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2908 '&oldid=' . urlencode( $oldid ) );
2909 // Bolden oversighted content
2910 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2911 $cdel = "<strong>$cdel</strong>";
2913 $cdel = "(<small>$cdel</small>) ";
2915 # Show user links if allowed to see them. Normally they
2916 # are hidden regardless, but since we can already see the text here...
2917 $userlinks = $sk->revUserTools( $revision, false );
2919 $m = wfMsg( 'revision-info-current' );
2920 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2921 ?
'revision-info-current'
2924 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks, $revision->getID() ) . "</div>\n" .
2926 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff,
2927 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2928 $wgOut->setSubtitle( $r );
2932 * This function is called right before saving the wikitext,
2933 * so we can do things like signatures and links-in-context.
2935 * @param $text String
2937 public function preSaveTransform( $text ) {
2938 global $wgParser, $wgUser;
2939 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2942 /* Caching functions */
2945 * checkLastModified returns true if it has taken care of all
2946 * output to the client that is necessary for this request.
2947 * (that is, it has sent a cached version of the page)
2949 protected function tryFileCache() {
2950 static $called = false;
2952 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2956 if( $this->isFileCacheable() ) {
2957 $cache = new HTMLFileCache( $this->mTitle
);
2958 if( $cache->isFileCacheGood( $this->mTouched
) ) {
2959 wfDebug( "Article::tryFileCache(): about to load file\n" );
2960 $cache->loadFromFileCache();
2963 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2964 ob_start( array(&$cache, 'saveToFileCache' ) );
2967 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2973 * Check if the page can be cached
2976 public function isFileCacheable() {
2977 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2978 // Get all query values
2979 $queryVals = $wgRequest->getValues();
2980 foreach( $queryVals as $query => $val ) {
2981 // Normal page view in query form can have action=view
2982 if( $query !== 'title' && $query !== 'curid' && !($query == 'action' && $val == 'view') ) {
2986 // Check for non-standard user language; this covers uselang,
2987 // and extensions for auto-detecting user language.
2988 $ulang = $wgLang->getCode();
2989 $clang = $wgContLang->getCode();
2991 $cacheable = $wgUseFileCache
2992 && !$wgShowIPinHeader
2993 && $this->getID() > 0
2994 && $wgUser->isAnon()
2995 && !$wgUser->getNewtalk()
2996 && !$this->mRedirectedFrom
2997 && $ulang === $clang;
2998 // Extension may have reason to disable file caching on some pages.
3000 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3006 * Loads page_touched and returns a value indicating if it should be used
3009 public function checkTouched() {
3010 if( !$this->mDataLoaded
) {
3011 $this->loadPageData();
3013 return !$this->mIsRedirect
;
3017 * Get the page_touched field
3019 public function getTouched() {
3020 # Ensure that page data has been loaded
3021 if( !$this->mDataLoaded
) {
3022 $this->loadPageData();
3024 return $this->mTouched
;
3028 * Get the page_latest field
3030 public function getLatest() {
3031 if( !$this->mDataLoaded
) {
3032 $this->loadPageData();
3034 return $this->mLatest
;
3038 * Edit an article without doing all that other stuff
3039 * The article must already exist; link tables etc
3040 * are not updated, caches are not flushed.
3042 * @param $text String: text submitted
3043 * @param $comment String: comment submitted
3044 * @param $minor Boolean: whereas it's a minor modification
3046 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3047 wfProfileIn( __METHOD__
);
3049 $dbw = wfGetDB( DB_MASTER
);
3050 $revision = new Revision( array(
3051 'page' => $this->getId(),
3053 'comment' => $comment,
3054 'minor_edit' => $minor ?
1 : 0,
3056 $revision->insertOn( $dbw );
3057 $this->updateRevisionOn( $dbw, $revision );
3059 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3061 wfProfileOut( __METHOD__
);
3065 * Used to increment the view counter
3067 * @param $id Integer: article id
3069 public static function incViewCount( $id ) {
3070 $id = intval( $id );
3071 global $wgHitcounterUpdateFreq, $wgDBtype;
3073 $dbw = wfGetDB( DB_MASTER
);
3074 $pageTable = $dbw->tableName( 'page' );
3075 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3076 $acchitsTable = $dbw->tableName( 'acchits' );
3078 if( $wgHitcounterUpdateFreq <= 1 ) {
3079 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3083 # Not important enough to warrant an error page in case of failure
3084 $oldignore = $dbw->ignoreErrors( true );
3086 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3088 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3089 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3090 # Most of the time (or on SQL errors), skip row count check
3091 $dbw->ignoreErrors( $oldignore );
3095 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3096 $row = $dbw->fetchObject( $res );
3097 $rown = intval( $row->n
);
3098 if( $rown >= $wgHitcounterUpdateFreq ){
3099 wfProfileIn( 'Article::incViewCount-collect' );
3100 $old_user_abort = ignore_user_abort( true );
3102 if($wgDBtype == 'mysql')
3103 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3104 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3105 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3106 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3108 $dbw->query("DELETE FROM $hitcounterTable");
3109 if($wgDBtype == 'mysql') {
3110 $dbw->query('UNLOCK TABLES');
3111 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3112 'WHERE page_id = hc_id');
3115 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3116 "FROM $acchitsTable WHERE page_id = hc_id");
3118 $dbw->query("DROP TABLE $acchitsTable");
3120 ignore_user_abort( $old_user_abort );
3121 wfProfileOut( 'Article::incViewCount-collect' );
3123 $dbw->ignoreErrors( $oldignore );
3127 * The onArticle*() functions are supposed to be a kind of hooks
3128 * which should be called whenever any of the specified actions
3131 * This is a good place to put code to clear caches, for instance.
3133 * This is called on page move and undelete, as well as edit
3135 * @param $title a title object
3138 public static function onArticleCreate( $title ) {
3139 # Update existence markers on article/talk tabs...
3140 if( $title->isTalkPage() ) {
3141 $other = $title->getSubjectPage();
3143 $other = $title->getTalkPage();
3145 $other->invalidateCache();
3146 $other->purgeSquid();
3148 $title->touchLinks();
3149 $title->purgeSquid();
3150 $title->deleteTitleProtection();
3153 public static function onArticleDelete( $title ) {
3154 global $wgUseFileCache, $wgMessageCache;
3155 # Update existence markers on article/talk tabs...
3156 if( $title->isTalkPage() ) {
3157 $other = $title->getSubjectPage();
3159 $other = $title->getTalkPage();
3161 $other->invalidateCache();
3162 $other->purgeSquid();
3164 $title->touchLinks();
3165 $title->purgeSquid();
3168 if( $wgUseFileCache ) {
3169 $cm = new HTMLFileCache( $title );
3170 @unlink
( $cm->fileCacheName() );
3174 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3175 $wgMessageCache->replace( $title->getDBkey(), false );
3178 if( $title->getNamespace() == NS_FILE
) {
3179 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3180 $update->doUpdate();
3183 if( $title->getNamespace() == NS_USER_TALK
) {
3184 $user = User
::newFromName( $title->getText(), false );
3185 $user->setNewtalk( false );
3190 * Purge caches on page update etc
3192 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3193 global $wgDeferredUpdateList, $wgUseFileCache;
3195 // Invalidate caches of articles which include this page
3196 if( $transclusions !== 'skiptransclusions' )
3197 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3199 // Invalidate the caches of all pages which redirect here
3200 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3202 # Purge squid for this page only
3203 $title->purgeSquid();
3205 # Clear file cache for this page only
3206 if( $wgUseFileCache ) {
3207 $cm = new HTMLFileCache( $title );
3208 @unlink
( $cm->fileCacheName() );
3215 * Overriden by ImagePage class, only present here to avoid a fatal error
3216 * Called for ?action=revert
3218 public function revert() {
3220 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3224 * Info about this page
3225 * Called for ?action=info when $wgAllowPageInfo is on.
3227 public function info() {
3228 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3230 if( !$wgAllowPageInfo ) {
3231 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3235 $page = $this->mTitle
->getSubjectPage();
3237 $wgOut->setPagetitle( $page->getPrefixedText() );
3238 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3239 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3241 if( !$this->mTitle
->exists() ) {
3242 $wgOut->addHTML( '<div class="noarticletext">' );
3243 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3244 // This doesn't quite make sense; the user is asking for
3245 // information about the _page_, not the message... -- RC
3246 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3248 $msg = $wgUser->isLoggedIn()
3250 : 'noarticletextanon';
3251 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3253 $wgOut->addHTML( '</div>' );
3255 $dbr = wfGetDB( DB_SLAVE
);
3257 'wl_title' => $page->getDBkey(),
3258 'wl_namespace' => $page->getNamespace() );
3259 $numwatchers = $dbr->selectField(
3264 $this->getSelectOptions() );
3266 $pageInfo = $this->pageCountInfo( $page );
3267 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3269 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3270 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3272 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3274 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3276 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3278 $wgOut->addHTML( '</ul>' );
3283 * Return the total number of edits and number of unique editors
3284 * on a given page. If page does not exist, returns false.
3286 * @param $title Title object
3289 protected function pageCountInfo( $title ) {
3290 $id = $title->getArticleId();
3294 $dbr = wfGetDB( DB_SLAVE
);
3295 $rev_clause = array( 'rev_page' => $id );
3296 $edits = $dbr->selectField(
3301 $this->getSelectOptions()
3303 $authors = $dbr->selectField(
3305 'COUNT(DISTINCT rev_user_text)',
3308 $this->getSelectOptions()
3310 return array( 'edits' => $edits, 'authors' => $authors );
3314 * Return a list of templates used by this article.
3315 * Uses the templatelinks table
3317 * @return Array of Title objects
3319 public function getUsedTemplates() {
3321 $id = $this->mTitle
->getArticleID();
3325 $dbr = wfGetDB( DB_SLAVE
);
3326 $res = $dbr->select( array( 'templatelinks' ),
3327 array( 'tl_namespace', 'tl_title' ),
3328 array( 'tl_from' => $id ),
3330 if( $res !== false ) {
3331 foreach( $res as $row ) {
3332 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3335 $dbr->freeResult( $res );
3340 * Returns a list of hidden categories this page is a member of.
3341 * Uses the page_props and categorylinks tables.
3343 * @return Array of Title objects
3345 public function getHiddenCategories() {
3347 $id = $this->mTitle
->getArticleID();
3351 $dbr = wfGetDB( DB_SLAVE
);
3352 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3354 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3355 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3357 if( $res !== false ) {
3358 foreach( $res as $row ) {
3359 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3362 $dbr->freeResult( $res );
3367 * Return an applicable autosummary if one exists for the given edit.
3368 * @param $oldtext String: the previous text of the page.
3369 * @param $newtext String: The submitted text of the page.
3370 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3371 * @return string An appropriate autosummary, or an empty string.
3373 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3374 # Decide what kind of autosummary is needed.
3376 # Redirect autosummaries
3377 $ot = Title
::newFromRedirect( $oldtext );
3378 $rt = Title
::newFromRedirect( $newtext );
3379 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3380 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3383 # New page autosummaries
3384 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3385 # If they're making a new article, give its text, truncated, in the summary.
3387 $truncatedtext = $wgContLang->truncate(
3388 str_replace("\n", ' ', $newtext),
3389 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3391 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3394 # Blanking autosummaries
3395 if( $oldtext != '' && $newtext == '' ) {
3396 return wfMsgForContent( 'autosumm-blank' );
3397 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3398 # Removing more than 90% of the article
3400 $truncatedtext = $wgContLang->truncate(
3402 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3405 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3408 # If we reach this point, there's no applicable autosummary for our case, so our
3409 # autosummary is empty.
3414 * Add the primary page-view wikitext to the output buffer
3415 * Saves the text into the parser cache if possible.
3416 * Updates templatelinks if it is out of date.
3418 * @param $text String
3419 * @param $cache Boolean
3421 public function outputWikiText( $text, $cache = true ) {
3422 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3424 $popts = $wgOut->parserOptions();
3425 $popts->setTidy(true);
3426 $popts->enableLimitReport();
3427 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3428 $popts, true, true, $this->getRevIdFetched() );
3429 $popts->setTidy(false);
3430 $popts->enableLimitReport( false );
3431 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3432 $parserCache = ParserCache
::singleton();
3433 $parserCache->save( $parserOutput, $this, $wgUser );
3435 // Make sure file cache is not used on uncacheable content.
3436 // Output that has magic words in it can still use the parser cache
3437 // (if enabled), though it will generally expire sooner.
3438 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3439 $wgUseFileCache = false;
3442 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3443 // templatelinks table may have become out of sync,
3444 // especially if using variable-based transclusions.
3445 // For paranoia, check if things have changed and if
3446 // so apply updates to the database. This will ensure
3447 // that cascaded protections apply as soon as the changes
3450 # Get templates from templatelinks
3451 $id = $this->mTitle
->getArticleID();
3453 $tlTemplates = array();
3455 $dbr = wfGetDB( DB_SLAVE
);
3456 $res = $dbr->select( array( 'templatelinks' ),
3457 array( 'tl_namespace', 'tl_title' ),
3458 array( 'tl_from' => $id ),
3463 if( $res !== false ) {
3464 foreach( $res as $row ) {
3465 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3469 # Get templates from parser output.
3470 $poTemplates_allns = $parserOutput->getTemplates();
3472 $poTemplates = array ();
3473 foreach ( $poTemplates_allns as $ns_templates ) {
3474 $poTemplates = array_merge( $poTemplates, $ns_templates );
3478 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3480 if( count( $templates_diff ) > 0 ) {
3481 # Whee, link updates time.
3482 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3487 $wgOut->addParserOutput( $parserOutput );
3491 * Update all the appropriate counts in the category table, given that
3492 * we've added the categories $added and deleted the categories $deleted.
3494 * @param $added array The names of categories that were added
3495 * @param $deleted array The names of categories that were deleted
3498 public function updateCategoryCounts( $added, $deleted ) {
3499 $ns = $this->mTitle
->getNamespace();
3500 $dbw = wfGetDB( DB_MASTER
);
3502 # First make sure the rows exist. If one of the "deleted" ones didn't
3503 # exist, we might legitimately not create it, but it's simpler to just
3504 # create it and then give it a negative value, since the value is bogus
3507 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3508 $insertCats = array_merge( $added, $deleted );
3509 if( !$insertCats ) {
3510 # Okay, nothing to do
3513 $insertRows = array();
3514 foreach( $insertCats as $cat ) {
3515 $insertRows[] = array( 'cat_title' => $cat );
3517 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3519 $addFields = array( 'cat_pages = cat_pages + 1' );
3520 $removeFields = array( 'cat_pages = cat_pages - 1' );
3521 if( $ns == NS_CATEGORY
) {
3522 $addFields[] = 'cat_subcats = cat_subcats + 1';
3523 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3524 } elseif( $ns == NS_FILE
) {
3525 $addFields[] = 'cat_files = cat_files + 1';
3526 $removeFields[] = 'cat_files = cat_files - 1';
3533 array( 'cat_title' => $added ),
3541 array( 'cat_title' => $deleted ),