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' );
227 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
228 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
229 if( $pager->getNumRows() > 0 ) {
230 $wgOut->addHtml( '<div id="mw-deleted-notice">' );
231 $wgOut->addWikiMsg( 'deleted-notice' );
233 $loglist->beginLogEventsList() .
235 $loglist->endLogEventsList()
237 $wgOut->addHtml( '</div>' );
239 return "<div class='noarticletext'>\n$ret\n</div>";
241 $this->loadContent();
242 wfProfileOut( __METHOD__
);
243 return $this->mContent
;
248 * This function returns the text of a section, specified by a number ($section).
249 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
250 * the first section before any such heading (section 0).
252 * If a section contains subsections, these are also returned.
254 * @param $text String: text to look in
255 * @param $section Integer: section number
256 * @return string text of the requested section
259 function getSection($text,$section) {
261 return $wgParser->getSection( $text, $section );
265 * @return int The oldid of the article that is to be shown, 0 for the
268 function getOldID() {
269 if ( is_null( $this->mOldId
) ) {
270 $this->mOldId
= $this->getOldIDFromRequest();
272 return $this->mOldId
;
276 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
278 * @return int The old id for the request
280 public function getOldIDFromRequest() {
282 $this->mRedirectUrl
= false;
283 $oldid = $wgRequest->getVal( 'oldid' );
284 if ( isset( $oldid ) ) {
285 $oldid = intval( $oldid );
286 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
287 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
291 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
293 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
294 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
312 * Load the revision (including text) into this object
314 function loadContent() {
315 if ( $this->mContentLoaded
) return;
318 $oldid = $this->getOldID();
320 # Pre-fill content with error message so that if something
321 # fails we'll have something telling us what we intended.
322 $this->mOldId
= $oldid;
323 $this->fetchContent( $oldid );
328 * Fetch a page record with the given conditions
329 * @param Database $dbr
330 * @param array $conditions
333 function pageData( $dbr, $conditions ) {
347 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
348 $row = $dbr->selectRow(
354 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
359 * @param Database $dbr
360 * @param Title $title
362 function pageDataFromTitle( $dbr, $title ) {
363 return $this->pageData( $dbr, array(
364 'page_namespace' => $title->getNamespace(),
365 'page_title' => $title->getDBkey() ) );
369 * @param Database $dbr
372 function pageDataFromId( $dbr, $id ) {
373 return $this->pageData( $dbr, array( 'page_id' => $id ) );
377 * Set the general counter, title etc data loaded from
380 * @param object $data
383 function loadPageData( $data = 'fromdb' ) {
384 if ( $data === 'fromdb' ) {
385 $dbr = wfGetDB( DB_MASTER
);
386 $data = $this->pageDataFromId( $dbr, $this->getId() );
389 $lc = LinkCache
::singleton();
391 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
393 $this->mTitle
->mArticleID
= $data->page_id
;
395 # Old-fashioned restrictions.
396 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
398 $this->mCounter
= $data->page_counter
;
399 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
400 $this->mIsRedirect
= $data->page_is_redirect
;
401 $this->mLatest
= $data->page_latest
;
403 if ( is_object( $this->mTitle
) ) {
404 $lc->addBadLinkObj( $this->mTitle
);
406 $this->mTitle
->mArticleID
= 0;
409 $this->mDataLoaded
= true;
413 * Get text of an article from database
414 * Does *NOT* follow redirects.
415 * @param int $oldid 0 for whatever the latest revision is
418 function fetchContent( $oldid = 0 ) {
419 if ( $this->mContentLoaded
) {
420 return $this->mContent
;
423 $dbr = wfGetDB( DB_MASTER
);
425 # Pre-fill content with error message so that if something
426 # fails we'll have something telling us what we intended.
427 $t = $this->mTitle
->getPrefixedText();
428 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
429 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
432 $revision = Revision
::newFromId( $oldid );
433 if( is_null( $revision ) ) {
434 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
437 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
439 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
442 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
443 $this->loadPageData( $data );
445 if( !$this->mDataLoaded
) {
446 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
448 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
451 $this->loadPageData( $data );
453 $revision = Revision
::newFromId( $this->mLatest
);
454 if( is_null( $revision ) ) {
455 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
460 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
461 // We should instead work with the Revision object when we need it...
462 $this->mContent
= $revision->revText(); // Loads if user is allowed
464 $this->mUser
= $revision->getUser();
465 $this->mUserText
= $revision->getUserText();
466 $this->mComment
= $revision->getComment();
467 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
469 $this->mRevIdFetched
= $revision->getId();
470 $this->mContentLoaded
= true;
471 $this->mRevision
=& $revision;
473 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
475 return $this->mContent
;
479 * Read/write accessor to select FOR UPDATE
481 * @param $x Mixed: FIXME
483 function forUpdate( $x = NULL ) {
484 return wfSetVar( $this->mForUpdate
, $x );
488 * Get the database which should be used for reads
491 * @deprecated - just call wfGetDB( DB_MASTER ) instead
494 wfDeprecated( __METHOD__
);
495 return wfGetDB( DB_MASTER
);
499 * Get options for all SELECT statements
501 * @param $options Array: an optional options array which'll be appended to
503 * @return Array: options
505 function getSelectOptions( $options = '' ) {
506 if ( $this->mForUpdate
) {
507 if ( is_array( $options ) ) {
508 $options[] = 'FOR UPDATE';
510 $options = 'FOR UPDATE';
517 * @return int Page ID
520 if( $this->mTitle
) {
521 return $this->mTitle
->getArticleID();
528 * @return bool Whether or not the page exists in the database
531 return $this->getId() != 0;
535 * @return int The view count for the page
537 function getCount() {
538 if ( -1 == $this->mCounter
) {
539 $id = $this->getID();
543 $dbr = wfGetDB( DB_SLAVE
);
544 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
545 'Article::getCount', $this->getSelectOptions() );
548 return $this->mCounter
;
552 * Determine whether a page would be suitable for being counted as an
553 * article in the site_stats table based on the title & its content
555 * @param $text String: text to analyze
558 function isCountable( $text ) {
559 global $wgUseCommaCount;
561 $token = $wgUseCommaCount ?
',' : '[[';
563 $this->mTitle
->isContentPage()
564 && !$this->isRedirect( $text )
565 && in_string( $token, $text );
569 * Tests if the article text represents a redirect
571 * @param $text String: FIXME
574 function isRedirect( $text = false ) {
575 if ( $text === false ) {
576 if ( $this->mDataLoaded
)
577 return $this->mIsRedirect
;
579 // Apparently loadPageData was never called
580 $this->loadContent();
581 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
583 $titleObj = Title
::newFromRedirect( $text );
585 return $titleObj !== NULL;
589 * Returns true if the currently-referenced revision is the current edit
590 * to this page (and it exists).
593 function isCurrent() {
594 # If no oldid, this is the current version.
595 if ($this->getOldID() == 0)
598 return $this->exists() &&
599 isset( $this->mRevision
) &&
600 $this->mRevision
->isCurrent();
604 * Loads everything except the text
605 * This isn't necessary for all uses, so it's only done if needed.
608 function loadLastEdit() {
609 if ( -1 != $this->mUser
)
612 # New or non-existent articles have no user information
613 $id = $this->getID();
614 if ( 0 == $id ) return;
616 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
617 if( !is_null( $this->mLastRevision
) ) {
618 $this->mUser
= $this->mLastRevision
->getUser();
619 $this->mUserText
= $this->mLastRevision
->getUserText();
620 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
621 $this->mComment
= $this->mLastRevision
->getComment();
622 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
623 $this->mRevIdFetched
= $this->mLastRevision
->getId();
627 function getTimestamp() {
628 // Check if the field has been filled by ParserCache::get()
629 if ( !$this->mTimestamp
) {
630 $this->loadLastEdit();
632 return wfTimestamp(TS_MW
, $this->mTimestamp
);
636 $this->loadLastEdit();
640 function getUserText() {
641 $this->loadLastEdit();
642 return $this->mUserText
;
645 function getComment() {
646 $this->loadLastEdit();
647 return $this->mComment
;
650 function getMinorEdit() {
651 $this->loadLastEdit();
652 return $this->mMinorEdit
;
655 function getRevIdFetched() {
656 $this->loadLastEdit();
657 return $this->mRevIdFetched
;
661 * @param $limit Integer: default 0.
662 * @param $offset Integer: default 0.
664 function getContributors($limit = 0, $offset = 0) {
665 # XXX: this is expensive; cache this info somewhere.
668 $dbr = wfGetDB( DB_SLAVE
);
669 $revTable = $dbr->tableName( 'revision' );
670 $userTable = $dbr->tableName( 'user' );
671 $user = $this->getUser();
672 $pageId = $this->getId();
674 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
675 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
676 WHERE rev_page = $pageId
677 AND rev_user != $user
678 GROUP BY rev_user, rev_user_text, user_real_name
679 ORDER BY timestamp DESC";
681 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
682 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
684 $sql .= ' '. $this->getSelectOptions();
686 $res = $dbr->query($sql, __METHOD__
);
688 return new UserArrayFromResult( $res );
692 * This is the default action of the script: just view the page of
696 global $wgUser, $wgOut, $wgRequest, $wgContLang;
697 global $wgEnableParserCache, $wgStylePath, $wgParser;
698 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
699 global $wgDefaultRobotPolicy;
700 $sk = $wgUser->getSkin();
702 wfProfileIn( __METHOD__
);
704 $parserCache = ParserCache
::singleton();
705 $ns = $this->mTitle
->getNamespace(); # shortcut
707 # Get variables from query string
708 $oldid = $this->getOldID();
710 # getOldID may want us to redirect somewhere else
711 if ( $this->mRedirectUrl
) {
712 $wgOut->redirect( $this->mRedirectUrl
);
713 wfProfileOut( __METHOD__
);
717 $diff = $wgRequest->getVal( 'diff' );
718 $rcid = $wgRequest->getVal( 'rcid' );
719 $rdfrom = $wgRequest->getVal( 'rdfrom' );
720 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
721 $purge = $wgRequest->getVal( 'action' ) == 'purge';
723 $wgOut->setArticleFlag( true );
725 # Discourage indexing of printable versions, but encourage following
726 if( $wgOut->isPrintable() ) {
727 $policy = 'noindex,follow';
728 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
729 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
730 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
731 # Honour customised robot policies for this namespace
732 $policy = $wgNamespaceRobotPolicies[$ns];
734 $policy = $wgDefaultRobotPolicy;
736 $wgOut->setRobotPolicy( $policy );
738 # If we got diff and oldid in the query, we want to see a
739 # diff page instead of the article.
741 if ( !is_null( $diff ) ) {
742 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
744 $diff = $wgRequest->getVal( 'diff' );
745 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
746 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
747 // DifferenceEngine directly fetched the revision:
748 $this->mRevIdFetched
= $de->mNewid
;
749 $de->showDiffPage( $diffOnly );
751 // Needed to get the page's current revision
752 $this->loadPageData();
753 if( $diff == 0 ||
$diff == $this->mLatest
) {
754 # Run view updates for current revision only
755 $this->viewUpdates();
757 wfProfileOut( __METHOD__
);
761 if ( empty( $oldid ) && $this->checkTouched() ) {
762 $wgOut->setETag($parserCache->getETag($this, $wgUser));
764 if( $wgOut->checkLastModified( $this->mTouched
) ){
765 wfProfileOut( __METHOD__
);
767 } else if ( $this->tryFileCache() ) {
768 # tell wgOut that output is taken care of
770 $this->viewUpdates();
771 wfProfileOut( __METHOD__
);
776 # Should the parser cache be used?
777 $pcache = $this->useParserCache( $oldid );
778 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
779 if ( $wgUser->getOption( 'stubthreshold' ) ) {
780 wfIncrStats( 'pcache_miss_stub' );
783 $wasRedirected = false;
784 if ( isset( $this->mRedirectedFrom
) ) {
785 // This is an internally redirected page view.
786 // We'll need a backlink to the source page for navigation.
787 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
788 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
789 $s = wfMsg( 'redirectedfrom', $redir );
790 $wgOut->setSubtitle( $s );
792 // Set the fragment if one was specified in the redirect
793 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
794 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
795 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
797 $wasRedirected = true;
799 } elseif ( !empty( $rdfrom ) ) {
800 // This is an externally redirected view, from some other wiki.
801 // If it was reported from a trusted site, supply a backlink.
802 global $wgRedirectSources;
803 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
804 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
805 $s = wfMsg( 'redirectedfrom', $redir );
806 $wgOut->setSubtitle( $s );
807 $wasRedirected = true;
812 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
814 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
815 // Ensure that UI elements requiring revision ID have
816 // the correct version information.
817 $wgOut->setRevisionId( $this->mLatest
);
821 # Fetch content and check for errors
822 if ( !$outputDone ) {
823 $text = $this->getContent();
824 if ( $text === false ) {
825 # Failed to load, replace text with error message
826 $t = $this->mTitle
->getPrefixedText();
828 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
829 $text = wfMsg( 'missing-article', $t, $d );
831 $text = wfMsg( 'noarticletext' );
835 # Another whitelist check in case oldid is altering the title
836 if ( !$this->mTitle
->userCanRead() ) {
837 $wgOut->loginToUse();
839 wfProfileOut( __METHOD__
);
843 # We're looking at an old revision
844 if ( !empty( $oldid ) ) {
845 $wgOut->setRobotPolicy( 'noindex,nofollow' );
846 if( is_null( $this->mRevision
) ) {
847 // FIXME: This would be a nice place to load the 'no such page' text.
849 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
850 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
851 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
852 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
853 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
854 wfProfileOut( __METHOD__
);
857 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
858 // and we are allowed to see...
864 $wgOut->setRevisionId( $this->getRevIdFetched() );
866 // Pages containing custom CSS or JavaScript get special treatment
867 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
868 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
869 // Give hooks a chance to customise the output
870 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
871 // Wrap the whole lot in a <pre> and don't parse
873 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
874 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
875 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
876 $wgOut->addHtml( "\n</pre>\n" );
878 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
879 # Don't append the subtitle if this was an old revision
880 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
881 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
882 $wgOut->addParserOutputNoText( $parseout );
883 } else if ( $pcache ) {
884 # Display content and save to parser cache
885 $this->outputWikiText( $text );
887 # Display content, don't attempt to save to parser cache
888 # Don't show section-edit links on old revisions... this way lies madness.
889 if( !$this->isCurrent() ) {
890 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
892 # Display content and don't save to parser cache
893 # With timing hack -- TS 2006-07-26
895 $this->outputWikiText( $text, false );
900 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
901 $this->mTitle
->getPrefixedDBkey()));
904 if( !$this->isCurrent() ) {
905 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
909 /* title may have been set from the cache */
910 $t = $wgOut->getPageTitle();
912 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
914 # For the main page, overwrite the <title> element with the con-
915 # tents of 'pagetitle-view-mainpage' instead of the default (if
917 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
918 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
919 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
923 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
924 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
925 $wgOut->addWikiMsg('anontalkpagetext');
928 # If we have been passed an &rcid= parameter, we want to give the user a
929 # chance to mark this new article as patrolled.
930 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
932 "<div class='patrollink'>" .
933 wfMsgHtml( 'markaspatrolledlink',
934 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
935 "action=markpatrolled&rcid=$rcid" )
942 if ($wgUseTrackbacks)
943 $this->addTrackbacks();
945 $this->viewUpdates();
946 wfProfileOut( __METHOD__
);
950 * Should the parser cache be used?
952 protected function useParserCache( $oldid ) {
953 global $wgUser, $wgEnableParserCache;
955 return $wgEnableParserCache
956 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
959 && !$this->mTitle
->isCssOrJsPage()
960 && !$this->mTitle
->isCssJsSubpage();
965 * @param Title $target Title of destination to redirect
966 * @param Bool $appendSubtitle Object[optional]
967 * @param Bool $forceKnown Should the image be shown as a bluelink regardless of existence?
969 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
970 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
973 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
974 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
976 if( $appendSubtitle ) {
977 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
979 $sk = $wgUser->getSkin();
981 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
983 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
985 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
986 '<span class="redirectText">'.$link.'</span>';
990 function addTrackbacks() {
991 global $wgOut, $wgUser;
993 $dbr = wfGetDB(DB_SLAVE
);
995 /* FROM */ 'trackbacks',
996 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
997 /* WHERE */ array('tb_page' => $this->getID())
1000 if (!$dbr->numrows($tbs))
1004 while ($o = $dbr->fetchObject($tbs)) {
1006 if ($wgUser->isAllowed( 'trackback' )) {
1007 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
1008 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1009 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1012 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1019 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1022 function deletetrackback() {
1023 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1025 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
1026 $wgOut->addWikiMsg( 'sessionfailure' );
1030 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1032 if (count($permission_errors)>0)
1034 $wgOut->showPermissionsErrorPage( $permission_errors );
1038 $db = wfGetDB(DB_MASTER
);
1039 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1040 $wgTitle->invalidateCache();
1041 $wgOut->addWikiMsg('trackbackdeleteok');
1047 $wgOut->setArticleBodyOnly(true);
1052 * Handle action=purge
1055 global $wgUser, $wgRequest, $wgOut;
1057 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1058 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1063 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1064 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1065 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1066 $msg = str_replace( '$1',
1067 "<form method=\"post\" action=\"$action\">\n" .
1068 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1069 "</form>\n", $msg );
1071 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1072 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1073 $wgOut->addHTML( $msg );
1078 * Perform the actions of a page purging
1080 function doPurge() {
1082 // Invalidate the cache
1083 $this->mTitle
->invalidateCache();
1085 if ( $wgUseSquid ) {
1086 // Commit the transaction before the purge is sent
1087 $dbw = wfGetDB( DB_MASTER
);
1088 $dbw->immediateCommit();
1091 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1092 $update->doUpdate();
1094 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1095 global $wgMessageCache;
1096 if ( $this->getID() == 0 ) {
1099 $text = $this->getContent();
1101 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1106 * Insert a new empty page record for this article.
1107 * This *must* be followed up by creating a revision
1108 * and running $this->updateToLatest( $rev_id );
1109 * or else the record will be left in a funky state.
1110 * Best if all done inside a transaction.
1112 * @param Database $dbw
1113 * @return int The newly created page_id key
1116 function insertOn( $dbw ) {
1117 wfProfileIn( __METHOD__
);
1119 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1120 $dbw->insert( 'page', array(
1121 'page_id' => $page_id,
1122 'page_namespace' => $this->mTitle
->getNamespace(),
1123 'page_title' => $this->mTitle
->getDBkey(),
1124 'page_counter' => 0,
1125 'page_restrictions' => '',
1126 'page_is_redirect' => 0, # Will set this shortly...
1128 'page_random' => wfRandom(),
1129 'page_touched' => $dbw->timestamp(),
1130 'page_latest' => 0, # Fill this in shortly...
1131 'page_len' => 0, # Fill this in shortly...
1133 $newid = $dbw->insertId();
1135 $this->mTitle
->resetArticleId( $newid );
1137 wfProfileOut( __METHOD__
);
1142 * Update the page record to point to a newly saved revision.
1144 * @param Database $dbw
1145 * @param Revision $revision For ID number, and text used to set
1146 length and redirect status fields
1147 * @param int $lastRevision If given, will not overwrite the page field
1148 * when different from the currently set value.
1149 * Giving 0 indicates the new page flag should
1151 * @param bool $lastRevIsRedirect If given, will optimize adding and
1152 * removing rows in redirect table.
1153 * @return bool true on success, false on failure
1156 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1157 wfProfileIn( __METHOD__
);
1159 $text = $revision->getText();
1160 $rt = Title
::newFromRedirect( $text );
1162 $conditions = array( 'page_id' => $this->getId() );
1163 if( !is_null( $lastRevision ) ) {
1164 # An extra check against threads stepping on each other
1165 $conditions['page_latest'] = $lastRevision;
1168 $dbw->update( 'page',
1170 'page_latest' => $revision->getId(),
1171 'page_touched' => $dbw->timestamp(),
1172 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1173 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1174 'page_len' => strlen( $text ),
1179 $result = $dbw->affectedRows() != 0;
1182 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1185 wfProfileOut( __METHOD__
);
1190 * Add row to the redirect table if this is a redirect, remove otherwise.
1192 * @param Database $dbw
1193 * @param $redirectTitle a title object pointing to the redirect target,
1194 * or NULL if this is not a redirect
1195 * @param bool $lastRevIsRedirect If given, will optimize adding and
1196 * removing rows in redirect table.
1197 * @return bool true on success, false on failure
1200 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1202 // Always update redirects (target link might have changed)
1203 // Update/Insert if we don't know if the last revision was a redirect or not
1204 // Delete if changing from redirect to non-redirect
1205 $isRedirect = !is_null($redirectTitle);
1206 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1208 wfProfileIn( __METHOD__
);
1212 // This title is a redirect, Add/Update row in the redirect table
1213 $set = array( /* SET */
1214 'rd_namespace' => $redirectTitle->getNamespace(),
1215 'rd_title' => $redirectTitle->getDBkey(),
1216 'rd_from' => $this->getId(),
1219 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1221 // This is not a redirect, remove row from redirect table
1222 $where = array( 'rd_from' => $this->getId() );
1223 $dbw->delete( 'redirect', $where, __METHOD__
);
1226 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1227 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1228 wfProfileOut( __METHOD__
);
1229 return ( $dbw->affectedRows() != 0 );
1236 * If the given revision is newer than the currently set page_latest,
1237 * update the page record. Otherwise, do nothing.
1239 * @param Database $dbw
1240 * @param Revision $revision
1242 function updateIfNewerOn( &$dbw, $revision ) {
1243 wfProfileIn( __METHOD__
);
1245 $row = $dbw->selectRow(
1246 array( 'revision', 'page' ),
1247 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1249 'page_id' => $this->getId(),
1250 'page_latest=rev_id' ),
1253 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1254 wfProfileOut( __METHOD__
);
1257 $prev = $row->rev_id
;
1258 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1260 # No or missing previous revision; mark the page as new
1262 $lastRevIsRedirect = null;
1265 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1266 wfProfileOut( __METHOD__
);
1271 * @return string Complete article text, or null if error
1273 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1274 wfProfileIn( __METHOD__
);
1276 if( $section == '' ) {
1277 // Whole-page edit; let the text through unmolested.
1279 if( is_null( $edittime ) ) {
1280 $rev = Revision
::newFromTitle( $this->mTitle
);
1282 $dbw = wfGetDB( DB_MASTER
);
1283 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1285 if( is_null( $rev ) ) {
1286 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1287 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1290 $oldtext = $rev->getText();
1292 if( $section == 'new' ) {
1293 # Inserting a new section
1294 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1295 $text = strlen( trim( $oldtext ) ) > 0
1296 ?
"{$oldtext}\n\n{$subject}{$text}"
1297 : "{$subject}{$text}";
1299 # Replacing an existing section; roll out the big guns
1301 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1306 wfProfileOut( __METHOD__
);
1311 * @deprecated use Article::doEdit()
1313 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1314 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1315 ( $isminor ? EDIT_MINOR
: 0 ) |
1316 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1317 ( $bot ? EDIT_FORCE_BOT
: 0 );
1319 # If this is a comment, add the summary as headline
1320 if ( $comment && $summary != "" ) {
1321 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1324 $this->doEdit( $text, $summary, $flags );
1326 $dbw = wfGetDB( DB_MASTER
);
1328 if (!$this->mTitle
->userIsWatching()) {
1334 if ( $this->mTitle
->userIsWatching() ) {
1340 $this->doRedirect( $this->isRedirect( $text ) );
1344 * @deprecated use Article::doEdit()
1346 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1347 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1348 ( $minor ? EDIT_MINOR
: 0 ) |
1349 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1351 $good = $this->doEdit( $text, $summary, $flags );
1353 $dbw = wfGetDB( DB_MASTER
);
1355 if (!$this->mTitle
->userIsWatching()) {
1361 if ( $this->mTitle
->userIsWatching() ) {
1368 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1369 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1371 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1379 * Change an existing article or create a new article. Updates RC and all necessary caches,
1380 * optionally via the deferred update array.
1382 * $wgUser must be set before calling this function.
1384 * @param string $text New text
1385 * @param string $summary Edit summary
1386 * @param integer $flags bitfield:
1388 * Article is known or assumed to be non-existent, create a new one
1390 * Article is known or assumed to be pre-existing, update it
1392 * Mark this edit minor, if the user is allowed to do so
1394 * Do not log the change in recentchanges
1396 * Mark the edit a "bot" edit regardless of user rights
1397 * EDIT_DEFER_UPDATES
1398 * Defer some of the updates until the end of index.php
1400 * Fill in blank summaries with generated text where possible
1402 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1403 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1404 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1405 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1406 * to MediaWiki's performance-optimised locking strategy.
1407 * @param $baseRevId, the revision ID this edit was based off, if any
1409 * @return bool success
1411 function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1412 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1414 if ($user == null) {
1418 wfProfileIn( __METHOD__
);
1421 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1422 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1424 $flags |
= EDIT_UPDATE
;
1430 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text,
1431 &$summary, $flags & EDIT_MINOR
,
1432 null, null, &$flags ) ) )
1434 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1435 wfProfileOut( __METHOD__
);
1439 # Silently ignore EDIT_MINOR if not allowed
1440 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1441 $bot = $flags & EDIT_FORCE_BOT
;
1443 $oldtext = $this->getContent();
1444 $oldsize = strlen( $oldtext );
1446 # Provide autosummaries if one is not provided and autosummaries are enabled.
1447 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1448 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1451 $editInfo = $this->prepareTextForEdit( $text );
1452 $text = $editInfo->pst
;
1453 $newsize = strlen( $text );
1455 $dbw = wfGetDB( DB_MASTER
);
1456 $now = wfTimestampNow();
1458 if ( $flags & EDIT_UPDATE
) {
1459 # Update article, but only if changed.
1461 # Make sure the revision is either completely inserted or not inserted at all
1462 if( !$wgDBtransactions ) {
1463 $userAbort = ignore_user_abort( true );
1469 $changed = ( strcmp( $text, $oldtext ) != 0 );
1472 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1473 - (int)$this->isCountable( $oldtext );
1474 $this->mTotalAdjustment
= 0;
1476 $lastRevision = $dbw->selectField(
1477 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1479 if ( !$lastRevision ) {
1480 # Article gone missing
1481 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1482 wfProfileOut( __METHOD__
);
1486 $revision = new Revision( array(
1487 'page' => $this->getId(),
1488 'comment' => $summary,
1489 'minor_edit' => $isminor,
1491 'parent_id' => $lastRevision,
1492 'user' => $user->getId(),
1493 'user_text' => $user->getName(),
1497 $revisionId = $revision->insertOn( $dbw );
1500 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1503 /* Belated edit conflict! Run away!! */
1507 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1509 # Update recentchanges
1510 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1511 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1512 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1515 # Mark as patrolled if the user can do so
1516 if( $GLOBALS['wgUseRCPatrol'] && $user->isAllowed( 'autopatrol' ) ) {
1517 RecentChange
::markPatrolled( $rcid );
1518 PatrolLog
::record( $rcid, true );
1521 $user->incEditCount();
1526 // Keep the same revision ID, but do some updates on it
1527 $revisionId = $this->getRevIdFetched();
1528 // Update page_touched, this is usually implicit in the page update
1529 // Other cache updates are done in onArticleEdit()
1530 $this->mTitle
->invalidateCache();
1533 if( !$wgDBtransactions ) {
1534 ignore_user_abort( $userAbort );
1538 # Invalidate cache of this article and all pages using this article
1539 # as a template. Partly deferred.
1540 Article
::onArticleEdit( $this->mTitle
);
1542 # Update links tables, site stats, etc.
1543 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1546 # Create new article
1548 # Set statistics members
1549 # We work out if it's countable after PST to avoid counter drift
1550 # when articles are created with {{subst:}}
1551 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1552 $this->mTotalAdjustment
= 1;
1556 # Add the page record; stake our claim on this title!
1557 # This will fail with a database query exception if the article already exists
1558 $newid = $this->insertOn( $dbw );
1560 # Save the revision text...
1561 $revision = new Revision( array(
1563 'comment' => $summary,
1564 'minor_edit' => $isminor,
1567 $revisionId = $revision->insertOn( $dbw );
1569 $this->mTitle
->resetArticleID( $newid );
1571 # Update the page record with revision data
1572 $this->updateRevisionOn( $dbw, $revision, 0 );
1574 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1576 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1577 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1578 '', strlen( $text ), $revisionId );
1579 # Mark as patrolled if the user can
1580 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $user->isAllowed( 'autopatrol' ) ) {
1581 RecentChange
::markPatrolled( $rcid );
1582 PatrolLog
::record( $rcid, true );
1585 $user->incEditCount();
1588 # Update links, etc.
1589 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1592 Article
::onArticleCreate( $this->mTitle
);
1594 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1595 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1598 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1603 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1604 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1607 wfProfileOut( __METHOD__
);
1612 * @deprecated wrapper for doRedirect
1614 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1615 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1619 * Output a redirect back to the article.
1620 * This is typically used after an edit.
1622 * @param boolean $noRedir Add redirect=no
1623 * @param string $sectionAnchor section to redirect to, including "#"
1624 * @param string $extraQuery, extra query params
1626 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1629 $query = 'redirect=no';
1631 $query .= "&$query";
1633 $query = $extraQuery;
1635 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1639 * Mark this particular edit/page as patrolled
1641 function markpatrolled() {
1642 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1643 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1645 # If we haven't been given an rc_id value, we can't do anything
1646 $rcid = (int) $wgRequest->getVal('rcid');
1647 $rc = RecentChange
::newFromId($rcid);
1650 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1654 #It would be nice to see where the user had actually come from, but for now just guess
1655 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1656 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1658 $errors = $rc->doMarkPatrolled();
1659 if (in_array(array('rcpatroldisabled'), $errors)) {
1660 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1664 if (in_array(array('hookaborted'), $errors)) {
1665 // The hook itself has handled any output
1669 if (in_array(array('markedaspatrollederror-noautopatrol'), $errors)) {
1670 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1671 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1672 $wgOut->returnToMain( false, $return );
1676 if (!empty($errors))
1678 $wgOut->showPermissionsErrorPage( $errors );
1683 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1684 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1685 $wgOut->returnToMain( false, $return );
1689 * User-interface handler for the "watch" action
1694 global $wgUser, $wgOut;
1696 if ( $wgUser->isAnon() ) {
1697 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1700 if ( wfReadOnly() ) {
1701 $wgOut->readOnlyPage();
1705 if( $this->doWatch() ) {
1706 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1707 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1709 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1712 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1716 * Add this page to $wgUser's watchlist
1717 * @return bool true on successful watch operation
1719 function doWatch() {
1721 if( $wgUser->isAnon() ) {
1725 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1726 $wgUser->addWatch( $this->mTitle
);
1728 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1735 * User interface handler for the "unwatch" action.
1737 function unwatch() {
1739 global $wgUser, $wgOut;
1741 if ( $wgUser->isAnon() ) {
1742 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1745 if ( wfReadOnly() ) {
1746 $wgOut->readOnlyPage();
1750 if( $this->doUnwatch() ) {
1751 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1752 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1754 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1757 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1761 * Stop watching a page
1762 * @return bool true on successful unwatch
1764 function doUnwatch() {
1766 if( $wgUser->isAnon() ) {
1770 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1771 $wgUser->removeWatch( $this->mTitle
);
1773 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1780 * action=protect handler
1782 function protect() {
1783 $form = new ProtectionForm( $this );
1788 * action=unprotect handler (alias)
1790 function unprotect() {
1795 * Update the article's restriction field, and leave a log entry.
1797 * @param array $limit set of restriction keys
1798 * @param string $reason
1799 * @return bool true on success
1801 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1802 global $wgUser, $wgRestrictionTypes, $wgContLang;
1804 $id = $this->mTitle
->getArticleID();
1805 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1813 // Take this opportunity to purge out expired restrictions
1814 Title
::purgeExpiredRestrictions();
1816 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1817 # we expect a single selection, but the schema allows otherwise.
1819 foreach( $wgRestrictionTypes as $action )
1820 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1822 $current = Article
::flattenRestrictions( $current );
1823 $updated = Article
::flattenRestrictions( $limit );
1825 $changed = ( $current != $updated );
1826 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1827 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1828 $protect = ( $updated != '' );
1830 # If nothing's changed, do nothing
1832 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1834 $dbw = wfGetDB( DB_MASTER
);
1836 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1838 $expiry_description = '';
1839 if( $encodedExpiry != 'infinity' ) {
1840 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',
1841 $wgContLang->timeanddate( $expiry, false, false ) ).')';
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' ) {
1863 $cascade_description = '';
1865 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1869 $comment .= ": $reason";
1871 $editComment = $comment;
1873 $editComment .= " [$updated]";
1874 if( $expiry_description && $protect )
1875 $editComment .= "$expiry_description";
1877 $editComment .= "$cascade_description";
1878 # Update restrictions table
1879 foreach( $limit as $action => $restrictions ) {
1880 if ($restrictions != '' ) {
1881 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1882 array( 'pr_page' => $id, 'pr_type' => $action
1883 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1884 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1886 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1887 'pr_type' => $action ), __METHOD__
);
1891 # Insert a null revision
1892 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1893 $nullRevId = $nullRevision->insertOn( $dbw );
1895 $latest = $this->getLatest();
1896 # Update page record
1897 $dbw->update( 'page',
1899 'page_touched' => $dbw->timestamp(),
1900 'page_restrictions' => '',
1901 'page_latest' => $nullRevId
1902 ), array( /* WHERE */
1904 ), 'Article::protect'
1907 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest) );
1908 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1910 # Update the protection log
1911 $log = new LogPage( 'protect' );
1913 $params = array($updated,$encodedExpiry,$cascade ?
'cascade' : '');
1914 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
1916 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1920 } # End "changed" check
1926 * Take an array of page restrictions and flatten it to a string
1927 * suitable for insertion into the page_restrictions field.
1928 * @param array $limit
1932 function flattenRestrictions( $limit ) {
1933 if( !is_array( $limit ) ) {
1934 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1938 foreach( $limit as $action => $restrictions ) {
1939 if( $restrictions != '' ) {
1940 $bits[] = "$action=$restrictions";
1943 return implode( ':', $bits );
1947 * Auto-generates a deletion reason
1948 * @param bool &$hasHistory Whether the page has a history
1950 public function generateReason(&$hasHistory)
1953 $dbw = wfGetDB(DB_MASTER
);
1954 // Get the last revision
1955 $rev = Revision
::newFromTitle($this->mTitle
);
1958 // Get the article's contents
1959 $contents = $rev->getText();
1961 // If the page is blank, use the text from the previous revision,
1962 // which can only be blank if there's a move/import/protect dummy revision involved
1965 $prev = $rev->getPrevious();
1968 $contents = $prev->getText();
1973 // Find out if there was only one contributor
1974 // Only scan the last 20 revisions
1976 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1977 array('LIMIT' => $limit));
1979 // This page has no revisions, which is very weird
1981 if($res->numRows() > 1)
1984 $hasHistory = false;
1985 $row = $dbw->fetchObject($res);
1986 $onlyAuthor = $row->rev_user_text
;
1987 // Try to find a second contributor
1988 foreach( $res as $row ) {
1989 if($row->rev_user_text
!= $onlyAuthor) {
1990 $onlyAuthor = false;
1994 $dbw->freeResult($res);
1996 // Generate the summary with a '$1' placeholder
1998 // The current revision is blank and the one before is also
1999 // blank. It's just not our lucky day
2000 $reason = wfMsgForContent('exbeforeblank', '$1');
2003 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
2005 $reason = wfMsgForContent('excontent', '$1');
2008 // Replace newlines with spaces to prevent uglyness
2009 $contents = preg_replace("/[\n\r]/", ' ', $contents);
2010 // Calculate the maximum amount of chars to get
2011 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2012 $maxLength = 255 - (strlen($reason) - 2) - 3;
2013 $contents = $wgContLang->truncate($contents, $maxLength, '...');
2014 // Remove possible unfinished links
2015 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2016 // Now replace the '$1' placeholder
2017 $reason = str_replace( '$1', $contents, $reason );
2023 * UI entry point for page deletion
2026 global $wgUser, $wgOut, $wgRequest;
2028 $confirm = $wgRequest->wasPosted() &&
2029 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2031 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2032 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2034 $reason = $this->DeleteReasonList
;
2036 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2037 // Entry from drop down menu + additional comment
2038 $reason .= ': ' . $this->DeleteReason
;
2039 } elseif ( $reason == 'other' ) {
2040 $reason = $this->DeleteReason
;
2042 # Flag to hide all contents of the archived revisions
2043 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2045 # This code desperately needs to be totally rewritten
2047 # Read-only check...
2048 if ( wfReadOnly() ) {
2049 $wgOut->readOnlyPage();
2054 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2056 if (count($permission_errors)>0) {
2057 $wgOut->showPermissionsErrorPage( $permission_errors );
2061 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2063 # Better double-check that it hasn't been deleted yet!
2064 $dbw = wfGetDB( DB_MASTER
);
2065 $conds = $this->mTitle
->pageCond();
2066 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2067 if ( $latest === false ) {
2068 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2072 # Hack for big sites
2073 $bigHistory = $this->isBigDeletion();
2074 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2075 global $wgLang, $wgDeleteRevisionsLimit;
2076 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2077 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2082 $this->doDelete( $reason, $suppress );
2083 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2085 } elseif( $this->mTitle
->userIsWatching() ) {
2091 // Generate deletion reason
2092 $hasHistory = false;
2093 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2095 // If the page has a history, insert a warning
2096 if( $hasHistory && !$confirm ) {
2097 $skin=$wgUser->getSkin();
2098 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2100 global $wgLang, $wgDeleteRevisionsLimit;
2101 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2102 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2106 return $this->confirmDelete( $reason );
2110 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2112 function isBigDeletion() {
2113 global $wgDeleteRevisionsLimit;
2114 if( $wgDeleteRevisionsLimit ) {
2115 $revCount = $this->estimateRevisionCount();
2116 return $revCount > $wgDeleteRevisionsLimit;
2122 * @return int approximate revision count
2124 function estimateRevisionCount() {
2126 // For an exact count...
2127 //return $dbr->selectField( 'revision', 'COUNT(*)',
2128 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2129 return $dbr->estimateRowCount( 'revision', '*',
2130 array( 'rev_page' => $this->getId() ), __METHOD__
);
2134 * Get the last N authors
2135 * @param int $num Number of revisions to get
2136 * @param string $revLatest The latest rev_id, selected from the master (optional)
2137 * @return array Array of authors, duplicates not removed
2139 function getLastNAuthors( $num, $revLatest = 0 ) {
2140 wfProfileIn( __METHOD__
);
2142 // First try the slave
2143 // If that doesn't have the latest revision, try the master
2145 $db = wfGetDB( DB_SLAVE
);
2147 $res = $db->select( array( 'page', 'revision' ),
2148 array( 'rev_id', 'rev_user_text' ),
2150 'page_namespace' => $this->mTitle
->getNamespace(),
2151 'page_title' => $this->mTitle
->getDBkey(),
2152 'rev_page = page_id'
2153 ), __METHOD__
, $this->getSelectOptions( array(
2154 'ORDER BY' => 'rev_timestamp DESC',
2159 wfProfileOut( __METHOD__
);
2162 $row = $db->fetchObject( $res );
2163 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2164 $db = wfGetDB( DB_MASTER
);
2169 } while ( $continue );
2171 $authors = array( $row->rev_user_text
);
2172 while ( $row = $db->fetchObject( $res ) ) {
2173 $authors[] = $row->rev_user_text
;
2175 wfProfileOut( __METHOD__
);
2180 * Output deletion confirmation dialog
2181 * @param $reason string Prefilled reason
2183 function confirmDelete( $reason ) {
2184 global $wgOut, $wgUser, $wgContLang;
2185 $align = $wgContLang->isRtl() ?
'left' : 'right';
2187 wfDebug( "Article::confirmDelete\n" );
2189 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2190 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2191 $wgOut->addWikiMsg( 'confirmdeletetext' );
2193 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2194 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2195 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2196 $suppress .= "</td></tr>";
2201 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2202 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2203 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2204 Xml
::openElement( 'table' ) .
2205 "<tr id=\"wpDeleteReasonListRow\">
2206 <td align='$align'>" .
2207 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2210 Xml
::listDropDown( 'wpDeleteReasonList',
2211 wfMsgForContent( 'deletereason-dropdown' ),
2212 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2215 <tr id=\"wpDeleteReasonRow\">
2216 <td align='$align'>" .
2217 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2220 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2226 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2233 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2236 Xml
::closeElement( 'table' ) .
2237 Xml
::closeElement( 'fieldset' ) .
2238 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2239 Xml
::closeElement( 'form' );
2241 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2242 $skin = $wgUser->getSkin();
2243 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2244 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2247 $wgOut->addHTML( $form );
2248 $this->showLogExtract( $wgOut );
2253 * Show relevant lines from the deletion log
2255 function showLogExtract( $out ) {
2256 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2257 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2262 * Perform a deletion and output success or failure messages
2264 function doDelete( $reason, $suppress = false ) {
2265 global $wgOut, $wgUser;
2266 wfDebug( __METHOD__
."\n" );
2268 $id = $this->getId();
2272 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error))) {
2273 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2274 $deleted = $this->mTitle
->getPrefixedText();
2276 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2277 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2279 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2281 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2282 $wgOut->returnToMain( false );
2283 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2286 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2288 $wgOut->showFatalError( $error );
2294 * Back-end article deletion
2295 * Deletes the article with database consistency, writes logs, purges caches
2298 function doDeleteArticle( $reason, $suppress = false ) {
2299 global $wgUseSquid, $wgDeferredUpdateList;
2300 global $wgUseTrackbacks;
2302 wfDebug( __METHOD__
."\n" );
2304 $dbw = wfGetDB( DB_MASTER
);
2305 $ns = $this->mTitle
->getNamespace();
2306 $t = $this->mTitle
->getDBkey();
2307 $id = $this->mTitle
->getArticleID();
2309 if ( $t == '' ||
$id == 0 ) {
2313 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2314 array_push( $wgDeferredUpdateList, $u );
2316 // Bitfields to further suppress the content
2319 // This should be 15...
2320 $bitfield |
= Revision
::DELETED_TEXT
;
2321 $bitfield |
= Revision
::DELETED_COMMENT
;
2322 $bitfield |
= Revision
::DELETED_USER
;
2323 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2325 $bitfield = 'rev_deleted';
2329 // For now, shunt the revision data into the archive table.
2330 // Text is *not* removed from the text table; bulk storage
2331 // is left intact to avoid breaking block-compression or
2332 // immutable storage schemes.
2334 // For backwards compatibility, note that some older archive
2335 // table entries will have ar_text and ar_flags fields still.
2337 // In the future, we may keep revisions and mark them with
2338 // the rev_deleted field, which is reserved for this purpose.
2339 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2341 'ar_namespace' => 'page_namespace',
2342 'ar_title' => 'page_title',
2343 'ar_comment' => 'rev_comment',
2344 'ar_user' => 'rev_user',
2345 'ar_user_text' => 'rev_user_text',
2346 'ar_timestamp' => 'rev_timestamp',
2347 'ar_minor_edit' => 'rev_minor_edit',
2348 'ar_rev_id' => 'rev_id',
2349 'ar_text_id' => 'rev_text_id',
2350 'ar_text' => '\'\'', // Be explicit to appease
2351 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2352 'ar_len' => 'rev_len',
2353 'ar_page_id' => 'page_id',
2354 'ar_deleted' => $bitfield
2357 'page_id = rev_page'
2361 # Delete restrictions for it
2362 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2364 # Fix category table counts
2366 $res = $dbw->select( 'categorylinks', 'cl_to',
2367 array( 'cl_from' => $id ), __METHOD__
);
2368 foreach( $res as $row ) {
2369 $cats []= $row->cl_to
;
2371 $this->updateCategoryCounts( array(), $cats );
2373 # Now that it's safely backed up, delete it
2374 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2375 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2381 # If using cascading deletes, we can skip some explicit deletes
2382 if ( !$dbw->cascadingDeletes() ) {
2383 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2385 if ($wgUseTrackbacks)
2386 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2388 # Delete outgoing links
2389 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2390 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2391 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2392 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2393 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2394 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2395 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2398 # If using cleanup triggers, we can skip some manual deletes
2399 if ( !$dbw->cleanupTriggers() ) {
2401 # Clean up recentchanges entries...
2402 $dbw->delete( 'recentchanges',
2403 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2409 Article
::onArticleDelete( $this->mTitle
);
2411 # Clear the cached article id so the interface doesn't act like we exist
2412 $this->mTitle
->resetArticleID( 0 );
2413 $this->mTitle
->mArticleID
= 0;
2415 # Log the deletion, if the page was suppressed, log it at Oversight instead
2416 $logtype = $suppress ?
'suppress' : 'delete';
2417 $log = new LogPage( $logtype );
2419 # Make sure logging got through
2420 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2426 * Roll back the most recent consecutive set of edits to a page
2427 * from the same user; fails if there are no eligible edits to
2428 * roll back to, e.g. user is the sole contributor. This function
2429 * performs permissions checks on $wgUser, then calls commitRollback()
2430 * to do the dirty work
2432 * @param string $fromP - Name of the user whose edits to rollback.
2433 * @param string $summary - Custom summary. Set to default summary if empty.
2434 * @param string $token - Rollback token.
2435 * @param bool $bot - If true, mark all reverted edits as bot.
2437 * @param array $resultDetails contains result-specific array of additional values
2438 * 'alreadyrolled' : 'current' (rev)
2439 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2441 * @return array of errors, each error formatted as
2442 * array(messagekey, param1, param2, ...).
2443 * On success, the array is empty. This array can also be passed to
2444 * OutputPage::showPermissionsErrorPage().
2446 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2448 $resultDetails = null;
2451 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2452 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2453 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2454 $errors[] = array( 'sessionfailure' );
2456 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2457 $errors[] = array( 'actionthrottledtext' );
2459 # If there were errors, bail out now
2463 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2467 * Backend implementation of doRollback(), please refer there for parameter
2468 * and return value documentation
2470 * NOTE: This function does NOT check ANY permissions, it just commits the
2471 * rollback to the DB Therefore, you should only call this function direct-
2472 * ly if you want to use custom permissions checks. If you don't, use
2473 * doRollback() instead.
2475 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2476 global $wgUseRCPatrol, $wgUser, $wgLang;
2477 $dbw = wfGetDB( DB_MASTER
);
2479 if( wfReadOnly() ) {
2480 return array( array( 'readonlytext' ) );
2483 # Get the last editor
2484 $current = Revision
::newFromTitle( $this->mTitle
);
2485 if( is_null( $current ) ) {
2486 # Something wrong... no page?
2487 return array(array('notanarticle'));
2490 $from = str_replace( '_', ' ', $fromP );
2491 if( $from != $current->getUserText() ) {
2492 $resultDetails = array( 'current' => $current );
2493 return array(array('alreadyrolled',
2494 htmlspecialchars($this->mTitle
->getPrefixedText()),
2495 htmlspecialchars($fromP),
2496 htmlspecialchars($current->getUserText())
2500 # Get the last edit not by this guy
2501 $user = intval( $current->getUser() );
2502 $user_text = $dbw->addQuotes( $current->getUserText() );
2503 $s = $dbw->selectRow( 'revision',
2504 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2505 array( 'rev_page' => $current->getPage(),
2506 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2508 array( 'USE INDEX' => 'page_timestamp',
2509 'ORDER BY' => 'rev_timestamp DESC' )
2511 if( $s === false ) {
2512 # No one else ever edited this page
2513 return array(array('cantrollback'));
2514 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2515 # Only admins can see this text
2516 return array(array('notvisiblerev'));
2520 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2521 # Mark all reverted edits as bot
2524 if ( $wgUseRCPatrol ) {
2525 # Mark all reverted edits as patrolled
2526 $set['rc_patrolled'] = 1;
2530 $dbw->update( 'recentchanges', $set,
2532 'rc_cur_id' => $current->getPage(),
2533 'rc_user_text' => $current->getUserText(),
2534 "rc_timestamp > '{$s->rev_timestamp}'",
2539 # Generate the edit summary if necessary
2540 $target = Revision
::newFromId( $s->rev_id
);
2541 if( empty( $summary ) ){
2542 $summary = wfMsgForContent( 'revertpage' );
2545 # Allow the custom summary to use the same args as the default message
2547 $target->getUserText(), $from, $s->rev_id
,
2548 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2549 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2551 $summary = wfMsgReplaceArgs( $summary, $args );
2554 $flags = EDIT_UPDATE
;
2556 if ($wgUser->isAllowed('minoredit'))
2557 $flags |
= EDIT_MINOR
;
2559 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2560 $flags |
= EDIT_FORCE_BOT
;
2561 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2563 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2565 $resultDetails = array(
2566 'summary' => $summary,
2567 'current' => $current,
2568 'target' => $target,
2574 * User interface for rollback operations
2576 function rollback() {
2577 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2580 $result = $this->doRollback(
2581 $wgRequest->getVal( 'from' ),
2582 $wgRequest->getText( 'summary' ),
2583 $wgRequest->getVal( 'token' ),
2584 $wgRequest->getBool( 'bot' ),
2588 if( in_array( array( 'blocked' ), $result ) ) {
2589 $wgOut->blockedPage();
2592 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2593 $wgOut->rateLimited();
2596 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2597 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2598 $errArray = $result[0];
2599 $errMsg = array_shift( $errArray );
2600 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2601 if( isset( $details['current'] ) ){
2602 $current = $details['current'];
2603 if( $current->getComment() != '' ) {
2604 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2609 # Display permissions errors before read-only message -- there's no
2610 # point in misleading the user into thinking the inability to rollback
2611 # is only temporary.
2612 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2613 # array_diff is completely broken for arrays of arrays, sigh. Re-
2614 # move any 'readonlytext' error manually.
2616 foreach( $result as $error ) {
2617 if( $error != array( 'readonlytext' ) ) {
2621 $wgOut->showPermissionsErrorPage( $out );
2624 if( $result == array( array('readonlytext') ) ) {
2625 $wgOut->readOnlyPage();
2629 $current = $details['current'];
2630 $target = $details['target'];
2631 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2632 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2633 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2634 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2635 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2636 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2637 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2638 $wgOut->returnToMain( false, $this->mTitle
);
2640 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2641 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), 'next', false, true );
2642 $de->showDiff( '', '' );
2648 * Do standard deferred updates after page view
2651 function viewUpdates() {
2652 global $wgDeferredUpdateList, $wgUser;
2654 if ( 0 != $this->getID() ) {
2655 # Don't update page view counters on views from bot users (bug 14044)
2656 global $wgDisableCounters;
2657 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2658 Article
::incViewCount( $this->getID() );
2659 $u = new SiteStatsUpdate( 1, 0, 0 );
2660 array_push( $wgDeferredUpdateList, $u );
2664 # Update newtalk / watchlist notification status
2665 $wgUser->clearNotification( $this->mTitle
);
2669 * Prepare text which is about to be saved.
2670 * Returns a stdclass with source, pst and output members
2672 function prepareTextForEdit( $text, $revid=null ) {
2673 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2675 return $this->mPreparedEdit
;
2678 $edit = (object)array();
2679 $edit->revid
= $revid;
2680 $edit->newText
= $text;
2681 $edit->pst
= $this->preSaveTransform( $text );
2682 $options = new ParserOptions
;
2683 $options->setTidy( true );
2684 $options->enableLimitReport();
2685 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2686 $edit->oldText
= $this->getContent();
2687 $this->mPreparedEdit
= $edit;
2692 * Do standard deferred updates after page edit.
2693 * Update links tables, site stats, search index and message cache.
2694 * Every 100th edit, prune the recent changes table.
2697 * @param $text New text of the article
2698 * @param $summary Edit summary
2699 * @param $minoredit Minor edit
2700 * @param $timestamp_of_pagechange Timestamp associated with the page change
2701 * @param $newid rev_id value of the new revision
2702 * @param $changed Whether or not the content actually changed
2704 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2705 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2707 wfProfileIn( __METHOD__
);
2710 # Be careful not to double-PST: $text is usually already PST-ed once
2711 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2712 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2713 $editInfo = $this->prepareTextForEdit( $text, $newid );
2715 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2716 $editInfo = $this->mPreparedEdit
;
2719 # Save it to the parser cache
2720 if ( $wgEnableParserCache ) {
2721 $parserCache = ParserCache
::singleton();
2722 $parserCache->save( $editInfo->output
, $this, $wgUser );
2725 # Update the links tables
2726 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2729 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2730 if ( 0 == mt_rand( 0, 99 ) ) {
2731 // Flush old entries from the `recentchanges` table; we do this on
2732 // random requests so as to avoid an increase in writes for no good reason
2734 $dbw = wfGetDB( DB_MASTER
);
2735 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2736 $recentchanges = $dbw->tableName( 'recentchanges' );
2737 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2738 $dbw->query( $sql );
2742 $id = $this->getID();
2743 $title = $this->mTitle
->getPrefixedDBkey();
2744 $shortTitle = $this->mTitle
->getDBkey();
2747 wfProfileOut( __METHOD__
);
2751 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2752 array_push( $wgDeferredUpdateList, $u );
2753 $u = new SearchUpdate( $id, $title, $text );
2754 array_push( $wgDeferredUpdateList, $u );
2756 # If this is another user's talk page, update newtalk
2757 # Don't do this if $changed = false otherwise some idiot can null-edit a
2758 # load of user talk pages and piss people off, nor if it's a minor edit
2759 # by a properly-flagged bot.
2760 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2761 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2762 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2763 $other = User
::newFromName( $shortTitle, false );
2765 wfDebug( __METHOD__
.": invalid username\n" );
2766 } elseif( User
::isIP( $shortTitle ) ) {
2767 // An anonymous user
2768 $other->setNewtalk( true );
2769 } elseif( $other->isLoggedIn() ) {
2770 $other->setNewtalk( true );
2772 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2777 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2778 $wgMessageCache->replace( $shortTitle, $text );
2781 wfProfileOut( __METHOD__
);
2785 * Perform article updates on a special page creation.
2787 * @param Revision $rev
2789 * @todo This is a shitty interface function. Kill it and replace the
2790 * other shitty functions like editUpdates and such so it's not needed
2793 function createUpdates( $rev ) {
2794 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2795 $this->mTotalAdjustment
= 1;
2796 $this->editUpdates( $rev->getText(), $rev->getComment(),
2797 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2801 * Generate the navigation links when browsing through an article revisions
2802 * It shows the information as:
2803 * Revision as of \<date\>; view current revision
2804 * \<- Previous version | Next Version -\>
2807 * @param string $oldid Revision ID of this article revision
2809 function setOldSubtitle( $oldid=0 ) {
2810 global $wgLang, $wgOut, $wgUser;
2812 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2816 $revision = Revision
::newFromId( $oldid );
2818 $current = ( $oldid == $this->mLatest
);
2819 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2820 $sk = $wgUser->getSkin();
2822 ?
wfMsg( 'currentrevisionlink' )
2823 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2826 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2827 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2829 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2830 : wfMsg( 'previousrevision' );
2832 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2834 $nextlink = $current
2835 ?
wfMsg( 'nextrevision' )
2836 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2837 $nextdiff = $current
2839 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2842 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2843 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2844 if( $revision->isCurrent() ) {
2845 // We don't handle top deleted edits too well
2846 $cdel = wfMsgHtml('rev-delundel');
2847 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2848 // If revision was hidden from sysops
2849 $cdel = wfMsgHtml('rev-delundel');
2851 $cdel = $sk->makeKnownLinkObj( $revdel,
2852 wfMsgHtml('rev-delundel'),
2853 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2854 '&oldid=' . urlencode( $oldid ) );
2855 // Bolden oversighted content
2856 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2857 $cdel = "<strong>$cdel</strong>";
2859 $cdel = "(<small>$cdel</small>) ";
2861 # Show user links if allowed to see them. Normally they
2862 # are hidden regardless, but since we can already see the text here...
2863 $userlinks = $sk->revUserTools( $revision, false );
2865 $m = wfMsg( 'revision-info-current' );
2866 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2867 ?
'revision-info-current'
2870 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2872 "\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";
2873 $wgOut->setSubtitle( $r );
2877 * This function is called right before saving the wikitext,
2878 * so we can do things like signatures and links-in-context.
2880 * @param string $text
2882 function preSaveTransform( $text ) {
2883 global $wgParser, $wgUser;
2884 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2887 /* Caching functions */
2890 * checkLastModified returns true if it has taken care of all
2891 * output to the client that is necessary for this request.
2892 * (that is, it has sent a cached version of the page)
2894 function tryFileCache() {
2895 static $called = false;
2897 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2901 if($this->isFileCacheable()) {
2902 $touched = $this->mTouched
;
2903 $cache = new HTMLFileCache( $this->mTitle
);
2904 if($cache->isFileCacheGood( $touched )) {
2905 wfDebug( "Article::tryFileCache(): about to load file\n" );
2906 $cache->loadFromFileCache();
2909 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2910 ob_start( array(&$cache, 'saveToFileCache' ) );
2913 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2918 * Check if the page can be cached
2921 function isFileCacheable() {
2922 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2923 $action = $wgRequest->getVal( 'action' );
2924 $oldid = $wgRequest->getVal( 'oldid' );
2925 $diff = $wgRequest->getVal( 'diff' );
2926 $redirect = $wgRequest->getVal( 'redirect' );
2927 $printable = $wgRequest->getVal( 'printable' );
2928 $page = $wgRequest->getVal( 'page' );
2929 $useskin = $wgRequest->getVal( 'useskin' );
2931 //check for non-standard user language; this covers uselang,
2932 //and extensions for auto-detecting user language.
2933 $ulang = $wgLang->getCode();
2934 $clang = $wgContLang->getCode();
2936 $cacheable = $wgUseFileCache
2937 && (!$wgShowIPinHeader)
2938 && ($this->getID() != 0)
2939 && ($wgUser->isAnon())
2940 && (!$wgUser->getNewtalk())
2941 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2942 && (!isset($useskin))
2943 && (empty( $action ) ||
$action == 'view')
2946 && (!isset($redirect))
2947 && (!isset($printable))
2949 && (!$this->mRedirectedFrom
)
2950 && ($ulang === $clang);
2953 //extension may have reason to disable file caching on some pages.
2954 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
2961 * Loads page_touched and returns a value indicating if it should be used
2964 function checkTouched() {
2965 if( !$this->mDataLoaded
) {
2966 $this->loadPageData();
2968 return !$this->mIsRedirect
;
2972 * Get the page_touched field
2974 function getTouched() {
2975 # Ensure that page data has been loaded
2976 if( !$this->mDataLoaded
) {
2977 $this->loadPageData();
2979 return $this->mTouched
;
2983 * Get the page_latest field
2985 function getLatest() {
2986 if ( !$this->mDataLoaded
) {
2987 $this->loadPageData();
2989 return $this->mLatest
;
2993 * Edit an article without doing all that other stuff
2994 * The article must already exist; link tables etc
2995 * are not updated, caches are not flushed.
2997 * @param string $text text submitted
2998 * @param string $comment comment submitted
2999 * @param bool $minor whereas it's a minor modification
3001 function quickEdit( $text, $comment = '', $minor = 0 ) {
3002 wfProfileIn( __METHOD__
);
3004 $dbw = wfGetDB( DB_MASTER
);
3006 $revision = new Revision( array(
3007 'page' => $this->getId(),
3009 'comment' => $comment,
3010 'minor_edit' => $minor ?
1 : 0,
3012 $revision->insertOn( $dbw );
3013 $this->updateRevisionOn( $dbw, $revision );
3016 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3018 wfProfileOut( __METHOD__
);
3022 * Used to increment the view counter
3025 * @param integer $id article id
3027 function incViewCount( $id ) {
3028 $id = intval( $id );
3029 global $wgHitcounterUpdateFreq, $wgDBtype;
3031 $dbw = wfGetDB( DB_MASTER
);
3032 $pageTable = $dbw->tableName( 'page' );
3033 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3034 $acchitsTable = $dbw->tableName( 'acchits' );
3036 if( $wgHitcounterUpdateFreq <= 1 ) {
3037 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3041 # Not important enough to warrant an error page in case of failure
3042 $oldignore = $dbw->ignoreErrors( true );
3044 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3046 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3047 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3048 # Most of the time (or on SQL errors), skip row count check
3049 $dbw->ignoreErrors( $oldignore );
3053 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3054 $row = $dbw->fetchObject( $res );
3055 $rown = intval( $row->n
);
3056 if( $rown >= $wgHitcounterUpdateFreq ){
3057 wfProfileIn( 'Article::incViewCount-collect' );
3058 $old_user_abort = ignore_user_abort( true );
3060 if ($wgDBtype == 'mysql')
3061 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3062 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3063 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3064 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3066 $dbw->query("DELETE FROM $hitcounterTable");
3067 if ($wgDBtype == 'mysql') {
3068 $dbw->query('UNLOCK TABLES');
3069 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3070 'WHERE page_id = hc_id');
3073 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3074 "FROM $acchitsTable WHERE page_id = hc_id");
3076 $dbw->query("DROP TABLE $acchitsTable");
3078 ignore_user_abort( $old_user_abort );
3079 wfProfileOut( 'Article::incViewCount-collect' );
3081 $dbw->ignoreErrors( $oldignore );
3085 * The onArticle*() functions are supposed to be a kind of hooks
3086 * which should be called whenever any of the specified actions
3089 * This is a good place to put code to clear caches, for instance.
3091 * This is called on page move and undelete, as well as edit
3093 * @param $title_obj a title object
3096 static function onArticleCreate($title) {
3097 # The talk page isn't in the regular link tables, so we need to update manually:
3098 if ( $title->isTalkPage() ) {
3099 $other = $title->getSubjectPage();
3101 $other = $title->getTalkPage();
3103 $other->invalidateCache();
3104 $other->purgeSquid();
3106 $title->touchLinks();
3107 $title->purgeSquid();
3108 $title->deleteTitleProtection();
3111 static function onArticleDelete( $title ) {
3112 global $wgUseFileCache, $wgMessageCache;
3114 // Update existence markers on article/talk tabs...
3115 if( $title->isTalkPage() ) {
3116 $other = $title->getSubjectPage();
3118 $other = $title->getTalkPage();
3120 $other->invalidateCache();
3121 $other->purgeSquid();
3123 $title->touchLinks();
3124 $title->purgeSquid();
3127 if ( $wgUseFileCache ) {
3128 $cm = new HTMLFileCache( $title );
3129 @unlink
( $cm->fileCacheName() );
3133 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3134 $wgMessageCache->replace( $title->getDBkey(), false );
3137 if( $title->getNamespace() == NS_IMAGE
) {
3138 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3139 $update->doUpdate();
3142 if( $title->getNamespace() == NS_USER_TALK
) {
3143 $user = User
::newFromName( $title->getText(), false );
3144 $user->setNewtalk( false );
3149 * Purge caches on page update etc
3151 static function onArticleEdit( $title ) {
3152 global $wgDeferredUpdateList, $wgUseFileCache;
3154 // Invalidate caches of articles which include this page
3155 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3157 // Invalidate the caches of all pages which redirect here
3158 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3160 # Purge squid for this page only
3161 $title->purgeSquid();
3164 if ( $wgUseFileCache ) {
3165 $cm = new HTMLFileCache( $title );
3166 @unlink
( $cm->fileCacheName() );
3173 * Overriden by ImagePage class, only present here to avoid a fatal error
3174 * Called for ?action=revert
3176 public function revert(){
3178 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3182 * Info about this page
3183 * Called for ?action=info when $wgAllowPageInfo is on.
3188 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3190 if ( !$wgAllowPageInfo ) {
3191 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3195 $page = $this->mTitle
->getSubjectPage();
3197 $wgOut->setPagetitle( $page->getPrefixedText() );
3198 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3199 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3201 if( !$this->mTitle
->exists() ) {
3202 $wgOut->addHtml( '<div class="noarticletext">' );
3203 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3204 // This doesn't quite make sense; the user is asking for
3205 // information about the _page_, not the message... -- RC
3206 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3208 $msg = $wgUser->isLoggedIn()
3210 : 'noarticletextanon';
3211 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3213 $wgOut->addHtml( '</div>' );
3215 $dbr = wfGetDB( DB_SLAVE
);
3217 'wl_title' => $page->getDBkey(),
3218 'wl_namespace' => $page->getNamespace() );
3219 $numwatchers = $dbr->selectField(
3224 $this->getSelectOptions() );
3226 $pageInfo = $this->pageCountInfo( $page );
3227 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3229 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3230 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3232 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3234 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3236 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3238 $wgOut->addHTML( '</ul>' );
3244 * Return the total number of edits and number of unique editors
3245 * on a given page. If page does not exist, returns false.
3247 * @param Title $title
3251 function pageCountInfo( $title ) {
3252 $id = $title->getArticleId();
3257 $dbr = wfGetDB( DB_SLAVE
);
3259 $rev_clause = array( 'rev_page' => $id );
3261 $edits = $dbr->selectField(
3266 $this->getSelectOptions() );
3268 $authors = $dbr->selectField(
3270 'COUNT(DISTINCT rev_user_text)',
3273 $this->getSelectOptions() );
3275 return array( 'edits' => $edits, 'authors' => $authors );
3279 * Return a list of templates used by this article.
3280 * Uses the templatelinks table
3282 * @return array Array of Title objects
3284 function getUsedTemplates() {
3286 $id = $this->mTitle
->getArticleID();
3291 $dbr = wfGetDB( DB_SLAVE
);
3292 $res = $dbr->select( array( 'templatelinks' ),
3293 array( 'tl_namespace', 'tl_title' ),
3294 array( 'tl_from' => $id ),
3296 if( false !== $res ) {
3297 foreach( $res as $row ) {
3298 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3301 $dbr->freeResult( $res );
3306 * Returns a list of hidden categories this page is a member of.
3307 * Uses the page_props and categorylinks tables.
3309 * @return array Array of Title objects
3311 function getHiddenCategories() {
3313 $id = $this->mTitle
->getArticleID();
3318 $dbr = wfGetDB( DB_SLAVE
);
3319 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3321 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3322 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3324 if ( false !== $res ) {
3325 foreach( $res as $row ) {
3326 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3329 $dbr->freeResult( $res );
3334 * Return an applicable autosummary if one exists for the given edit.
3335 * @param string $oldtext The previous text of the page.
3336 * @param string $newtext The submitted text of the page.
3337 * @param bitmask $flags A bitmask of flags submitted for the edit.
3338 * @return string An appropriate autosummary, or an empty string.
3340 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3341 # Decide what kind of autosummary is needed.
3343 # Redirect autosummaries
3344 $rt = Title
::newFromRedirect( $newtext );
3345 if( is_object( $rt ) ) {
3346 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3349 # New page autosummaries
3350 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3351 # If they're making a new article, give its text, truncated, in the summary.
3353 $truncatedtext = $wgContLang->truncate(
3354 str_replace("\n", ' ', $newtext),
3355 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3357 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3360 # Blanking autosummaries
3361 if( $oldtext != '' && $newtext == '' ) {
3362 return wfMsgForContent('autosumm-blank');
3363 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3364 # Removing more than 90% of the article
3366 $truncatedtext = $wgContLang->truncate(
3368 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3371 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3374 # If we reach this point, there's no applicable autosummary for our case, so our
3375 # autosummary is empty.
3380 * Add the primary page-view wikitext to the output buffer
3381 * Saves the text into the parser cache if possible.
3382 * Updates templatelinks if it is out of date.
3384 * @param string $text
3385 * @param bool $cache
3387 public function outputWikiText( $text, $cache = true ) {
3388 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3390 $popts = $wgOut->parserOptions();
3391 $popts->setTidy(true);
3392 $popts->enableLimitReport();
3393 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3394 $popts, true, true, $this->getRevIdFetched() );
3395 $popts->setTidy(false);
3396 $popts->enableLimitReport( false );
3397 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3398 $parserCache = ParserCache
::singleton();
3399 $parserCache->save( $parserOutput, $this, $wgUser );
3402 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3403 // templatelinks table may have become out of sync,
3404 // especially if using variable-based transclusions.
3405 // For paranoia, check if things have changed and if
3406 // so apply updates to the database. This will ensure
3407 // that cascaded protections apply as soon as the changes
3410 # Get templates from templatelinks
3411 $id = $this->mTitle
->getArticleID();
3413 $tlTemplates = array();
3415 $dbr = wfGetDB( DB_SLAVE
);
3416 $res = $dbr->select( array( 'templatelinks' ),
3417 array( 'tl_namespace', 'tl_title' ),
3418 array( 'tl_from' => $id ),
3423 if ( false !== $res ) {
3424 foreach( $res as $row ) {
3425 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3429 # Get templates from parser output.
3430 $poTemplates_allns = $parserOutput->getTemplates();
3432 $poTemplates = array ();
3433 foreach ( $poTemplates_allns as $ns_templates ) {
3434 $poTemplates = array_merge( $poTemplates, $ns_templates );
3438 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3440 if ( count( $templates_diff ) > 0 ) {
3441 # Whee, link updates time.
3442 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3444 $dbw = wfGetDb( DB_MASTER
);
3453 $wgOut->addParserOutput( $parserOutput );
3457 * Update all the appropriate counts in the category table, given that
3458 * we've added the categories $added and deleted the categories $deleted.
3460 * @param $added array The names of categories that were added
3461 * @param $deleted array The names of categories that were deleted
3464 public function updateCategoryCounts( $added, $deleted ) {
3465 $ns = $this->mTitle
->getNamespace();
3466 $dbw = wfGetDB( DB_MASTER
);
3468 # First make sure the rows exist. If one of the "deleted" ones didn't
3469 # exist, we might legitimately not create it, but it's simpler to just
3470 # create it and then give it a negative value, since the value is bogus
3473 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3474 $insertCats = array_merge( $added, $deleted );
3475 if( !$insertCats ) {
3476 # Okay, nothing to do
3479 $insertRows = array();
3480 foreach( $insertCats as $cat ) {
3481 $insertRows[] = array( 'cat_title' => $cat );
3483 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3485 $addFields = array( 'cat_pages = cat_pages + 1' );
3486 $removeFields = array( 'cat_pages = cat_pages - 1' );
3487 if( $ns == NS_CATEGORY
) {
3488 $addFields[] = 'cat_subcats = cat_subcats + 1';
3489 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3490 } elseif( $ns == NS_IMAGE
) {
3491 $addFields[] = 'cat_files = cat_files + 1';
3492 $removeFields[] = 'cat_files = cat_files - 1';
3499 array( 'cat_title' => $added ),
3507 array( 'cat_title' => $deleted ),