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 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 );
62 return $t == null ?
null : new Article( $t );
66 * Tell the page view functions that this view was redirected
67 * from another page on the wiki.
68 * @param $from Title object.
70 function setRedirectedFrom( $from ) {
71 $this->mRedirectedFrom
= $from;
75 * If this page is a redirect, get its target
77 * The target will be fetched from the redirect table if possible.
78 * If this page doesn't have an entry there, call insertRedirect()
79 * @return mixed Title object, or null if this page is not a redirect
81 public function getRedirectTarget() {
82 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
84 if(!is_null($this->mRedirectTarget
))
85 return $this->mRedirectTarget
;
87 # Query the redirect table
88 $dbr = wfGetDB(DB_SLAVE
);
89 $res = $dbr->select('redirect',
90 array('rd_namespace', 'rd_title'),
91 array('rd_from' => $this->getID()),
94 $row = $dbr->fetchObject($res);
96 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
98 # This page doesn't have an entry in the redirect table
99 return $this->mRedirectTarget
= $this->insertRedirect();
103 * Insert an entry for this page into the redirect table.
105 * Don't call this function directly unless you know what you're doing.
106 * @return Title object
108 public function insertRedirect() {
109 $retval = Title
::newFromRedirect($this->getContent());
112 $dbw = wfGetDB(DB_MASTER
);
113 $dbw->replace('redirect', array('rd_from'), array(
114 'rd_from' => $this->getID(),
115 'rd_namespace' => $retval->getNamespace(),
116 'rd_title' => $retval->getDBKey()
122 * Get the Title object this page redirects to
124 * @return mixed false, Title of in-wiki target, or string with URL
126 public function followRedirect() {
127 $text = $this->getContent();
128 return $this->followRedirectText( $text );
132 * Get the Title object this text redirects to
134 * @return mixed false, Title of in-wiki target, or string with URL
136 public function followRedirectText( $text ) {
137 $rt = Title
::newFromRedirect( $text );
138 # process if title object is valid and not special:userlogout
140 if( $rt->getInterwiki() != '' ) {
141 if( $rt->isLocal() ) {
142 // Offsite wikis need an HTTP redirect.
144 // This can be hard to reverse and may produce loops,
145 // 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.
158 if( $rt->isSpecial( 'Userlogout' ) ) {
161 return $rt->getFullURL();
167 // No or invalid redirect
172 * get the title object of the article
174 function getTitle() {
175 return $this->mTitle
;
183 $this->mDataLoaded
= false;
184 $this->mContentLoaded
= false;
186 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
187 $this->mRedirectedFrom
= null; # Title object if set
188 $this->mRedirectTarget
= null; # Title object if set
190 $this->mTimestamp
= $this->mComment
= '';
191 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
192 $this->mTouched
= '19700101000000';
193 $this->mForUpdate
= false;
194 $this->mIsRedirect
= false;
195 $this->mRevIdFetched
= 0;
196 $this->mRedirectUrl
= false;
197 $this->mLatest
= false;
198 $this->mPreparedEdit
= false;
202 * Note that getContent/loadContent do not follow redirects anymore.
203 * If you need to fetch redirectable content easily, try
204 * the shortcut in Article::followContent()
206 * @todo There are still side-effects in this!
207 * In general, you should use the Revision class, not Article,
208 * to fetch text for purposes other than page views.
210 * @return Return the text of this revision
212 function getContent() {
213 global $wgUser, $wgOut, $wgMessageCache;
215 wfProfileIn( __METHOD__
);
217 if ( 0 == $this->getID() ) {
218 wfProfileOut( __METHOD__
);
219 $wgOut->setRobotPolicy( 'noindex,nofollow' );
221 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
222 $wgMessageCache->loadAllMessages();
223 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
225 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
228 return "<div class='noarticletext'>\n$ret\n</div>";
230 $this->loadContent();
231 wfProfileOut( __METHOD__
);
232 return $this->mContent
;
237 * This function returns the text of a section, specified by a number ($section).
238 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
239 * the first section before any such heading (section 0).
241 * If a section contains subsections, these are also returned.
243 * @param $text String: text to look in
244 * @param $section Integer: section number
245 * @return string text of the requested section
248 function getSection($text,$section) {
250 return $wgParser->getSection( $text, $section );
254 * @return int The oldid of the article that is to be shown, 0 for the
257 function getOldID() {
258 if ( is_null( $this->mOldId
) ) {
259 $this->mOldId
= $this->getOldIDFromRequest();
261 return $this->mOldId
;
265 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
267 * @return int The old id for the request
269 public function getOldIDFromRequest() {
271 $this->mRedirectUrl
= false;
272 $oldid = $wgRequest->getVal( 'oldid' );
273 if ( isset( $oldid ) ) {
274 $oldid = intval( $oldid );
275 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
276 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
280 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
282 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
283 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
301 * Load the revision (including text) into this object
303 function loadContent() {
304 if ( $this->mContentLoaded
) return;
307 $oldid = $this->getOldID();
309 # Pre-fill content with error message so that if something
310 # fails we'll have something telling us what we intended.
311 $this->mOldId
= $oldid;
312 $this->fetchContent( $oldid );
317 * Fetch a page record with the given conditions
318 * @param Database $dbr
319 * @param array $conditions
322 function pageData( $dbr, $conditions ) {
336 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
337 $row = $dbr->selectRow(
343 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
348 * @param Database $dbr
349 * @param Title $title
351 function pageDataFromTitle( $dbr, $title ) {
352 return $this->pageData( $dbr, array(
353 'page_namespace' => $title->getNamespace(),
354 'page_title' => $title->getDBkey() ) );
358 * @param Database $dbr
361 function pageDataFromId( $dbr, $id ) {
362 return $this->pageData( $dbr, array( 'page_id' => $id ) );
366 * Set the general counter, title etc data loaded from
369 * @param object $data
372 function loadPageData( $data = 'fromdb' ) {
373 if ( $data === 'fromdb' ) {
374 $dbr = wfGetDB( DB_MASTER
);
375 $data = $this->pageDataFromId( $dbr, $this->getId() );
378 $lc = LinkCache
::singleton();
380 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
382 $this->mTitle
->mArticleID
= $data->page_id
;
384 # Old-fashioned restrictions.
385 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
387 $this->mCounter
= $data->page_counter
;
388 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
389 $this->mIsRedirect
= $data->page_is_redirect
;
390 $this->mLatest
= $data->page_latest
;
392 if ( is_object( $this->mTitle
) ) {
393 $lc->addBadLinkObj( $this->mTitle
);
395 $this->mTitle
->mArticleID
= 0;
398 $this->mDataLoaded
= true;
402 * Get text of an article from database
403 * Does *NOT* follow redirects.
404 * @param int $oldid 0 for whatever the latest revision is
407 function fetchContent( $oldid = 0 ) {
408 if ( $this->mContentLoaded
) {
409 return $this->mContent
;
412 $dbr = wfGetDB( DB_MASTER
);
414 # Pre-fill content with error message so that if something
415 # fails we'll have something telling us what we intended.
416 $t = $this->mTitle
->getPrefixedText();
417 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
418 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
421 $revision = Revision
::newFromId( $oldid );
422 if( is_null( $revision ) ) {
423 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
426 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
428 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
431 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
432 $this->loadPageData( $data );
434 if( !$this->mDataLoaded
) {
435 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
437 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
440 $this->loadPageData( $data );
442 $revision = Revision
::newFromId( $this->mLatest
);
443 if( is_null( $revision ) ) {
444 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
449 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
450 // We should instead work with the Revision object when we need it...
451 $this->mContent
= $revision->revText(); // Loads if user is allowed
453 $this->mUser
= $revision->getUser();
454 $this->mUserText
= $revision->getUserText();
455 $this->mComment
= $revision->getComment();
456 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
458 $this->mRevIdFetched
= $revision->getId();
459 $this->mContentLoaded
= true;
460 $this->mRevision
=& $revision;
462 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
464 return $this->mContent
;
468 * Read/write accessor to select FOR UPDATE
470 * @param $x Mixed: FIXME
472 function forUpdate( $x = NULL ) {
473 return wfSetVar( $this->mForUpdate
, $x );
477 * Get the database which should be used for reads
480 * @deprecated - just call wfGetDB( DB_MASTER ) instead
483 wfDeprecated( __METHOD__
);
484 return wfGetDB( DB_MASTER
);
488 * Get options for all SELECT statements
490 * @param $options Array: an optional options array which'll be appended to
492 * @return Array: options
494 function getSelectOptions( $options = '' ) {
495 if ( $this->mForUpdate
) {
496 if ( is_array( $options ) ) {
497 $options[] = 'FOR UPDATE';
499 $options = 'FOR UPDATE';
506 * @return int Page ID
509 if( $this->mTitle
) {
510 return $this->mTitle
->getArticleID();
517 * @return bool Whether or not the page exists in the database
520 return $this->getId() != 0;
524 * @return int The view count for the page
526 function getCount() {
527 if ( -1 == $this->mCounter
) {
528 $id = $this->getID();
532 $dbr = wfGetDB( DB_SLAVE
);
533 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
534 'Article::getCount', $this->getSelectOptions() );
537 return $this->mCounter
;
541 * Determine whether a page would be suitable for being counted as an
542 * article in the site_stats table based on the title & its content
544 * @param $text String: text to analyze
547 function isCountable( $text ) {
548 global $wgUseCommaCount;
550 $token = $wgUseCommaCount ?
',' : '[[';
552 $this->mTitle
->isContentPage()
553 && !$this->isRedirect( $text )
554 && in_string( $token, $text );
558 * Tests if the article text represents a redirect
560 * @param $text String: FIXME
563 function isRedirect( $text = false ) {
564 if ( $text === false ) {
565 if ( $this->mDataLoaded
)
566 return $this->mIsRedirect
;
568 // Apparently loadPageData was never called
569 $this->loadContent();
570 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
572 $titleObj = Title
::newFromRedirect( $text );
574 return $titleObj !== NULL;
578 * Returns true if the currently-referenced revision is the current edit
579 * to this page (and it exists).
582 function isCurrent() {
583 # If no oldid, this is the current version.
584 if ($this->getOldID() == 0)
587 return $this->exists() &&
588 isset( $this->mRevision
) &&
589 $this->mRevision
->isCurrent();
593 * Loads everything except the text
594 * This isn't necessary for all uses, so it's only done if needed.
597 function loadLastEdit() {
598 if ( -1 != $this->mUser
)
601 # New or non-existent articles have no user information
602 $id = $this->getID();
603 if ( 0 == $id ) return;
605 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
606 if( !is_null( $this->mLastRevision
) ) {
607 $this->mUser
= $this->mLastRevision
->getUser();
608 $this->mUserText
= $this->mLastRevision
->getUserText();
609 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
610 $this->mComment
= $this->mLastRevision
->getComment();
611 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
612 $this->mRevIdFetched
= $this->mLastRevision
->getId();
616 function getTimestamp() {
617 // Check if the field has been filled by ParserCache::get()
618 if ( !$this->mTimestamp
) {
619 $this->loadLastEdit();
621 return wfTimestamp(TS_MW
, $this->mTimestamp
);
625 $this->loadLastEdit();
629 function getUserText() {
630 $this->loadLastEdit();
631 return $this->mUserText
;
634 function getComment() {
635 $this->loadLastEdit();
636 return $this->mComment
;
639 function getMinorEdit() {
640 $this->loadLastEdit();
641 return $this->mMinorEdit
;
644 function getRevIdFetched() {
645 $this->loadLastEdit();
646 return $this->mRevIdFetched
;
650 * @param $limit Integer: default 0.
651 * @param $offset Integer: default 0.
653 function getContributors($limit = 0, $offset = 0) {
654 # XXX: this is expensive; cache this info somewhere.
657 $dbr = wfGetDB( DB_SLAVE
);
658 $revTable = $dbr->tableName( 'revision' );
659 $userTable = $dbr->tableName( 'user' );
660 $user = $this->getUser();
661 $pageId = $this->getId();
663 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
664 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
665 WHERE rev_page = $pageId
666 AND rev_user != $user
667 GROUP BY rev_user, rev_user_text, user_real_name
668 ORDER BY timestamp DESC";
670 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
671 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
673 $sql .= ' '. $this->getSelectOptions();
675 $res = $dbr->query($sql, __METHOD__
);
677 return new UserArrayFromResult( $res );
681 * This is the default action of the script: just view the page of
685 global $wgUser, $wgOut, $wgRequest, $wgContLang;
686 global $wgEnableParserCache, $wgStylePath, $wgParser;
687 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
688 global $wgDefaultRobotPolicy;
689 $sk = $wgUser->getSkin();
691 wfProfileIn( __METHOD__
);
693 $parserCache = ParserCache
::singleton();
694 $ns = $this->mTitle
->getNamespace(); # shortcut
696 # Get variables from query string
697 $oldid = $this->getOldID();
699 # getOldID may want us to redirect somewhere else
700 if ( $this->mRedirectUrl
) {
701 $wgOut->redirect( $this->mRedirectUrl
);
702 wfProfileOut( __METHOD__
);
706 $diff = $wgRequest->getVal( 'diff' );
707 $rcid = $wgRequest->getVal( 'rcid' );
708 $rdfrom = $wgRequest->getVal( 'rdfrom' );
709 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
710 $purge = $wgRequest->getVal( 'action' ) == 'purge';
712 $wgOut->setArticleFlag( true );
714 # Discourage indexing of printable versions, but encourage following
715 if( $wgOut->isPrintable() ) {
716 $policy = 'noindex,follow';
717 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
718 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
719 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
720 # Honour customised robot policies for this namespace
721 $policy = $wgNamespaceRobotPolicies[$ns];
723 $policy = $wgDefaultRobotPolicy;
725 $wgOut->setRobotPolicy( $policy );
727 # If we got diff and oldid in the query, we want to see a
728 # diff page instead of the article.
730 if ( !is_null( $diff ) ) {
731 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
733 $diff = $wgRequest->getVal( 'diff' );
734 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
735 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
736 // DifferenceEngine directly fetched the revision:
737 $this->mRevIdFetched
= $de->mNewid
;
738 $de->showDiffPage( $diffOnly );
740 // Needed to get the page's current revision
741 $this->loadPageData();
742 if( $diff == 0 ||
$diff == $this->mLatest
) {
743 # Run view updates for current revision only
744 $this->viewUpdates();
746 wfProfileOut( __METHOD__
);
750 if ( empty( $oldid ) && $this->checkTouched() ) {
751 $wgOut->setETag($parserCache->getETag($this, $wgUser));
753 if( $wgOut->checkLastModified( $this->mTouched
) ){
754 wfProfileOut( __METHOD__
);
756 } else if ( $this->tryFileCache() ) {
757 # tell wgOut that output is taken care of
759 $this->viewUpdates();
760 wfProfileOut( __METHOD__
);
765 # Should the parser cache be used?
766 $pcache = $this->useParserCache( $oldid );
767 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
768 if ( $wgUser->getOption( 'stubthreshold' ) ) {
769 wfIncrStats( 'pcache_miss_stub' );
772 $wasRedirected = false;
773 if ( isset( $this->mRedirectedFrom
) ) {
774 // This is an internally redirected page view.
775 // We'll need a backlink to the source page for navigation.
776 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
777 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
778 $s = wfMsg( 'redirectedfrom', $redir );
779 $wgOut->setSubtitle( $s );
781 // Set the fragment if one was specified in the redirect
782 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
783 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
784 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
786 $wasRedirected = true;
788 } elseif ( !empty( $rdfrom ) ) {
789 // This is an externally redirected view, from some other wiki.
790 // If it was reported from a trusted site, supply a backlink.
791 global $wgRedirectSources;
792 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
793 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
794 $s = wfMsg( 'redirectedfrom', $redir );
795 $wgOut->setSubtitle( $s );
796 $wasRedirected = true;
801 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
803 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
804 // Ensure that UI elements requiring revision ID have
805 // the correct version information.
806 $wgOut->setRevisionId( $this->mLatest
);
810 # Fetch content and check for errors
811 if ( !$outputDone ) {
812 # If the article does not exist and was deleted, show the log
813 if ($this->getID() == 0) {
814 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
815 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
816 if( $pager->getNumRows() > 0 ) {
817 $wgOut->addHtml( '<div id="mw-deleted-notice">' );
818 $wgOut->addWikiMsg( 'deleted-notice' );
820 $loglist->beginLogEventsList() .
822 $loglist->endLogEventsList()
824 $wgOut->addHtml( '</div>' );
827 $text = $this->getContent();
828 if ( $text === false ) {
829 # Failed to load, replace text with error message
830 $t = $this->mTitle
->getPrefixedText();
832 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
833 $text = wfMsg( 'missing-article', $t, $d );
835 $text = wfMsg( 'noarticletext' );
839 # Another whitelist check in case oldid is altering the title
840 if ( !$this->mTitle
->userCanRead() ) {
841 $wgOut->loginToUse();
843 wfProfileOut( __METHOD__
);
847 # We're looking at an old revision
848 if ( !empty( $oldid ) ) {
849 $wgOut->setRobotPolicy( 'noindex,nofollow' );
850 if( is_null( $this->mRevision
) ) {
851 // FIXME: This would be a nice place to load the 'no such page' text.
853 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
854 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
855 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
856 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
857 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
858 wfProfileOut( __METHOD__
);
861 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
862 // and we are allowed to see...
868 $wgOut->setRevisionId( $this->getRevIdFetched() );
870 // Pages containing custom CSS or JavaScript get special treatment
871 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
872 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
873 // Give hooks a chance to customise the output
874 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
875 // Wrap the whole lot in a <pre> and don't parse
877 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
878 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
879 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
880 $wgOut->addHtml( "\n</pre>\n" );
882 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
883 # Don't append the subtitle if this was an old revision
884 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
885 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
886 $wgOut->addParserOutputNoText( $parseout );
887 } else if ( $pcache ) {
888 # Display content and save to parser cache
889 $this->outputWikiText( $text );
891 # Display content, don't attempt to save to parser cache
892 # Don't show section-edit links on old revisions... this way lies madness.
893 if( !$this->isCurrent() ) {
894 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
896 # Display content and don't save to parser cache
897 # With timing hack -- TS 2006-07-26
899 $this->outputWikiText( $text, false );
904 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
905 $this->mTitle
->getPrefixedDBkey()));
908 if( !$this->isCurrent() ) {
909 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
913 /* title may have been set from the cache */
914 $t = $wgOut->getPageTitle();
916 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
918 # For the main page, overwrite the <title> element with the con-
919 # tents of 'pagetitle-view-mainpage' instead of the default (if
921 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
922 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
923 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
927 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
928 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
929 $wgOut->addWikiMsg('anontalkpagetext');
932 # If we have been passed an &rcid= parameter, we want to give the user a
933 # chance to mark this new article as patrolled.
934 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
936 "<div class='patrollink'>" .
937 wfMsgHtml( 'markaspatrolledlink',
938 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
939 "action=markpatrolled&rcid=$rcid" )
946 if ($wgUseTrackbacks)
947 $this->addTrackbacks();
949 $this->viewUpdates();
950 wfProfileOut( __METHOD__
);
954 * Should the parser cache be used?
956 protected function useParserCache( $oldid ) {
957 global $wgUser, $wgEnableParserCache;
959 return $wgEnableParserCache
960 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
963 && !$this->mTitle
->isCssOrJsPage()
964 && !$this->mTitle
->isCssJsSubpage();
969 * @param Title $target Title of destination to redirect
970 * @param Bool $appendSubtitle Object[optional]
971 * @param Bool $forceKnown Should the image be shown as a bluelink regardless of existence?
973 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
974 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
977 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
978 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
980 if( $appendSubtitle ) {
981 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
983 $sk = $wgUser->getSkin();
985 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
987 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
989 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
990 '<span class="redirectText">'.$link.'</span>';
994 function addTrackbacks() {
995 global $wgOut, $wgUser;
997 $dbr = wfGetDB(DB_SLAVE
);
999 /* FROM */ 'trackbacks',
1000 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1001 /* WHERE */ array('tb_page' => $this->getID())
1004 if (!$dbr->numrows($tbs))
1008 while ($o = $dbr->fetchObject($tbs)) {
1010 if ($wgUser->isAllowed( 'trackback' )) {
1011 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
1012 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1013 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1016 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1023 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1026 function deletetrackback() {
1027 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1029 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
1030 $wgOut->addWikiMsg( 'sessionfailure' );
1034 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1036 if (count($permission_errors)>0)
1038 $wgOut->showPermissionsErrorPage( $permission_errors );
1042 $db = wfGetDB(DB_MASTER
);
1043 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1044 $wgTitle->invalidateCache();
1045 $wgOut->addWikiMsg('trackbackdeleteok');
1051 $wgOut->setArticleBodyOnly(true);
1056 * Handle action=purge
1059 global $wgUser, $wgRequest, $wgOut;
1061 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1062 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1067 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1068 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1069 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1070 $msg = str_replace( '$1',
1071 "<form method=\"post\" action=\"$action\">\n" .
1072 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1073 "</form>\n", $msg );
1075 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1076 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1077 $wgOut->addHTML( $msg );
1082 * Perform the actions of a page purging
1084 function doPurge() {
1086 // Invalidate the cache
1087 $this->mTitle
->invalidateCache();
1089 if ( $wgUseSquid ) {
1090 // Commit the transaction before the purge is sent
1091 $dbw = wfGetDB( DB_MASTER
);
1092 $dbw->immediateCommit();
1095 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1096 $update->doUpdate();
1098 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1099 global $wgMessageCache;
1100 if ( $this->getID() == 0 ) {
1103 $text = $this->getContent();
1105 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1110 * Insert a new empty page record for this article.
1111 * This *must* be followed up by creating a revision
1112 * and running $this->updateToLatest( $rev_id );
1113 * or else the record will be left in a funky state.
1114 * Best if all done inside a transaction.
1116 * @param Database $dbw
1117 * @return int The newly created page_id key
1120 function insertOn( $dbw ) {
1121 wfProfileIn( __METHOD__
);
1123 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1124 $dbw->insert( 'page', array(
1125 'page_id' => $page_id,
1126 'page_namespace' => $this->mTitle
->getNamespace(),
1127 'page_title' => $this->mTitle
->getDBkey(),
1128 'page_counter' => 0,
1129 'page_restrictions' => '',
1130 'page_is_redirect' => 0, # Will set this shortly...
1132 'page_random' => wfRandom(),
1133 'page_touched' => $dbw->timestamp(),
1134 'page_latest' => 0, # Fill this in shortly...
1135 'page_len' => 0, # Fill this in shortly...
1137 $newid = $dbw->insertId();
1139 $this->mTitle
->resetArticleId( $newid );
1141 wfProfileOut( __METHOD__
);
1146 * Update the page record to point to a newly saved revision.
1148 * @param Database $dbw
1149 * @param Revision $revision For ID number, and text used to set
1150 length and redirect status fields
1151 * @param int $lastRevision If given, will not overwrite the page field
1152 * when different from the currently set value.
1153 * Giving 0 indicates the new page flag should
1155 * @param bool $lastRevIsRedirect If given, will optimize adding and
1156 * removing rows in redirect table.
1157 * @return bool true on success, false on failure
1160 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1161 wfProfileIn( __METHOD__
);
1163 $text = $revision->getText();
1164 $rt = Title
::newFromRedirect( $text );
1166 $conditions = array( 'page_id' => $this->getId() );
1167 if( !is_null( $lastRevision ) ) {
1168 # An extra check against threads stepping on each other
1169 $conditions['page_latest'] = $lastRevision;
1172 $dbw->update( 'page',
1174 'page_latest' => $revision->getId(),
1175 'page_touched' => $dbw->timestamp(),
1176 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1177 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1178 'page_len' => strlen( $text ),
1183 $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 Database $dbw
1197 * @param $redirectTitle a title object pointing to the redirect target,
1198 * or NULL if this is not a redirect
1199 * @param bool $lastRevIsRedirect If given, will optimize adding and
1200 * removing rows in redirect table.
1201 * @return bool true on success, false on failure
1204 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1206 // Always update redirects (target link might have changed)
1207 // Update/Insert if we don't know if the last revision was a redirect or not
1208 // Delete if changing from redirect to non-redirect
1209 $isRedirect = !is_null($redirectTitle);
1210 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1212 wfProfileIn( __METHOD__
);
1216 // This title is a redirect, Add/Update row in the redirect table
1217 $set = array( /* SET */
1218 'rd_namespace' => $redirectTitle->getNamespace(),
1219 'rd_title' => $redirectTitle->getDBkey(),
1220 'rd_from' => $this->getId(),
1223 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1225 // This is not a redirect, remove row from redirect table
1226 $where = array( 'rd_from' => $this->getId() );
1227 $dbw->delete( 'redirect', $where, __METHOD__
);
1230 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1231 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1232 wfProfileOut( __METHOD__
);
1233 return ( $dbw->affectedRows() != 0 );
1240 * If the given revision is newer than the currently set page_latest,
1241 * update the page record. Otherwise, do nothing.
1243 * @param Database $dbw
1244 * @param Revision $revision
1246 function updateIfNewerOn( &$dbw, $revision ) {
1247 wfProfileIn( __METHOD__
);
1249 $row = $dbw->selectRow(
1250 array( 'revision', 'page' ),
1251 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1253 'page_id' => $this->getId(),
1254 'page_latest=rev_id' ),
1257 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1258 wfProfileOut( __METHOD__
);
1261 $prev = $row->rev_id
;
1262 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1264 # No or missing previous revision; mark the page as new
1266 $lastRevIsRedirect = null;
1269 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1270 wfProfileOut( __METHOD__
);
1275 * @return string Complete article text, or null if error
1277 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1278 wfProfileIn( __METHOD__
);
1280 if( $section == '' ) {
1281 // Whole-page edit; let the text through unmolested.
1283 if( is_null( $edittime ) ) {
1284 $rev = Revision
::newFromTitle( $this->mTitle
);
1286 $dbw = wfGetDB( DB_MASTER
);
1287 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1289 if( is_null( $rev ) ) {
1290 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1291 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1294 $oldtext = $rev->getText();
1296 if( $section == 'new' ) {
1297 # Inserting a new section
1298 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1299 $text = strlen( trim( $oldtext ) ) > 0
1300 ?
"{$oldtext}\n\n{$subject}{$text}"
1301 : "{$subject}{$text}";
1303 # Replacing an existing section; roll out the big guns
1305 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1310 wfProfileOut( __METHOD__
);
1315 * @deprecated use Article::doEdit()
1317 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1318 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1319 ( $isminor ? EDIT_MINOR
: 0 ) |
1320 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1321 ( $bot ? EDIT_FORCE_BOT
: 0 );
1323 # If this is a comment, add the summary as headline
1324 if ( $comment && $summary != "" ) {
1325 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1328 $this->doEdit( $text, $summary, $flags );
1330 $dbw = wfGetDB( DB_MASTER
);
1332 if (!$this->mTitle
->userIsWatching()) {
1338 if ( $this->mTitle
->userIsWatching() ) {
1344 $this->doRedirect( $this->isRedirect( $text ) );
1348 * @deprecated use Article::doEdit()
1350 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1351 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1352 ( $minor ? EDIT_MINOR
: 0 ) |
1353 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1355 $good = $this->doEdit( $text, $summary, $flags );
1357 $dbw = wfGetDB( DB_MASTER
);
1359 if (!$this->mTitle
->userIsWatching()) {
1365 if ( $this->mTitle
->userIsWatching() ) {
1372 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1373 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1375 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1383 * Change an existing article or create a new article. Updates RC and all necessary caches,
1384 * optionally via the deferred update array.
1386 * $wgUser must be set before calling this function.
1388 * @param string $text New text
1389 * @param string $summary Edit summary
1390 * @param integer $flags bitfield:
1392 * Article is known or assumed to be non-existent, create a new one
1394 * Article is known or assumed to be pre-existing, update it
1396 * Mark this edit minor, if the user is allowed to do so
1398 * Do not log the change in recentchanges
1400 * Mark the edit a "bot" edit regardless of user rights
1401 * EDIT_DEFER_UPDATES
1402 * Defer some of the updates until the end of index.php
1404 * Fill in blank summaries with generated text where possible
1406 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1407 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1408 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1409 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1410 * to MediaWiki's performance-optimised locking strategy.
1411 * @param $baseRevId, the revision ID this edit was based off, if any
1413 * @return bool success
1415 function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1416 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1418 if ($user == null) {
1422 wfProfileIn( __METHOD__
);
1425 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1426 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1428 $flags |
= EDIT_UPDATE
;
1434 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text,
1435 &$summary, $flags & EDIT_MINOR
,
1436 null, null, &$flags ) ) )
1438 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1439 wfProfileOut( __METHOD__
);
1443 # Silently ignore EDIT_MINOR if not allowed
1444 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1445 $bot = $flags & EDIT_FORCE_BOT
;
1447 $oldtext = $this->getContent();
1448 $oldsize = strlen( $oldtext );
1450 # Provide autosummaries if one is not provided and autosummaries are enabled.
1451 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1452 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1455 $editInfo = $this->prepareTextForEdit( $text );
1456 $text = $editInfo->pst
;
1457 $newsize = strlen( $text );
1459 $dbw = wfGetDB( DB_MASTER
);
1460 $now = wfTimestampNow();
1462 if ( $flags & EDIT_UPDATE
) {
1463 # Update article, but only if changed.
1465 # Make sure the revision is either completely inserted or not inserted at all
1466 if( !$wgDBtransactions ) {
1467 $userAbort = ignore_user_abort( true );
1475 $changed = ( strcmp( $text, $oldtext ) != 0 );
1477 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1478 - (int)$this->isCountable( $oldtext );
1479 $this->mTotalAdjustment
= 0;
1481 $lastRevision = $dbw->selectField(
1482 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1484 if ( !$lastRevision ) {
1485 # Article gone missing
1486 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1487 wfProfileOut( __METHOD__
);
1491 $revision = new Revision( array(
1492 'page' => $this->getId(),
1493 'comment' => $summary,
1494 'minor_edit' => $isminor,
1496 'parent_id' => $lastRevision,
1497 'user' => $user->getId(),
1498 'user_text' => $user->getName(),
1501 $revisionId = $revision->insertOn( $dbw );
1504 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1507 /* Belated edit conflict! Run away!! */
1511 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1513 # Update recentchanges
1514 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1515 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1516 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1519 # Mark as patrolled if the user can do so
1520 if( $GLOBALS['wgUseRCPatrol'] && $user->isAllowed( 'autopatrol' ) ) {
1521 RecentChange
::markPatrolled( $rc, true );
1524 $user->incEditCount();
1528 // Keep the same revision ID, but do some updates on it
1529 $revisionId = $this->getRevIdFetched();
1530 // Update page_touched, this is usually implicit in the page update
1531 // Other cache updates are done in onArticleEdit()
1532 $this->mTitle
->invalidateCache();
1535 if( !$wgDBtransactions ) {
1536 ignore_user_abort( $userAbort );
1540 # Invalidate cache of this article and all pages using this article
1541 # as a template. Partly deferred.
1542 Article
::onArticleEdit( $this->mTitle
);
1544 # Update links tables, site stats, etc.
1545 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1549 # Create new article
1551 # Set statistics members
1552 # We work out if it's countable after PST to avoid counter drift
1553 # when articles are created with {{subst:}}
1554 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1555 $this->mTotalAdjustment
= 1;
1559 # Add the page record; stake our claim on this title!
1560 # This will fail with a database query exception if the article already exists
1561 $newid = $this->insertOn( $dbw );
1563 # Save the revision text...
1564 $revision = new Revision( array(
1566 'comment' => $summary,
1567 'minor_edit' => $isminor,
1569 'user' => $user->getId(),
1570 'user_text' => $user->getName(),
1572 $revisionId = $revision->insertOn( $dbw );
1574 $this->mTitle
->resetArticleID( $newid );
1576 # Update the page record with revision data
1577 $this->updateRevisionOn( $dbw, $revision, 0 );
1579 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1581 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1582 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1583 '', strlen( $text ), $revisionId );
1584 # Mark as patrolled if the user can
1585 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $user->isAllowed( 'autopatrol' ) ) {
1586 RecentChange
::markPatrolled( $rc, true );
1589 $user->incEditCount();
1592 # Update links, etc.
1593 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1596 Article
::onArticleCreate( $this->mTitle
);
1598 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1599 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1602 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1607 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1608 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1611 wfProfileOut( __METHOD__
);
1616 * @deprecated wrapper for doRedirect
1618 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1619 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1623 * Output a redirect back to the article.
1624 * This is typically used after an edit.
1626 * @param boolean $noRedir Add redirect=no
1627 * @param string $sectionAnchor section to redirect to, including "#"
1628 * @param string $extraQuery, extra query params
1630 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1633 $query = 'redirect=no';
1635 $query .= "&$query";
1637 $query = $extraQuery;
1639 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1643 * Mark this particular edit/page as patrolled
1645 function markpatrolled() {
1646 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1647 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1649 # If we haven't been given an rc_id value, we can't do anything
1650 $rcid = (int) $wgRequest->getVal('rcid');
1651 $rc = RecentChange
::newFromId($rcid);
1652 if ( is_null($rc) ) {
1653 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1657 #It would be nice to see where the user had actually come from, but for now just guess
1658 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1659 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1661 $dbw = wfGetDB( DB_MASTER
);
1663 $errors = $rc->doMarkPatrolled();
1666 if ( in_array(array('rcpatroldisabled'), $errors) ) {
1667 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1671 if ( in_array(array('hookaborted'), $errors) ) {
1672 // The hook itself has handled any output
1676 if ( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1677 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1678 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1679 $wgOut->returnToMain( false, $return );
1683 if ( !empty($errors) ) {
1684 $wgOut->showPermissionsErrorPage( $errors );
1689 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1690 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1691 $wgOut->returnToMain( false, $return );
1695 * User-interface handler for the "watch" action
1700 global $wgUser, $wgOut;
1702 if ( $wgUser->isAnon() ) {
1703 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1706 if ( wfReadOnly() ) {
1707 $wgOut->readOnlyPage();
1711 if( $this->doWatch() ) {
1712 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1713 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1715 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1718 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1722 * Add this page to $wgUser's watchlist
1723 * @return bool true on successful watch operation
1725 function doWatch() {
1727 if( $wgUser->isAnon() ) {
1731 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1732 $wgUser->addWatch( $this->mTitle
);
1734 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1741 * User interface handler for the "unwatch" action.
1743 function unwatch() {
1745 global $wgUser, $wgOut;
1747 if ( $wgUser->isAnon() ) {
1748 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1751 if ( wfReadOnly() ) {
1752 $wgOut->readOnlyPage();
1756 if( $this->doUnwatch() ) {
1757 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1758 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1760 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1763 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1767 * Stop watching a page
1768 * @return bool true on successful unwatch
1770 function doUnwatch() {
1772 if( $wgUser->isAnon() ) {
1776 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1777 $wgUser->removeWatch( $this->mTitle
);
1779 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1786 * action=protect handler
1788 function protect() {
1789 $form = new ProtectionForm( $this );
1794 * action=unprotect handler (alias)
1796 function unprotect() {
1801 * Update the article's restriction field, and leave a log entry.
1803 * @param array $limit set of restriction keys
1804 * @param string $reason
1805 * @return bool true on success
1807 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = array() ) {
1808 global $wgUser, $wgRestrictionTypes, $wgContLang;
1810 $id = $this->mTitle
->getArticleID();
1811 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1819 // Take this opportunity to purge out expired restrictions
1820 Title
::purgeExpiredRestrictions();
1822 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1823 # we expect a single selection, but the schema allows otherwise.
1825 $updated = Article
::flattenRestrictions( $limit );
1827 foreach( $wgRestrictionTypes as $action ) {
1828 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1829 $changed = ($changed ||
($this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action]) );
1832 $current = Article
::flattenRestrictions( $current );
1834 $changed = ($changed ||
( $current != $updated ) );
1835 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1836 $protect = ( $updated != '' );
1838 # If nothing's changed, do nothing
1840 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1842 $dbw = wfGetDB( DB_MASTER
);
1844 # Prepare a null revision to be added to the history
1845 $modified = $current != '' && $protect;
1847 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1849 $comment_type = 'unprotectedarticle';
1851 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1853 # Only restrictions with the 'protect' right can cascade...
1854 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1855 foreach( $limit as $action => $restriction ) {
1856 # FIXME: can $restriction be an array or what? (same as fixme above)
1857 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1862 $cascade_description = '';
1864 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1868 $comment .= ": $reason";
1870 $editComment = $comment;
1871 $encodedExpiry = array();
1872 $protect_description = '';
1873 foreach( $limit as $action => $restrictions ) {
1874 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
1875 if ($restrictions != '') {
1876 $protect_description .= "[$action=$restrictions] (";
1877 if( $encodedExpiry[$action] != 'infinity' ) {
1878 $protect_description .= wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry[$action], false, false ) );
1880 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1882 $protect_description .= ') ';
1886 if( $protect_description && $protect )
1887 $editComment .= " ($protect_description)";
1889 $editComment .= "$cascade_description";
1890 # Update restrictions table
1891 foreach( $limit as $action => $restrictions ) {
1892 if ($restrictions != '' ) {
1893 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1894 array( 'pr_page' => $id,
1895 'pr_type' => $action,
1896 'pr_level' => $restrictions,
1897 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
1898 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
1900 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1901 'pr_type' => $action ), __METHOD__
);
1905 # Insert a null revision
1906 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1907 $nullRevId = $nullRevision->insertOn( $dbw );
1909 $latest = $this->getLatest();
1910 # Update page record
1911 $dbw->update( 'page',
1913 'page_touched' => $dbw->timestamp(),
1914 'page_restrictions' => '',
1915 'page_latest' => $nullRevId
1916 ), array( /* WHERE */
1918 ), 'Article::protect'
1921 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest) );
1922 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1924 # Update the protection log
1925 $log = new LogPage( 'protect' );
1927 $params = array($protect_description,$cascade ?
'cascade' : '');
1928 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
1930 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1934 } # End "changed" check
1940 * Take an array of page restrictions and flatten it to a string
1941 * suitable for insertion into the page_restrictions field.
1942 * @param array $limit
1946 function flattenRestrictions( $limit ) {
1947 if( !is_array( $limit ) ) {
1948 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1952 foreach( $limit as $action => $restrictions ) {
1953 if( $restrictions != '' ) {
1954 $bits[] = "$action=$restrictions";
1957 return implode( ':', $bits );
1961 * Auto-generates a deletion reason
1962 * @param bool &$hasHistory Whether the page has a history
1964 public function generateReason(&$hasHistory)
1967 $dbw = wfGetDB(DB_MASTER
);
1968 // Get the last revision
1969 $rev = Revision
::newFromTitle($this->mTitle
);
1972 // Get the article's contents
1973 $contents = $rev->getText();
1975 // If the page is blank, use the text from the previous revision,
1976 // which can only be blank if there's a move/import/protect dummy revision involved
1979 $prev = $rev->getPrevious();
1982 $contents = $prev->getText();
1987 // Find out if there was only one contributor
1988 // Only scan the last 20 revisions
1990 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1991 array('LIMIT' => $limit));
1993 // This page has no revisions, which is very weird
1995 if($res->numRows() > 1)
1998 $hasHistory = false;
1999 $row = $dbw->fetchObject($res);
2000 $onlyAuthor = $row->rev_user_text
;
2001 // Try to find a second contributor
2002 foreach( $res as $row ) {
2003 if($row->rev_user_text
!= $onlyAuthor) {
2004 $onlyAuthor = false;
2008 $dbw->freeResult($res);
2010 // Generate the summary with a '$1' placeholder
2012 // The current revision is blank and the one before is also
2013 // blank. It's just not our lucky day
2014 $reason = wfMsgForContent('exbeforeblank', '$1');
2017 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
2019 $reason = wfMsgForContent('excontent', '$1');
2022 // Replace newlines with spaces to prevent uglyness
2023 $contents = preg_replace("/[\n\r]/", ' ', $contents);
2024 // Calculate the maximum amount of chars to get
2025 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2026 $maxLength = 255 - (strlen($reason) - 2) - 3;
2027 $contents = $wgContLang->truncate($contents, $maxLength, '...');
2028 // Remove possible unfinished links
2029 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2030 // Now replace the '$1' placeholder
2031 $reason = str_replace( '$1', $contents, $reason );
2037 * UI entry point for page deletion
2040 global $wgUser, $wgOut, $wgRequest;
2042 $confirm = $wgRequest->wasPosted() &&
2043 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2045 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2046 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2048 $reason = $this->DeleteReasonList
;
2050 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2051 // Entry from drop down menu + additional comment
2052 $reason .= ': ' . $this->DeleteReason
;
2053 } elseif ( $reason == 'other' ) {
2054 $reason = $this->DeleteReason
;
2056 # Flag to hide all contents of the archived revisions
2057 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2059 # This code desperately needs to be totally rewritten
2061 # Read-only check...
2062 if ( wfReadOnly() ) {
2063 $wgOut->readOnlyPage();
2068 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2070 if (count($permission_errors)>0) {
2071 $wgOut->showPermissionsErrorPage( $permission_errors );
2075 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2077 # Better double-check that it hasn't been deleted yet!
2078 $dbw = wfGetDB( DB_MASTER
);
2079 $conds = $this->mTitle
->pageCond();
2080 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2081 if ( $latest === false ) {
2082 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2086 # Hack for big sites
2087 $bigHistory = $this->isBigDeletion();
2088 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2089 global $wgLang, $wgDeleteRevisionsLimit;
2090 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2091 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2096 $this->doDelete( $reason, $suppress );
2097 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2099 } elseif( $this->mTitle
->userIsWatching() ) {
2105 // Generate deletion reason
2106 $hasHistory = false;
2107 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2109 // If the page has a history, insert a warning
2110 if( $hasHistory && !$confirm ) {
2111 $skin=$wgUser->getSkin();
2112 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2114 global $wgLang, $wgDeleteRevisionsLimit;
2115 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2116 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2120 return $this->confirmDelete( $reason );
2124 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2126 function isBigDeletion() {
2127 global $wgDeleteRevisionsLimit;
2128 if( $wgDeleteRevisionsLimit ) {
2129 $revCount = $this->estimateRevisionCount();
2130 return $revCount > $wgDeleteRevisionsLimit;
2136 * @return int approximate revision count
2138 function estimateRevisionCount() {
2140 // For an exact count...
2141 //return $dbr->selectField( 'revision', 'COUNT(*)',
2142 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2143 return $dbr->estimateRowCount( 'revision', '*',
2144 array( 'rev_page' => $this->getId() ), __METHOD__
);
2148 * Get the last N authors
2149 * @param int $num Number of revisions to get
2150 * @param string $revLatest The latest rev_id, selected from the master (optional)
2151 * @return array Array of authors, duplicates not removed
2153 function getLastNAuthors( $num, $revLatest = 0 ) {
2154 wfProfileIn( __METHOD__
);
2156 // First try the slave
2157 // If that doesn't have the latest revision, try the master
2159 $db = wfGetDB( DB_SLAVE
);
2161 $res = $db->select( array( 'page', 'revision' ),
2162 array( 'rev_id', 'rev_user_text' ),
2164 'page_namespace' => $this->mTitle
->getNamespace(),
2165 'page_title' => $this->mTitle
->getDBkey(),
2166 'rev_page = page_id'
2167 ), __METHOD__
, $this->getSelectOptions( array(
2168 'ORDER BY' => 'rev_timestamp DESC',
2173 wfProfileOut( __METHOD__
);
2176 $row = $db->fetchObject( $res );
2177 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2178 $db = wfGetDB( DB_MASTER
);
2183 } while ( $continue );
2185 $authors = array( $row->rev_user_text
);
2186 while ( $row = $db->fetchObject( $res ) ) {
2187 $authors[] = $row->rev_user_text
;
2189 wfProfileOut( __METHOD__
);
2194 * Output deletion confirmation dialog
2195 * @param $reason string Prefilled reason
2197 function confirmDelete( $reason ) {
2198 global $wgOut, $wgUser, $wgContLang;
2199 $align = $wgContLang->isRtl() ?
'left' : 'right';
2201 wfDebug( "Article::confirmDelete\n" );
2203 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2204 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2205 $wgOut->addWikiMsg( 'confirmdeletetext' );
2207 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2208 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2209 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2210 $suppress .= "</td></tr>";
2215 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2216 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2217 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2218 Xml
::openElement( 'table' ) .
2219 "<tr id=\"wpDeleteReasonListRow\">
2220 <td align='$align'>" .
2221 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2224 Xml
::listDropDown( 'wpDeleteReasonList',
2225 wfMsgForContent( 'deletereason-dropdown' ),
2226 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2229 <tr id=\"wpDeleteReasonRow\">
2230 <td align='$align'>" .
2231 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2234 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2240 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2247 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2250 Xml
::closeElement( 'table' ) .
2251 Xml
::closeElement( 'fieldset' ) .
2252 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2253 Xml
::closeElement( 'form' );
2255 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2256 $skin = $wgUser->getSkin();
2257 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2258 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2261 $wgOut->addHTML( $form );
2262 $this->showLogExtract( $wgOut );
2267 * Show relevant lines from the deletion log
2269 function showLogExtract( $out ) {
2270 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2271 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2276 * Perform a deletion and output success or failure messages
2278 function doDelete( $reason, $suppress = false ) {
2279 global $wgOut, $wgUser;
2280 wfDebug( __METHOD__
."\n" );
2282 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2286 if ( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2287 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2288 $deleted = $this->mTitle
->getPrefixedText();
2290 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2291 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2293 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2295 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2296 $wgOut->returnToMain( false );
2297 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2300 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2302 $wgOut->showFatalError( $error );
2308 * Back-end article deletion
2309 * Deletes the article with database consistency, writes logs, purges caches
2312 function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2313 global $wgUseSquid, $wgDeferredUpdateList;
2314 global $wgUseTrackbacks;
2316 wfDebug( __METHOD__
."\n" );
2318 $dbw = wfGetDB( DB_MASTER
);
2319 $ns = $this->mTitle
->getNamespace();
2320 $t = $this->mTitle
->getDBkey();
2321 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2323 if ( $t == '' ||
$id == 0 ) {
2327 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2328 array_push( $wgDeferredUpdateList, $u );
2330 // Bitfields to further suppress the content
2333 // This should be 15...
2334 $bitfield |
= Revision
::DELETED_TEXT
;
2335 $bitfield |
= Revision
::DELETED_COMMENT
;
2336 $bitfield |
= Revision
::DELETED_USER
;
2337 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2339 $bitfield = 'rev_deleted';
2343 // For now, shunt the revision data into the archive table.
2344 // Text is *not* removed from the text table; bulk storage
2345 // is left intact to avoid breaking block-compression or
2346 // immutable storage schemes.
2348 // For backwards compatibility, note that some older archive
2349 // table entries will have ar_text and ar_flags fields still.
2351 // In the future, we may keep revisions and mark them with
2352 // the rev_deleted field, which is reserved for this purpose.
2353 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2355 'ar_namespace' => 'page_namespace',
2356 'ar_title' => 'page_title',
2357 'ar_comment' => 'rev_comment',
2358 'ar_user' => 'rev_user',
2359 'ar_user_text' => 'rev_user_text',
2360 'ar_timestamp' => 'rev_timestamp',
2361 'ar_minor_edit' => 'rev_minor_edit',
2362 'ar_rev_id' => 'rev_id',
2363 'ar_text_id' => 'rev_text_id',
2364 'ar_text' => '\'\'', // Be explicit to appease
2365 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2366 'ar_len' => 'rev_len',
2367 'ar_page_id' => 'page_id',
2368 'ar_deleted' => $bitfield
2371 'page_id = rev_page'
2375 # Delete restrictions for it
2376 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2378 # Now that it's safely backed up, delete it
2379 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2380 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2386 # If using cascading deletes, we can skip some explicit deletes
2387 if ( !$dbw->cascadingDeletes() ) {
2388 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2390 if ($wgUseTrackbacks)
2391 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2393 # Delete outgoing links
2394 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2395 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2396 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2397 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2398 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2399 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2400 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2403 # If using cleanup triggers, we can skip some manual deletes
2404 if ( !$dbw->cleanupTriggers() ) {
2405 # Clean up recentchanges entries...
2406 $dbw->delete( 'recentchanges',
2407 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2412 Article
::onArticleDelete( $this->mTitle
);
2414 # Fix category table counts
2416 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2417 foreach( $res as $row ) {
2418 $cats []= $row->cl_to
;
2420 $this->updateCategoryCounts( array(), $cats );
2422 # Clear the cached article id so the interface doesn't act like we exist
2423 $this->mTitle
->resetArticleID( 0 );
2424 $this->mTitle
->mArticleID
= 0;
2426 # Log the deletion, if the page was suppressed, log it at Oversight instead
2427 $logtype = $suppress ?
'suppress' : 'delete';
2428 $log = new LogPage( $logtype );
2430 # Make sure logging got through
2431 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2439 * Roll back the most recent consecutive set of edits to a page
2440 * from the same user; fails if there are no eligible edits to
2441 * roll back to, e.g. user is the sole contributor. This function
2442 * performs permissions checks on $wgUser, then calls commitRollback()
2443 * to do the dirty work
2445 * @param string $fromP - Name of the user whose edits to rollback.
2446 * @param string $summary - Custom summary. Set to default summary if empty.
2447 * @param string $token - Rollback token.
2448 * @param bool $bot - If true, mark all reverted edits as bot.
2450 * @param array $resultDetails contains result-specific array of additional values
2451 * 'alreadyrolled' : 'current' (rev)
2452 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2454 * @return array of errors, each error formatted as
2455 * array(messagekey, param1, param2, ...).
2456 * On success, the array is empty. This array can also be passed to
2457 * OutputPage::showPermissionsErrorPage().
2459 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2461 $resultDetails = null;
2464 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2465 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2466 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2467 $errors[] = array( 'sessionfailure' );
2469 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2470 $errors[] = array( 'actionthrottledtext' );
2472 # If there were errors, bail out now
2476 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2480 * Backend implementation of doRollback(), please refer there for parameter
2481 * and return value documentation
2483 * NOTE: This function does NOT check ANY permissions, it just commits the
2484 * rollback to the DB Therefore, you should only call this function direct-
2485 * ly if you want to use custom permissions checks. If you don't, use
2486 * doRollback() instead.
2488 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2489 global $wgUseRCPatrol, $wgUser, $wgLang;
2490 $dbw = wfGetDB( DB_MASTER
);
2492 if( wfReadOnly() ) {
2493 return array( array( 'readonlytext' ) );
2496 # Get the last editor
2497 $current = Revision
::newFromTitle( $this->mTitle
);
2498 if( is_null( $current ) ) {
2499 # Something wrong... no page?
2500 return array(array('notanarticle'));
2503 $from = str_replace( '_', ' ', $fromP );
2504 if( $from != $current->getUserText() ) {
2505 $resultDetails = array( 'current' => $current );
2506 return array(array('alreadyrolled',
2507 htmlspecialchars($this->mTitle
->getPrefixedText()),
2508 htmlspecialchars($fromP),
2509 htmlspecialchars($current->getUserText())
2513 # Get the last edit not by this guy
2514 $user = intval( $current->getUser() );
2515 $user_text = $dbw->addQuotes( $current->getUserText() );
2516 $s = $dbw->selectRow( 'revision',
2517 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2518 array( 'rev_page' => $current->getPage(),
2519 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2521 array( 'USE INDEX' => 'page_timestamp',
2522 'ORDER BY' => 'rev_timestamp DESC' )
2524 if( $s === false ) {
2525 # No one else ever edited this page
2526 return array(array('cantrollback'));
2527 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2528 # Only admins can see this text
2529 return array(array('notvisiblerev'));
2533 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2534 # Mark all reverted edits as bot
2537 if ( $wgUseRCPatrol ) {
2538 # Mark all reverted edits as patrolled
2539 $set['rc_patrolled'] = 1;
2543 $dbw->update( 'recentchanges', $set,
2545 'rc_cur_id' => $current->getPage(),
2546 'rc_user_text' => $current->getUserText(),
2547 "rc_timestamp > '{$s->rev_timestamp}'",
2552 # Generate the edit summary if necessary
2553 $target = Revision
::newFromId( $s->rev_id
);
2554 if( empty( $summary ) ){
2555 $summary = wfMsgForContent( 'revertpage' );
2558 # Allow the custom summary to use the same args as the default message
2560 $target->getUserText(), $from, $s->rev_id
,
2561 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2562 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2564 $summary = wfMsgReplaceArgs( $summary, $args );
2567 $flags = EDIT_UPDATE
;
2569 if ($wgUser->isAllowed('minoredit'))
2570 $flags |
= EDIT_MINOR
;
2572 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2573 $flags |
= EDIT_FORCE_BOT
;
2574 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2576 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2578 $resultDetails = array(
2579 'summary' => $summary,
2580 'current' => $current,
2581 'target' => $target,
2587 * User interface for rollback operations
2589 function rollback() {
2590 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2593 $result = $this->doRollback(
2594 $wgRequest->getVal( 'from' ),
2595 $wgRequest->getText( 'summary' ),
2596 $wgRequest->getVal( 'token' ),
2597 $wgRequest->getBool( 'bot' ),
2601 if( in_array( array( 'blocked' ), $result ) ) {
2602 $wgOut->blockedPage();
2605 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2606 $wgOut->rateLimited();
2609 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2610 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2611 $errArray = $result[0];
2612 $errMsg = array_shift( $errArray );
2613 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2614 if( isset( $details['current'] ) ){
2615 $current = $details['current'];
2616 if( $current->getComment() != '' ) {
2617 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2622 # Display permissions errors before read-only message -- there's no
2623 # point in misleading the user into thinking the inability to rollback
2624 # is only temporary.
2625 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2626 # array_diff is completely broken for arrays of arrays, sigh. Re-
2627 # move any 'readonlytext' error manually.
2629 foreach( $result as $error ) {
2630 if( $error != array( 'readonlytext' ) ) {
2634 $wgOut->showPermissionsErrorPage( $out );
2637 if( $result == array( array('readonlytext') ) ) {
2638 $wgOut->readOnlyPage();
2642 $current = $details['current'];
2643 $target = $details['target'];
2644 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2645 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2646 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2647 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2648 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2649 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2650 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2651 $wgOut->returnToMain( false, $this->mTitle
);
2653 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2654 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), 'next', false, true );
2655 $de->showDiff( '', '' );
2661 * Do standard deferred updates after page view
2664 function viewUpdates() {
2665 global $wgDeferredUpdateList, $wgUser;
2667 if ( 0 != $this->getID() ) {
2668 # Don't update page view counters on views from bot users (bug 14044)
2669 global $wgDisableCounters;
2670 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2671 Article
::incViewCount( $this->getID() );
2672 $u = new SiteStatsUpdate( 1, 0, 0 );
2673 array_push( $wgDeferredUpdateList, $u );
2677 # Update newtalk / watchlist notification status
2678 $wgUser->clearNotification( $this->mTitle
);
2682 * Prepare text which is about to be saved.
2683 * Returns a stdclass with source, pst and output members
2685 function prepareTextForEdit( $text, $revid=null ) {
2686 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2688 return $this->mPreparedEdit
;
2691 $edit = (object)array();
2692 $edit->revid
= $revid;
2693 $edit->newText
= $text;
2694 $edit->pst
= $this->preSaveTransform( $text );
2695 $options = new ParserOptions
;
2696 $options->setTidy( true );
2697 $options->enableLimitReport();
2698 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2699 $edit->oldText
= $this->getContent();
2700 $this->mPreparedEdit
= $edit;
2705 * Do standard deferred updates after page edit.
2706 * Update links tables, site stats, search index and message cache.
2707 * Every 100th edit, prune the recent changes table.
2710 * @param $text New text of the article
2711 * @param $summary Edit summary
2712 * @param $minoredit Minor edit
2713 * @param $timestamp_of_pagechange Timestamp associated with the page change
2714 * @param $newid rev_id value of the new revision
2715 * @param $changed Whether or not the content actually changed
2717 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2718 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2720 wfProfileIn( __METHOD__
);
2723 # Be careful not to double-PST: $text is usually already PST-ed once
2724 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2725 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2726 $editInfo = $this->prepareTextForEdit( $text, $newid );
2728 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2729 $editInfo = $this->mPreparedEdit
;
2732 # Save it to the parser cache
2733 if ( $wgEnableParserCache ) {
2734 $parserCache = ParserCache
::singleton();
2735 $parserCache->save( $editInfo->output
, $this, $wgUser );
2738 # Update the links tables
2739 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2742 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2743 if ( 0 == mt_rand( 0, 99 ) ) {
2744 // Flush old entries from the `recentchanges` table; we do this on
2745 // random requests so as to avoid an increase in writes for no good reason
2747 $dbw = wfGetDB( DB_MASTER
);
2748 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2749 $recentchanges = $dbw->tableName( 'recentchanges' );
2750 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2751 $dbw->query( $sql );
2755 $id = $this->getID();
2756 $title = $this->mTitle
->getPrefixedDBkey();
2757 $shortTitle = $this->mTitle
->getDBkey();
2760 wfProfileOut( __METHOD__
);
2764 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2765 array_push( $wgDeferredUpdateList, $u );
2766 $u = new SearchUpdate( $id, $title, $text );
2767 array_push( $wgDeferredUpdateList, $u );
2769 # If this is another user's talk page, update newtalk
2770 # Don't do this if $changed = false otherwise some idiot can null-edit a
2771 # load of user talk pages and piss people off, nor if it's a minor edit
2772 # by a properly-flagged bot.
2773 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2774 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2775 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2776 $other = User
::newFromName( $shortTitle, false );
2778 wfDebug( __METHOD__
.": invalid username\n" );
2779 } elseif( User
::isIP( $shortTitle ) ) {
2780 // An anonymous user
2781 $other->setNewtalk( true );
2782 } elseif( $other->isLoggedIn() ) {
2783 $other->setNewtalk( true );
2785 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2790 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2791 $wgMessageCache->replace( $shortTitle, $text );
2794 wfProfileOut( __METHOD__
);
2798 * Perform article updates on a special page creation.
2800 * @param Revision $rev
2802 * @todo This is a shitty interface function. Kill it and replace the
2803 * other shitty functions like editUpdates and such so it's not needed
2806 function createUpdates( $rev ) {
2807 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2808 $this->mTotalAdjustment
= 1;
2809 $this->editUpdates( $rev->getText(), $rev->getComment(),
2810 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2814 * Generate the navigation links when browsing through an article revisions
2815 * It shows the information as:
2816 * Revision as of \<date\>; view current revision
2817 * \<- Previous version | Next Version -\>
2820 * @param string $oldid Revision ID of this article revision
2822 function setOldSubtitle( $oldid=0 ) {
2823 global $wgLang, $wgOut, $wgUser;
2825 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2829 $revision = Revision
::newFromId( $oldid );
2831 $current = ( $oldid == $this->mLatest
);
2832 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2833 $sk = $wgUser->getSkin();
2835 ?
wfMsg( 'currentrevisionlink' )
2836 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2839 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2840 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2842 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2843 : wfMsg( 'previousrevision' );
2845 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2847 $nextlink = $current
2848 ?
wfMsg( 'nextrevision' )
2849 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2850 $nextdiff = $current
2852 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2855 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2856 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2857 if( $revision->isCurrent() ) {
2858 // We don't handle top deleted edits too well
2859 $cdel = wfMsgHtml('rev-delundel');
2860 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2861 // If revision was hidden from sysops
2862 $cdel = wfMsgHtml('rev-delundel');
2864 $cdel = $sk->makeKnownLinkObj( $revdel,
2865 wfMsgHtml('rev-delundel'),
2866 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2867 '&oldid=' . urlencode( $oldid ) );
2868 // Bolden oversighted content
2869 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2870 $cdel = "<strong>$cdel</strong>";
2872 $cdel = "(<small>$cdel</small>) ";
2874 # Show user links if allowed to see them. Normally they
2875 # are hidden regardless, but since we can already see the text here...
2876 $userlinks = $sk->revUserTools( $revision, false );
2878 $m = wfMsg( 'revision-info-current' );
2879 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2880 ?
'revision-info-current'
2883 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2885 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2886 $wgOut->setSubtitle( $r );
2890 * This function is called right before saving the wikitext,
2891 * so we can do things like signatures and links-in-context.
2893 * @param string $text
2895 function preSaveTransform( $text ) {
2896 global $wgParser, $wgUser;
2897 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2900 /* Caching functions */
2903 * checkLastModified returns true if it has taken care of all
2904 * output to the client that is necessary for this request.
2905 * (that is, it has sent a cached version of the page)
2907 function tryFileCache() {
2908 static $called = false;
2910 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2914 if($this->isFileCacheable()) {
2915 $touched = $this->mTouched
;
2916 $cache = new HTMLFileCache( $this->mTitle
);
2917 if($cache->isFileCacheGood( $touched )) {
2918 wfDebug( "Article::tryFileCache(): about to load file\n" );
2919 $cache->loadFromFileCache();
2922 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2923 ob_start( array(&$cache, 'saveToFileCache' ) );
2926 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2931 * Check if the page can be cached
2934 function isFileCacheable() {
2935 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2936 $action = $wgRequest->getVal( 'action' );
2937 $oldid = $wgRequest->getVal( 'oldid' );
2938 $diff = $wgRequest->getVal( 'diff' );
2939 $redirect = $wgRequest->getVal( 'redirect' );
2940 $printable = $wgRequest->getVal( 'printable' );
2941 $page = $wgRequest->getVal( 'page' );
2942 $useskin = $wgRequest->getVal( 'useskin' );
2944 //check for non-standard user language; this covers uselang,
2945 //and extensions for auto-detecting user language.
2946 $ulang = $wgLang->getCode();
2947 $clang = $wgContLang->getCode();
2949 $cacheable = $wgUseFileCache
2950 && (!$wgShowIPinHeader)
2951 && ($this->getID() != 0)
2952 && ($wgUser->isAnon())
2953 && (!$wgUser->getNewtalk())
2954 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2955 && (!isset($useskin))
2956 && (empty( $action ) ||
$action == 'view')
2959 && (!isset($redirect))
2960 && (!isset($printable))
2962 && (!$this->mRedirectedFrom
)
2963 && ($ulang === $clang);
2966 //extension may have reason to disable file caching on some pages.
2967 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
2974 * Loads page_touched and returns a value indicating if it should be used
2977 function checkTouched() {
2978 if( !$this->mDataLoaded
) {
2979 $this->loadPageData();
2981 return !$this->mIsRedirect
;
2985 * Get the page_touched field
2987 function getTouched() {
2988 # Ensure that page data has been loaded
2989 if( !$this->mDataLoaded
) {
2990 $this->loadPageData();
2992 return $this->mTouched
;
2996 * Get the page_latest field
2998 function getLatest() {
2999 if ( !$this->mDataLoaded
) {
3000 $this->loadPageData();
3002 return $this->mLatest
;
3006 * Edit an article without doing all that other stuff
3007 * The article must already exist; link tables etc
3008 * are not updated, caches are not flushed.
3010 * @param string $text text submitted
3011 * @param string $comment comment submitted
3012 * @param bool $minor whereas it's a minor modification
3014 function quickEdit( $text, $comment = '', $minor = 0 ) {
3015 wfProfileIn( __METHOD__
);
3017 $dbw = wfGetDB( DB_MASTER
);
3019 $revision = new Revision( array(
3020 'page' => $this->getId(),
3022 'comment' => $comment,
3023 'minor_edit' => $minor ?
1 : 0,
3025 $revision->insertOn( $dbw );
3026 $this->updateRevisionOn( $dbw, $revision );
3029 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3031 wfProfileOut( __METHOD__
);
3035 * Used to increment the view counter
3038 * @param integer $id article id
3040 function incViewCount( $id ) {
3041 $id = intval( $id );
3042 global $wgHitcounterUpdateFreq, $wgDBtype;
3044 $dbw = wfGetDB( DB_MASTER
);
3045 $pageTable = $dbw->tableName( 'page' );
3046 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3047 $acchitsTable = $dbw->tableName( 'acchits' );
3049 if( $wgHitcounterUpdateFreq <= 1 ) {
3050 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3054 # Not important enough to warrant an error page in case of failure
3055 $oldignore = $dbw->ignoreErrors( true );
3057 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3059 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3060 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3061 # Most of the time (or on SQL errors), skip row count check
3062 $dbw->ignoreErrors( $oldignore );
3066 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3067 $row = $dbw->fetchObject( $res );
3068 $rown = intval( $row->n
);
3069 if( $rown >= $wgHitcounterUpdateFreq ){
3070 wfProfileIn( 'Article::incViewCount-collect' );
3071 $old_user_abort = ignore_user_abort( true );
3073 if ($wgDBtype == 'mysql')
3074 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3075 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3076 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3077 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3079 $dbw->query("DELETE FROM $hitcounterTable");
3080 if ($wgDBtype == 'mysql') {
3081 $dbw->query('UNLOCK TABLES');
3082 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3083 'WHERE page_id = hc_id');
3086 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3087 "FROM $acchitsTable WHERE page_id = hc_id");
3089 $dbw->query("DROP TABLE $acchitsTable");
3091 ignore_user_abort( $old_user_abort );
3092 wfProfileOut( 'Article::incViewCount-collect' );
3094 $dbw->ignoreErrors( $oldignore );
3098 * The onArticle*() functions are supposed to be a kind of hooks
3099 * which should be called whenever any of the specified actions
3102 * This is a good place to put code to clear caches, for instance.
3104 * This is called on page move and undelete, as well as edit
3106 * @param $title_obj a title object
3109 static function onArticleCreate($title) {
3110 # The talk page isn't in the regular link tables, so we need to update manually:
3111 if ( $title->isTalkPage() ) {
3112 $other = $title->getSubjectPage();
3114 $other = $title->getTalkPage();
3116 $other->invalidateCache();
3117 $other->purgeSquid();
3119 $title->touchLinks();
3120 $title->purgeSquid();
3121 $title->deleteTitleProtection();
3124 static function onArticleDelete( $title ) {
3125 global $wgUseFileCache, $wgMessageCache;
3127 // Update existence markers on article/talk tabs...
3128 if( $title->isTalkPage() ) {
3129 $other = $title->getSubjectPage();
3131 $other = $title->getTalkPage();
3133 $other->invalidateCache();
3134 $other->purgeSquid();
3136 $title->touchLinks();
3137 $title->purgeSquid();
3140 if ( $wgUseFileCache ) {
3141 $cm = new HTMLFileCache( $title );
3142 @unlink
( $cm->fileCacheName() );
3146 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3147 $wgMessageCache->replace( $title->getDBkey(), false );
3150 if( $title->getNamespace() == NS_IMAGE
) {
3151 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3152 $update->doUpdate();
3155 if( $title->getNamespace() == NS_USER_TALK
) {
3156 $user = User
::newFromName( $title->getText(), false );
3157 $user->setNewtalk( false );
3162 * Purge caches on page update etc
3164 static function onArticleEdit( $title ) {
3165 global $wgDeferredUpdateList, $wgUseFileCache;
3167 // Invalidate caches of articles which include this page
3168 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3170 // Invalidate the caches of all pages which redirect here
3171 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3173 # Purge squid for this page only
3174 $title->purgeSquid();
3177 if ( $wgUseFileCache ) {
3178 $cm = new HTMLFileCache( $title );
3179 @unlink
( $cm->fileCacheName() );
3186 * Overriden by ImagePage class, only present here to avoid a fatal error
3187 * Called for ?action=revert
3189 public function revert(){
3191 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3195 * Info about this page
3196 * Called for ?action=info when $wgAllowPageInfo is on.
3201 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3203 if ( !$wgAllowPageInfo ) {
3204 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3208 $page = $this->mTitle
->getSubjectPage();
3210 $wgOut->setPagetitle( $page->getPrefixedText() );
3211 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3212 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3214 if( !$this->mTitle
->exists() ) {
3215 $wgOut->addHtml( '<div class="noarticletext">' );
3216 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3217 // This doesn't quite make sense; the user is asking for
3218 // information about the _page_, not the message... -- RC
3219 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3221 $msg = $wgUser->isLoggedIn()
3223 : 'noarticletextanon';
3224 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3226 $wgOut->addHtml( '</div>' );
3228 $dbr = wfGetDB( DB_SLAVE
);
3230 'wl_title' => $page->getDBkey(),
3231 'wl_namespace' => $page->getNamespace() );
3232 $numwatchers = $dbr->selectField(
3237 $this->getSelectOptions() );
3239 $pageInfo = $this->pageCountInfo( $page );
3240 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3242 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3243 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3245 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3247 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3249 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3251 $wgOut->addHTML( '</ul>' );
3257 * Return the total number of edits and number of unique editors
3258 * on a given page. If page does not exist, returns false.
3260 * @param Title $title
3264 function pageCountInfo( $title ) {
3265 $id = $title->getArticleId();
3270 $dbr = wfGetDB( DB_SLAVE
);
3272 $rev_clause = array( 'rev_page' => $id );
3274 $edits = $dbr->selectField(
3279 $this->getSelectOptions() );
3281 $authors = $dbr->selectField(
3283 'COUNT(DISTINCT rev_user_text)',
3286 $this->getSelectOptions() );
3288 return array( 'edits' => $edits, 'authors' => $authors );
3292 * Return a list of templates used by this article.
3293 * Uses the templatelinks table
3295 * @return array Array of Title objects
3297 function getUsedTemplates() {
3299 $id = $this->mTitle
->getArticleID();
3304 $dbr = wfGetDB( DB_SLAVE
);
3305 $res = $dbr->select( array( 'templatelinks' ),
3306 array( 'tl_namespace', 'tl_title' ),
3307 array( 'tl_from' => $id ),
3309 if( false !== $res ) {
3310 foreach( $res as $row ) {
3311 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3314 $dbr->freeResult( $res );
3319 * Returns a list of hidden categories this page is a member of.
3320 * Uses the page_props and categorylinks tables.
3322 * @return array Array of Title objects
3324 function getHiddenCategories() {
3326 $id = $this->mTitle
->getArticleID();
3331 $dbr = wfGetDB( DB_SLAVE
);
3332 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3334 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3335 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3337 if ( false !== $res ) {
3338 foreach( $res as $row ) {
3339 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3342 $dbr->freeResult( $res );
3347 * Return an applicable autosummary if one exists for the given edit.
3348 * @param string $oldtext The previous text of the page.
3349 * @param string $newtext The submitted text of the page.
3350 * @param bitmask $flags A bitmask of flags submitted for the edit.
3351 * @return string An appropriate autosummary, or an empty string.
3353 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3354 # Decide what kind of autosummary is needed.
3356 # Redirect autosummaries
3357 $rt = Title
::newFromRedirect( $newtext );
3358 if( is_object( $rt ) ) {
3359 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3362 # New page autosummaries
3363 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3364 # If they're making a new article, give its text, truncated, in the summary.
3366 $truncatedtext = $wgContLang->truncate(
3367 str_replace("\n", ' ', $newtext),
3368 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3370 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3373 # Blanking autosummaries
3374 if( $oldtext != '' && $newtext == '' ) {
3375 return wfMsgForContent('autosumm-blank');
3376 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3377 # Removing more than 90% of the article
3379 $truncatedtext = $wgContLang->truncate(
3381 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3384 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3387 # If we reach this point, there's no applicable autosummary for our case, so our
3388 # autosummary is empty.
3393 * Add the primary page-view wikitext to the output buffer
3394 * Saves the text into the parser cache if possible.
3395 * Updates templatelinks if it is out of date.
3397 * @param string $text
3398 * @param bool $cache
3400 public function outputWikiText( $text, $cache = true ) {
3401 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3403 $popts = $wgOut->parserOptions();
3404 $popts->setTidy(true);
3405 $popts->enableLimitReport();
3406 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3407 $popts, true, true, $this->getRevIdFetched() );
3408 $popts->setTidy(false);
3409 $popts->enableLimitReport( false );
3410 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3411 $parserCache = ParserCache
::singleton();
3412 $parserCache->save( $parserOutput, $this, $wgUser );
3415 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3416 // templatelinks table may have become out of sync,
3417 // especially if using variable-based transclusions.
3418 // For paranoia, check if things have changed and if
3419 // so apply updates to the database. This will ensure
3420 // that cascaded protections apply as soon as the changes
3423 # Get templates from templatelinks
3424 $id = $this->mTitle
->getArticleID();
3426 $tlTemplates = array();
3428 $dbr = wfGetDB( DB_SLAVE
);
3429 $res = $dbr->select( array( 'templatelinks' ),
3430 array( 'tl_namespace', 'tl_title' ),
3431 array( 'tl_from' => $id ),
3436 if ( false !== $res ) {
3437 foreach( $res as $row ) {
3438 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3442 # Get templates from parser output.
3443 $poTemplates_allns = $parserOutput->getTemplates();
3445 $poTemplates = array ();
3446 foreach ( $poTemplates_allns as $ns_templates ) {
3447 $poTemplates = array_merge( $poTemplates, $ns_templates );
3451 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3453 if ( count( $templates_diff ) > 0 ) {
3454 # Whee, link updates time.
3455 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3457 $dbw = wfGetDb( DB_MASTER
);
3466 $wgOut->addParserOutput( $parserOutput );
3470 * Update all the appropriate counts in the category table, given that
3471 * we've added the categories $added and deleted the categories $deleted.
3473 * @param $added array The names of categories that were added
3474 * @param $deleted array The names of categories that were deleted
3477 public function updateCategoryCounts( $added, $deleted ) {
3478 $ns = $this->mTitle
->getNamespace();
3479 $dbw = wfGetDB( DB_MASTER
);
3481 # First make sure the rows exist. If one of the "deleted" ones didn't
3482 # exist, we might legitimately not create it, but it's simpler to just
3483 # create it and then give it a negative value, since the value is bogus
3486 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3487 $insertCats = array_merge( $added, $deleted );
3488 if( !$insertCats ) {
3489 # Okay, nothing to do
3492 $insertRows = array();
3493 foreach( $insertCats as $cat ) {
3494 $insertRows[] = array( 'cat_title' => $cat );
3496 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3498 $addFields = array( 'cat_pages = cat_pages + 1' );
3499 $removeFields = array( 'cat_pages = cat_pages - 1' );
3500 if( $ns == NS_CATEGORY
) {
3501 $addFields[] = 'cat_subcats = cat_subcats + 1';
3502 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3503 } elseif( $ns == NS_IMAGE
) {
3504 $addFields[] = 'cat_files = cat_files + 1';
3505 $removeFields[] = 'cat_files = cat_files - 1';
3512 array( 'cat_title' => $added ),
3520 array( 'cat_title' => $deleted ),