8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
19 var $mComment = ''; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
37 var $mTimestamp = ''; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
46 * Constructor and clear the article
47 * @param $title Reference to a Title object.
48 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 public function __construct( Title
$title, $oldId = null ) {
51 $this->mTitle
=& $title;
52 $this->mOldId
= $oldId;
56 * Constructor from an article article
57 * @param $id The article ID to load
59 public static function newFromID( $id ) {
60 $t = Title
::newFromID( $id );
61 return $t == null ?
null : new Article( $t );
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
69 public function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom
= $from;
74 * If this page is a redirect, get its target
76 * The target will be fetched from the redirect table if possible.
77 * If this page doesn't have an entry there, call insertRedirect()
78 * @return mixed Title object, or null if this page is not a redirect
80 public function getRedirectTarget() {
81 if( !$this->mTitle ||
!$this->mTitle
->isRedirect() )
83 if( !is_null($this->mRedirectTarget
) )
84 return $this->mRedirectTarget
;
85 # Query the redirect table
86 $dbr = wfGetDB( DB_SLAVE
);
87 $res = $dbr->select( 'redirect',
88 array('rd_namespace', 'rd_title'),
89 array('rd_from' => $this->getID()),
92 if( $row = $dbr->fetchObject($res) ) {
93 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
95 # This page doesn't have an entry in the redirect table
96 return $this->mRedirectTarget
= $this->insertRedirect();
100 * Insert an entry for this page into the redirect table.
102 * Don't call this function directly unless you know what you're doing.
103 * @return Title object
105 public function insertRedirect() {
106 $retval = Title
::newFromRedirect( $this->getContent() );
110 $dbw = wfGetDB( DB_MASTER
);
111 $dbw->replace( 'redirect', array('rd_from'),
113 'rd_from' => $this->getID(),
114 'rd_namespace' => $retval->getNamespace(),
115 'rd_title' => $retval->getDBKey()
123 * Get the Title object this page redirects to
125 * @return mixed false, Title of in-wiki target, or string with URL
127 public function followRedirect() {
128 $text = $this->getContent();
129 return $this->followRedirectText( $text );
133 * Get the Title object this text redirects to
135 * @return mixed false, Title of in-wiki target, or string with URL
137 public function followRedirectText( $text ) {
138 $rt = Title
::newFromRedirect( $text );
139 # process if title object is valid and not special:userlogout
141 if( $rt->getInterwiki() != '' ) {
142 if( $rt->isLocal() ) {
143 // Offsite wikis need an HTTP redirect.
145 // This can be hard to reverse and may produce loops,
146 // so they may be disabled in the site configuration.
147 $source = $this->mTitle
->getFullURL( 'redirect=no' );
148 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
151 if( $rt->getNamespace() == NS_SPECIAL
) {
152 // Gotta handle redirects to special pages differently:
153 // Fill the HTTP response "Location" header and ignore
154 // the rest of the page we're on.
156 // This can be hard to reverse, so they may be disabled.
157 if( $rt->isSpecial( 'Userlogout' ) ) {
160 return $rt->getFullURL();
166 // No or invalid redirect
171 * get the title object of the article
173 public function getTitle() {
174 return $this->mTitle
;
181 public function clear() {
182 $this->mDataLoaded
= false;
183 $this->mContentLoaded
= false;
185 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
186 $this->mRedirectedFrom
= null; # Title object if set
187 $this->mRedirectTarget
= null; # Title object if set
189 $this->mTimestamp
= $this->mComment
= '';
190 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
191 $this->mTouched
= '19700101000000';
192 $this->mForUpdate
= false;
193 $this->mIsRedirect
= false;
194 $this->mRevIdFetched
= 0;
195 $this->mRedirectUrl
= false;
196 $this->mLatest
= false;
197 $this->mPreparedEdit
= false;
201 * Note that getContent/loadContent do not follow redirects anymore.
202 * If you need to fetch redirectable content easily, try
203 * the shortcut in Article::followContent()
205 * @return Return the text of this revision
207 public function getContent() {
208 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
209 wfProfileIn( __METHOD__
);
210 if( $this->getID() === 0 ) {
211 # If this is a MediaWiki:x message, then load the messages
212 # and return the message value for x.
213 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
214 # If this is a system message, get the default text.
215 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
216 $wgMessageCache->loadAllMessages( $lang );
217 $text = wfMsgGetKey( $message, false, $lang, false );
218 if( wfEmptyMsg( $message, $text ) )
221 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
223 wfProfileOut( __METHOD__
);
226 $this->loadContent();
227 wfProfileOut( __METHOD__
);
228 return $this->mContent
;
233 * Get the text of the current revision. No side-effects...
235 * @return Return the text of the current revision
237 public function getRawText() {
238 // Check process cache for current revision
239 if( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
240 return $this->mContent
;
242 $rev = Revision
::newFromTitle( $this->mTitle
);
243 $text = $rev ?
$rev->getRawText() : false;
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 public 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 public 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 );
307 * Load the revision (including text) into this object
309 function loadContent() {
310 if( $this->mContentLoaded
) return;
311 wfProfileIn( __METHOD__
);
313 $oldid = $this->getOldID();
314 # Pre-fill content with error message so that if something
315 # fails we'll have something telling us what we intended.
316 $this->mOldId
= $oldid;
317 $this->fetchContent( $oldid );
318 wfProfileOut( __METHOD__
);
323 * Fetch a page record with the given conditions
324 * @param $dbr Database object
325 * @param $conditions Array
327 protected function pageData( $dbr, $conditions ) {
341 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
342 $row = $dbr->selectRow(
348 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
353 * @param $dbr Database object
354 * @param $title Title object
356 public function pageDataFromTitle( $dbr, $title ) {
357 return $this->pageData( $dbr, array(
358 'page_namespace' => $title->getNamespace(),
359 'page_title' => $title->getDBkey() ) );
363 * @param $dbr Database
366 protected function pageDataFromId( $dbr, $id ) {
367 return $this->pageData( $dbr, array( 'page_id' => $id ) );
371 * Set the general counter, title etc data loaded from
374 * @param $data Database row object or "fromdb"
376 public function loadPageData( $data = 'fromdb' ) {
377 if( $data === 'fromdb' ) {
378 $dbr = wfGetDB( DB_MASTER
);
379 $data = $this->pageDataFromId( $dbr, $this->getId() );
382 $lc = LinkCache
::singleton();
384 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
386 $this->mTitle
->mArticleID
= $data->page_id
;
388 # Old-fashioned restrictions
389 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
391 $this->mCounter
= $data->page_counter
;
392 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
393 $this->mIsRedirect
= $data->page_is_redirect
;
394 $this->mLatest
= $data->page_latest
;
396 if( is_object( $this->mTitle
) ) {
397 $lc->addBadLinkObj( $this->mTitle
);
399 $this->mTitle
->mArticleID
= 0;
402 $this->mDataLoaded
= true;
406 * Get text of an article from database
407 * Does *NOT* follow redirects.
408 * @param $oldid Int: 0 for whatever the latest revision is
411 function fetchContent( $oldid = 0 ) {
412 if( $this->mContentLoaded
) {
413 return $this->mContent
;
416 $dbr = wfGetDB( DB_MASTER
);
418 # Pre-fill content with error message so that if something
419 # fails we'll have something telling us what we intended.
420 $t = $this->mTitle
->getPrefixedText();
421 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
422 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
425 $revision = Revision
::newFromId( $oldid );
426 if( is_null( $revision ) ) {
427 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
430 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
432 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
435 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
436 $this->loadPageData( $data );
438 if( !$this->mDataLoaded
) {
439 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
441 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
444 $this->loadPageData( $data );
446 $revision = Revision
::newFromId( $this->mLatest
);
447 if( is_null( $revision ) ) {
448 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
453 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
454 // We should instead work with the Revision object when we need it...
455 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
457 $this->mUser
= $revision->getUser();
458 $this->mUserText
= $revision->getUserText();
459 $this->mComment
= $revision->getComment();
460 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
462 $this->mRevIdFetched
= $revision->getId();
463 $this->mContentLoaded
= true;
464 $this->mRevision
=& $revision;
466 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
468 return $this->mContent
;
472 * Read/write accessor to select FOR UPDATE
474 * @param $x Mixed: FIXME
476 public function forUpdate( $x = NULL ) {
477 return wfSetVar( $this->mForUpdate
, $x );
481 * Get the database which should be used for reads
484 * @deprecated - just call wfGetDB( DB_MASTER ) instead
487 wfDeprecated( __METHOD__
);
488 return wfGetDB( DB_MASTER
);
492 * Get options for all SELECT statements
494 * @param $options Array: an optional options array which'll be appended to
496 * @return Array: options
498 protected function getSelectOptions( $options = '' ) {
499 if( $this->mForUpdate
) {
500 if( is_array( $options ) ) {
501 $options[] = 'FOR UPDATE';
503 $options = 'FOR UPDATE';
510 * @return int Page ID
512 public function getID() {
513 if( $this->mTitle
) {
514 return $this->mTitle
->getArticleID();
521 * @return bool Whether or not the page exists in the database
523 public function exists() {
524 return $this->getId() > 0;
528 * Check if this page is something we're going to be showing
529 * some sort of sensible content for. If we return false, page
530 * views (plain action=view) will return an HTTP 404 response,
531 * so spiders and robots can know they're following a bad link.
535 public function hasViewableContent() {
536 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
540 * @return int The view count for the page
542 public function getCount() {
543 if( -1 == $this->mCounter
) {
544 $id = $this->getID();
548 $dbr = wfGetDB( DB_SLAVE
);
549 $this->mCounter
= $dbr->selectField( 'page',
551 array( 'page_id' => $id ),
553 $this->getSelectOptions()
557 return $this->mCounter
;
561 * Determine whether a page would be suitable for being counted as an
562 * article in the site_stats table based on the title & its content
564 * @param $text String: text to analyze
567 public function isCountable( $text ) {
568 global $wgUseCommaCount;
570 $token = $wgUseCommaCount ?
',' : '[[';
571 return $this->mTitle
->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
575 * Tests if the article text represents a redirect
577 * @param $text String: FIXME
580 public function isRedirect( $text = false ) {
581 if( $text === false ) {
582 if( $this->mDataLoaded
) {
583 return $this->mIsRedirect
;
585 // Apparently loadPageData was never called
586 $this->loadContent();
587 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
589 $titleObj = Title
::newFromRedirect( $text );
591 return $titleObj !== NULL;
595 * Returns true if the currently-referenced revision is the current edit
596 * to this page (and it exists).
599 public function isCurrent() {
600 # If no oldid, this is the current version.
601 if( $this->getOldID() == 0 ) {
604 return $this->exists() && isset($this->mRevision
) && $this->mRevision
->isCurrent();
608 * Loads everything except the text
609 * This isn't necessary for all uses, so it's only done if needed.
611 protected function loadLastEdit() {
612 if( -1 != $this->mUser
)
615 # New or non-existent articles have no user information
616 $id = $this->getID();
617 if( 0 == $id ) return;
619 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
620 if( !is_null( $this->mLastRevision
) ) {
621 $this->mUser
= $this->mLastRevision
->getUser();
622 $this->mUserText
= $this->mLastRevision
->getUserText();
623 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
624 $this->mComment
= $this->mLastRevision
->getComment();
625 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
626 $this->mRevIdFetched
= $this->mLastRevision
->getId();
630 public function getTimestamp() {
631 // Check if the field has been filled by ParserCache::get()
632 if( !$this->mTimestamp
) {
633 $this->loadLastEdit();
635 return wfTimestamp(TS_MW
, $this->mTimestamp
);
638 public function getUser() {
639 $this->loadLastEdit();
643 public function getUserText() {
644 $this->loadLastEdit();
645 return $this->mUserText
;
648 public function getComment() {
649 $this->loadLastEdit();
650 return $this->mComment
;
653 public function getMinorEdit() {
654 $this->loadLastEdit();
655 return $this->mMinorEdit
;
658 /* Use this to fetch the rev ID used on page views */
659 public function getRevIdFetched() {
660 $this->loadLastEdit();
661 return $this->mRevIdFetched
;
665 * @param $limit Integer: default 0.
666 * @param $offset Integer: default 0.
668 public function getContributors($limit = 0, $offset = 0) {
669 # XXX: this is expensive; cache this info somewhere.
672 $dbr = wfGetDB( DB_SLAVE
);
673 $revTable = $dbr->tableName( 'revision' );
674 $userTable = $dbr->tableName( 'user' );
675 $user = $this->getUser();
676 $pageId = $this->getId();
678 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
679 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
680 WHERE rev_page = $pageId
681 AND rev_user != $user
682 GROUP BY rev_user, rev_user_text, user_real_name
683 ORDER BY timestamp DESC";
685 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
686 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
688 $sql .= ' '. $this->getSelectOptions();
690 $res = $dbr->query($sql, __METHOD__
);
692 return new UserArrayFromResult( $res );
696 * This is the default action of the script: just view the page of
699 public function view() {
700 global $wgUser, $wgOut, $wgRequest, $wgContLang;
701 global $wgEnableParserCache, $wgStylePath, $wgParser;
702 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
703 global $wgDefaultRobotPolicy;
705 wfProfileIn( __METHOD__
);
707 # Get variables from query string
708 $oldid = $this->getOldID();
711 if( $oldid === 0 && $this->checkTouched() ) {
714 $parserCache = ParserCache
::singleton();
715 $wgOut->setETag( $parserCache->getETag($this,$wgUser) );
717 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
718 wfProfileOut( __METHOD__
);
720 } else if( $this->tryFileCache() ) {
721 # tell wgOut that output is taken care of
723 $this->viewUpdates();
724 wfProfileOut( __METHOD__
);
729 $ns = $this->mTitle
->getNamespace(); # shortcut
730 $sk = $wgUser->getSkin();
732 # getOldID may want us to redirect somewhere else
733 if( $this->mRedirectUrl
) {
734 $wgOut->redirect( $this->mRedirectUrl
);
735 wfProfileOut( __METHOD__
);
739 $diff = $wgRequest->getVal( 'diff' );
740 $rcid = $wgRequest->getVal( 'rcid' );
741 $rdfrom = $wgRequest->getVal( 'rdfrom' );
742 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
743 $purge = $wgRequest->getVal( 'action' ) == 'purge';
746 $wgOut->setArticleFlag( true );
748 # Discourage indexing of printable versions, but encourage following
749 if( $wgOut->isPrintable() ) {
750 $policy = 'noindex,follow';
751 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
752 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
753 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
754 # Honour customised robot policies for this namespace
755 $policy = $wgNamespaceRobotPolicies[$ns];
757 $policy = $wgDefaultRobotPolicy;
759 $wgOut->setRobotPolicy( $policy );
761 # If we got diff and oldid in the query, we want to see a
762 # diff page instead of the article.
764 if( !is_null( $diff ) ) {
765 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
767 $diff = $wgRequest->getVal( 'diff' );
768 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
769 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff);
770 // DifferenceEngine directly fetched the revision:
771 $this->mRevIdFetched
= $de->mNewid
;
772 $de->showDiffPage( $diffOnly );
774 // Needed to get the page's current revision
775 $this->loadPageData();
776 if( $diff == 0 ||
$diff == $this->mLatest
) {
777 # Run view updates for current revision only
778 $this->viewUpdates();
780 wfProfileOut( __METHOD__
);
784 # Should the parser cache be used?
785 $pcache = $this->useParserCache( $oldid );
786 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
787 if( $wgUser->getOption( 'stubthreshold' ) ) {
788 wfIncrStats( 'pcache_miss_stub' );
791 $wasRedirected = false;
792 if( isset( $this->mRedirectedFrom
) ) {
793 // This is an internally redirected page view.
794 // We'll need a backlink to the source page for navigation.
795 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
796 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
797 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
798 $wgOut->setSubtitle( $s );
800 // Set the fragment if one was specified in the redirect
801 if( strval( $this->mTitle
->getFragment() ) != '' ) {
802 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
803 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
805 $wasRedirected = true;
807 } elseif( !empty( $rdfrom ) ) {
808 // This is an externally redirected view, from some other wiki.
809 // If it was reported from a trusted site, supply a backlink.
810 global $wgRedirectSources;
811 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
812 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
813 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
814 $wgOut->setSubtitle( $s );
815 $wasRedirected = true;
820 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
821 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
822 // Ensure that UI elements requiring revision ID have
823 // the correct version information.
824 $wgOut->setRevisionId( $this->mLatest
);
827 # Fetch content and check for errors
829 # If the article does not exist and was deleted, show the log
830 if( $this->getID() == 0 ) {
831 $this->showDeletionLog();
833 $text = $this->getContent();
834 // For now, check also for ID until getContent actually returns
835 // false for pages that do not exists
836 if( $text === false ||
$this->getID() === 0 ) {
837 # Failed to load, replace text with error message
838 $t = $this->mTitle
->getPrefixedText();
840 $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
841 $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
843 $text = wfMsgExt( 'noarticletext', 'parsemag' );
848 if( $this->getID() === 0 ) {
849 $wgOut->setRobotPolicy( 'noindex,nofollow' );
850 $text = "<div class='noarticletext'>\n$text\n</div>";
851 if( !$this->hasViewableContent() ) {
852 // If there's no backing content, send a 404 Not Found
853 // for better machine handling of broken links.
859 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
862 # Another whitelist check in case oldid is altering the title
863 if( !$this->mTitle
->userCanRead() ) {
864 $wgOut->loginToUse();
867 wfProfileOut( __METHOD__
);
871 # For ?curid=x urls, disallow indexing
872 if( $wgRequest->getInt('curid') )
873 $wgOut->setRobotPolicy( 'noindex,follow' );
875 # We're looking at an old revision
876 if( !empty( $oldid ) ) {
877 $wgOut->setRobotPolicy( 'noindex,nofollow' );
878 if( is_null( $this->mRevision
) ) {
879 // FIXME: This would be a nice place to load the 'no such page' text.
881 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
882 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
883 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
884 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
885 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
886 wfProfileOut( __METHOD__
);
889 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
890 // and we are allowed to see...
896 $wgOut->setRevisionId( $this->getRevIdFetched() );
898 // Pages containing custom CSS or JavaScript get special treatment
899 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
900 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
901 // Give hooks a chance to customise the output
902 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
903 // Wrap the whole lot in a <pre> and don't parse
905 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
906 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
907 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
908 $wgOut->addHTML( "\n</pre>\n" );
910 } else if( $rt = Title
::newFromRedirect( $text ) ) {
911 # Don't append the subtitle if this was an old revision
912 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
913 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
914 $wgOut->addParserOutputNoText( $parseout );
915 } else if( $pcache ) {
916 # Display content and save to parser cache
917 $this->outputWikiText( $text );
919 # Display content, don't attempt to save to parser cache
920 # Don't show section-edit links on old revisions... this way lies madness.
921 if( !$this->isCurrent() ) {
922 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
924 # Display content and don't save to parser cache
925 # With timing hack -- TS 2006-07-26
927 $this->outputWikiText( $text, false );
932 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
933 $this->mTitle
->getPrefixedDBkey()));
936 if( !$this->isCurrent() ) {
937 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
941 /* title may have been set from the cache */
942 $t = $wgOut->getPageTitle();
944 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
946 # For the main page, overwrite the <title> element with the con-
947 # tents of 'pagetitle-view-mainpage' instead of the default (if
949 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
950 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
951 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
955 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
956 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
957 $wgOut->addWikiMsg('anontalkpagetext');
960 # If we have been passed an &rcid= parameter, we want to give the user a
961 # chance to mark this new article as patrolled.
962 if( !empty($rcid) && $this->mTitle
->exists() && $this->mTitle
->userCan('patrol') ) {
964 "<div class='patrollink'>" .
965 wfMsgHtml( 'markaspatrolledlink',
966 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
967 "action=markpatrolled&rcid=$rcid" )
974 if( $wgUseTrackbacks ) {
975 $this->addTrackbacks();
978 $this->viewUpdates();
979 wfProfileOut( __METHOD__
);
982 protected function showDeletionLog() {
983 global $wgUser, $wgOut;
984 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
985 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
986 if( $pager->getNumRows() > 0 ) {
988 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
989 $wgOut->addWikiMsg( 'deleted-notice' );
991 $loglist->beginLogEventsList() .
993 $loglist->endLogEventsList()
995 if( $pager->getNumRows() > 10 ) {
996 $wgOut->addHTML( $wgUser->getSkin()->link(
997 SpecialPage
::getTitleFor( 'Log' ),
998 wfMsgHtml( 'deletelog-fulllog' ),
1000 array( 'type' => 'delete', 'page' => $this->mTitle
->getPrefixedText() )
1003 $wgOut->addHTML( '</div>' );
1008 * Should the parser cache be used?
1010 protected function useParserCache( $oldid ) {
1011 global $wgUser, $wgEnableParserCache;
1013 return $wgEnableParserCache
1014 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1017 && !$this->mTitle
->isCssOrJsPage()
1018 && !$this->mTitle
->isCssJsSubpage();
1023 * @param $target Title object of destination to redirect
1024 * @param $appendSubtitle Boolean [optional]
1025 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1027 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1028 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1030 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1031 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
1033 if( $appendSubtitle ) {
1034 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1036 $sk = $wgUser->getSkin();
1038 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1040 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1042 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1043 '<span class="redirectText">'.$link.'</span>';
1047 public function addTrackbacks() {
1048 global $wgOut, $wgUser;
1049 $dbr = wfGetDB( DB_SLAVE
);
1050 $tbs = $dbr->select( 'trackbacks',
1051 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1052 array('tb_page' => $this->getID() )
1054 if( !$dbr->numRows($tbs) ) return;
1057 while( $o = $dbr->fetchObject($tbs) ) {
1059 if( $wgUser->isAllowed( 'trackback' ) ) {
1060 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1061 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1062 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1065 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1072 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1073 $this->mTitle
->invalidateCache();
1076 public function deletetrackback() {
1077 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1078 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1079 $wgOut->addWikiMsg( 'sessionfailure' );
1083 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1084 if( count($permission_errors) ) {
1085 $wgOut->showPermissionsErrorPage( $permission_errors );
1089 $db = wfGetDB( DB_MASTER
);
1090 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1092 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1093 $this->mTitle
->invalidateCache();
1096 public function render() {
1098 $wgOut->setArticleBodyOnly(true);
1103 * Handle action=purge
1105 public function purge() {
1106 global $wgUser, $wgRequest, $wgOut;
1107 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1108 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1113 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1114 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1115 $form = "<form method=\"post\" action=\"$action\">\n" .
1116 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1118 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1119 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1120 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1121 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1122 $wgOut->addHTML( $top . $form . $bottom );
1127 * Perform the actions of a page purging
1129 public function doPurge() {
1131 // Invalidate the cache
1132 $this->mTitle
->invalidateCache();
1135 // Commit the transaction before the purge is sent
1136 $dbw = wfGetDB( DB_MASTER
);
1137 $dbw->immediateCommit();
1140 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1141 $update->doUpdate();
1143 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1144 global $wgMessageCache;
1145 if( $this->getID() == 0 ) {
1148 $text = $this->getRawText();
1150 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1155 * Insert a new empty page record for this article.
1156 * This *must* be followed up by creating a revision
1157 * and running $this->updateToLatest( $rev_id );
1158 * or else the record will be left in a funky state.
1159 * Best if all done inside a transaction.
1161 * @param $dbw Database
1162 * @return int The newly created page_id key, or false if the title already existed
1165 public function insertOn( $dbw ) {
1166 wfProfileIn( __METHOD__
);
1168 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1169 $dbw->insert( 'page', array(
1170 'page_id' => $page_id,
1171 'page_namespace' => $this->mTitle
->getNamespace(),
1172 'page_title' => $this->mTitle
->getDBkey(),
1173 'page_counter' => 0,
1174 'page_restrictions' => '',
1175 'page_is_redirect' => 0, # Will set this shortly...
1177 'page_random' => wfRandom(),
1178 'page_touched' => $dbw->timestamp(),
1179 'page_latest' => 0, # Fill this in shortly...
1180 'page_len' => 0, # Fill this in shortly...
1181 ), __METHOD__
, 'IGNORE' );
1183 $affected = $dbw->affectedRows();
1185 $newid = $dbw->insertId();
1186 $this->mTitle
->resetArticleId( $newid );
1188 wfProfileOut( __METHOD__
);
1189 return $affected ?
$newid : false;
1193 * Update the page record to point to a newly saved revision.
1195 * @param $dbw Database object
1196 * @param $revision Revision: For ID number, and text used to set
1197 length and redirect status fields
1198 * @param $lastRevision Integer: if given, will not overwrite the page field
1199 * when different from the currently set value.
1200 * Giving 0 indicates the new page flag should be set
1202 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1203 * removing rows in redirect table.
1204 * @return bool true on success, false on failure
1207 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1208 wfProfileIn( __METHOD__
);
1210 $text = $revision->getText();
1211 $rt = Title
::newFromRedirect( $text );
1213 $conditions = array( 'page_id' => $this->getId() );
1214 if( !is_null( $lastRevision ) ) {
1215 # An extra check against threads stepping on each other
1216 $conditions['page_latest'] = $lastRevision;
1219 $dbw->update( 'page',
1221 'page_latest' => $revision->getId(),
1222 'page_touched' => $dbw->timestamp(),
1223 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1224 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1225 'page_len' => strlen( $text ),
1230 $result = $dbw->affectedRows() != 0;
1232 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1235 wfProfileOut( __METHOD__
);
1240 * Add row to the redirect table if this is a redirect, remove otherwise.
1242 * @param $dbw Database
1243 * @param $redirectTitle a title object pointing to the redirect target,
1244 * or NULL if this is not a redirect
1245 * @param $lastRevIsRedirect If given, will optimize adding and
1246 * removing rows in redirect table.
1247 * @return bool true on success, false on failure
1250 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1251 // Always update redirects (target link might have changed)
1252 // Update/Insert if we don't know if the last revision was a redirect or not
1253 // Delete if changing from redirect to non-redirect
1254 $isRedirect = !is_null($redirectTitle);
1255 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1256 wfProfileIn( __METHOD__
);
1258 // This title is a redirect, Add/Update row in the redirect table
1259 $set = array( /* SET */
1260 'rd_namespace' => $redirectTitle->getNamespace(),
1261 'rd_title' => $redirectTitle->getDBkey(),
1262 'rd_from' => $this->getId(),
1264 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1266 // This is not a redirect, remove row from redirect table
1267 $where = array( 'rd_from' => $this->getId() );
1268 $dbw->delete( 'redirect', $where, __METHOD__
);
1270 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1271 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1273 wfProfileOut( __METHOD__
);
1274 return ( $dbw->affectedRows() != 0 );
1280 * If the given revision is newer than the currently set page_latest,
1281 * update the page record. Otherwise, do nothing.
1283 * @param $dbw Database object
1284 * @param $revision Revision object
1286 public function updateIfNewerOn( &$dbw, $revision ) {
1287 wfProfileIn( __METHOD__
);
1288 $row = $dbw->selectRow(
1289 array( 'revision', 'page' ),
1290 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1292 'page_id' => $this->getId(),
1293 'page_latest=rev_id' ),
1296 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1297 wfProfileOut( __METHOD__
);
1300 $prev = $row->rev_id
;
1301 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1303 # No or missing previous revision; mark the page as new
1305 $lastRevIsRedirect = null;
1307 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1308 wfProfileOut( __METHOD__
);
1313 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1314 * @return string Complete article text, or null if error
1316 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1317 wfProfileIn( __METHOD__
);
1318 if( strval( $section ) == '' ) {
1319 // Whole-page edit; let the whole text through
1321 if( is_null($edittime) ) {
1322 $rev = Revision
::newFromTitle( $this->mTitle
);
1324 $dbw = wfGetDB( DB_MASTER
);
1325 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1328 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1329 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1332 $oldtext = $rev->getText();
1334 if( $section == 'new' ) {
1335 # Inserting a new section
1336 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1337 $text = strlen( trim( $oldtext ) ) > 0
1338 ?
"{$oldtext}\n\n{$subject}{$text}"
1339 : "{$subject}{$text}";
1341 # Replacing an existing section; roll out the big guns
1343 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1346 wfProfileOut( __METHOD__
);
1351 * @deprecated use Article::doEdit()
1353 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1354 wfDeprecated( __METHOD__
);
1355 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1356 ( $isminor ? EDIT_MINOR
: 0 ) |
1357 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1358 ( $bot ? EDIT_FORCE_BOT
: 0 );
1360 # If this is a comment, add the summary as headline
1361 if( $comment && $summary != "" ) {
1362 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1365 $this->doEdit( $text, $summary, $flags );
1367 $dbw = wfGetDB( DB_MASTER
);
1369 if(!$this->mTitle
->userIsWatching()) {
1375 if( $this->mTitle
->userIsWatching() ) {
1381 $this->doRedirect( $this->isRedirect( $text ) );
1385 * @deprecated use Article::doEdit()
1387 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1388 wfDeprecated( __METHOD__
);
1389 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1390 ( $minor ? EDIT_MINOR
: 0 ) |
1391 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1393 $status = $this->doEdit( $text, $summary, $flags );
1394 if( !$status->isOK() ) {
1398 $dbw = wfGetDB( DB_MASTER
);
1400 if(!$this->mTitle
->userIsWatching()) {
1406 if( $this->mTitle
->userIsWatching() ) {
1413 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1414 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1416 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1423 * Change an existing article or create a new article. Updates RC and all necessary caches,
1424 * optionally via the deferred update array.
1426 * $wgUser must be set before calling this function.
1428 * @param $text String: new text
1429 * @param $summary String: edit summary
1430 * @param $flags Integer bitfield:
1432 * Article is known or assumed to be non-existent, create a new one
1434 * Article is known or assumed to be pre-existing, update it
1436 * Mark this edit minor, if the user is allowed to do so
1438 * Do not log the change in recentchanges
1440 * Mark the edit a "bot" edit regardless of user rights
1441 * EDIT_DEFER_UPDATES
1442 * Defer some of the updates until the end of index.php
1444 * Fill in blank summaries with generated text where possible
1446 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1447 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1448 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1449 * edit-already-exists error will be returned. These two conditions are also possible with
1450 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1452 * @param $baseRevId the revision ID this edit was based off, if any
1453 * @param $user Optional user object, $wgUser will be used if not passed
1455 * @return Status object. Possible errors:
1456 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1457 * edit-gone-missing: In update mode, but the article didn't exist
1458 * edit-conflict: In update mode, the article changed unexpectedly
1459 * edit-no-change: Warning that the text was the same as before
1460 * edit-already-exists: In creation mode, but the article already exists
1462 * Extensions may define additional errors.
1464 * $return->value will contain an associative array with members as follows:
1465 * new: Boolean indicating if the function attempted to create a new article
1466 * revision: The revision object for the inserted revision, or null
1468 * Compatibility note: this function previously returned a boolean value indicating success/failure
1470 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1471 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1473 # Low-level sanity check
1474 if( $this->mTitle
->getText() == '' ) {
1475 throw new MWException( 'Something is trying to edit an article with an empty title' );
1478 wfProfileIn( __METHOD__
);
1480 $user = is_null($user) ?
$wgUser : $user;
1481 $status = Status
::newGood( array() );
1483 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1484 $this->loadPageData();
1486 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1487 $aid = $this->mTitle
->getArticleID();
1489 $flags |
= EDIT_UPDATE
;
1495 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1496 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1498 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1499 wfProfileOut( __METHOD__
);
1500 if( $status->isOK() ) {
1501 $status->fatal( 'edit-hook-aborted');
1506 # Silently ignore EDIT_MINOR if not allowed
1507 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1508 $bot = $flags & EDIT_FORCE_BOT
;
1510 $oldtext = $this->getRawText(); // current revision
1511 $oldsize = strlen( $oldtext );
1513 # Provide autosummaries if one is not provided and autosummaries are enabled.
1514 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1515 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1518 $editInfo = $this->prepareTextForEdit( $text );
1519 $text = $editInfo->pst
;
1520 $newsize = strlen( $text );
1522 $dbw = wfGetDB( DB_MASTER
);
1523 $now = wfTimestampNow();
1525 if( $flags & EDIT_UPDATE
) {
1526 # Update article, but only if changed.
1527 $status->value
['new'] = false;
1528 # Make sure the revision is either completely inserted or not inserted at all
1529 if( !$wgDBtransactions ) {
1530 $userAbort = ignore_user_abort( true );
1535 $changed = ( strcmp( $text, $oldtext ) != 0 );
1538 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1539 - (int)$this->isCountable( $oldtext );
1540 $this->mTotalAdjustment
= 0;
1542 if( !$this->mLatest
) {
1543 # Article gone missing
1544 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1545 $status->fatal( 'edit-gone-missing' );
1546 wfProfileOut( __METHOD__
);
1550 $revision = new Revision( array(
1551 'page' => $this->getId(),
1552 'comment' => $summary,
1553 'minor_edit' => $isminor,
1555 'parent_id' => $this->mLatest
,
1556 'user' => $user->getId(),
1557 'user_text' => $user->getName(),
1561 $revisionId = $revision->insertOn( $dbw );
1565 # Note that we use $this->mLatest instead of fetching a value from the master DB
1566 # during the course of this function. This makes sure that EditPage can detect
1567 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1568 # before this function is called. A previous function used a separate query, this
1569 # creates a window where concurrent edits can cause an ignored edit conflict.
1570 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1573 /* Belated edit conflict! Run away!! */
1574 $status->fatal( 'edit-conflict' );
1575 # Delete the invalid revision if the DB is not transactional
1576 if( !$wgDBtransactions ) {
1577 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1582 global $wgUseRCPatrol;
1583 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1584 # Update recentchanges
1585 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1586 # Mark as patrolled if the user can do so
1587 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan('autopatrol');
1588 # Add RC row to the DB
1589 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1590 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1591 $revisionId, $patrolled
1593 # Log auto-patrolled edits
1595 PatrolLog
::record( $rc, true );
1598 $user->incEditCount();
1602 $status->warning( 'edit-no-change' );
1604 // Keep the same revision ID, but do some updates on it
1605 $revisionId = $this->getRevIdFetched();
1606 // Update page_touched, this is usually implicit in the page update
1607 // Other cache updates are done in onArticleEdit()
1608 $this->mTitle
->invalidateCache();
1611 if( !$wgDBtransactions ) {
1612 ignore_user_abort( $userAbort );
1614 // Now that ignore_user_abort is restored, we can respond to fatal errors
1615 if( !$status->isOK() ) {
1616 wfProfileOut( __METHOD__
);
1620 # Invalidate cache of this article and all pages using this article
1621 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1622 Article
::onArticleEdit( $this->mTitle
, 'skiptransclusions' );
1623 # Update links tables, site stats, etc.
1624 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1626 # Create new article
1627 $status->value
['new'] = true;
1629 # Set statistics members
1630 # We work out if it's countable after PST to avoid counter drift
1631 # when articles are created with {{subst:}}
1632 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1633 $this->mTotalAdjustment
= 1;
1637 # Add the page record; stake our claim on this title!
1638 # This will return false if the article already exists
1639 $newid = $this->insertOn( $dbw );
1641 if( $newid === false ) {
1643 $status->fatal( 'edit-already-exists' );
1644 wfProfileOut( __METHOD__
);
1648 # Save the revision text...
1649 $revision = new Revision( array(
1651 'comment' => $summary,
1652 'minor_edit' => $isminor,
1654 'user' => $user->getId(),
1655 'user_text' => $user->getName(),
1657 $revisionId = $revision->insertOn( $dbw );
1659 $this->mTitle
->resetArticleID( $newid );
1661 # Update the page record with revision data
1662 $this->updateRevisionOn( $dbw, $revision, 0 );
1664 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1665 # Update recentchanges
1666 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1667 global $wgUseRCPatrol, $wgUseNPPatrol;
1668 # Mark as patrolled if the user can do so
1669 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $this->mTitle
->userCan('autopatrol');
1670 # Add RC row to the DB
1671 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1672 '', strlen($text), $revisionId, $patrolled );
1673 # Log auto-patrolled edits
1675 PatrolLog
::record( $rc, true );
1678 $user->incEditCount();
1681 # Update links, etc.
1682 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1685 Article
::onArticleCreate( $this->mTitle
);
1687 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1688 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1691 # Do updates right now unless deferral was requested
1692 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1696 // Return the new revision (or null) to the caller
1697 $status->value
['revision'] = $revision;
1699 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1700 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status ) );
1702 wfProfileOut( __METHOD__
);
1707 * @deprecated wrapper for doRedirect
1709 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1710 wfDeprecated( __METHOD__
);
1711 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1715 * Output a redirect back to the article.
1716 * This is typically used after an edit.
1718 * @param $noRedir Boolean: add redirect=no
1719 * @param $sectionAnchor String: section to redirect to, including "#"
1720 * @param $extraQuery String: extra query params
1722 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1725 $query = 'redirect=no';
1727 $query .= "&$query";
1729 $query = $extraQuery;
1731 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1735 * Mark this particular edit/page as patrolled
1737 public function markpatrolled() {
1738 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1739 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1741 # If we haven't been given an rc_id value, we can't do anything
1742 $rcid = (int) $wgRequest->getVal('rcid');
1743 $rc = RecentChange
::newFromId($rcid);
1744 if( is_null($rc) ) {
1745 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1749 #It would be nice to see where the user had actually come from, but for now just guess
1750 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1751 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1753 $dbw = wfGetDB( DB_MASTER
);
1754 $errors = $rc->doMarkPatrolled();
1756 if( in_array(array('rcpatroldisabled'), $errors) ) {
1757 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1761 if( in_array(array('hookaborted'), $errors) ) {
1762 // The hook itself has handled any output
1766 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1767 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1768 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1769 $wgOut->returnToMain( false, $return );
1773 if( !empty($errors) ) {
1774 $wgOut->showPermissionsErrorPage( $errors );
1779 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1780 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1781 $wgOut->returnToMain( false, $return );
1785 * User-interface handler for the "watch" action
1788 public function watch() {
1789 global $wgUser, $wgOut;
1790 if( $wgUser->isAnon() ) {
1791 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1794 if( wfReadOnly() ) {
1795 $wgOut->readOnlyPage();
1798 if( $this->doWatch() ) {
1799 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1800 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1801 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1803 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1807 * Add this page to $wgUser's watchlist
1808 * @return bool true on successful watch operation
1810 public function doWatch() {
1812 if( $wgUser->isAnon() ) {
1815 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1816 $wgUser->addWatch( $this->mTitle
);
1817 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1823 * User interface handler for the "unwatch" action.
1825 public function unwatch() {
1826 global $wgUser, $wgOut;
1827 if( $wgUser->isAnon() ) {
1828 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1831 if( wfReadOnly() ) {
1832 $wgOut->readOnlyPage();
1835 if( $this->doUnwatch() ) {
1836 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1837 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1838 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1840 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1844 * Stop watching a page
1845 * @return bool true on successful unwatch
1847 public function doUnwatch() {
1849 if( $wgUser->isAnon() ) {
1852 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1853 $wgUser->removeWatch( $this->mTitle
);
1854 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1860 * action=protect handler
1862 public function protect() {
1863 $form = new ProtectionForm( $this );
1868 * action=unprotect handler (alias)
1870 public function unprotect() {
1875 * Update the article's restriction field, and leave a log entry.
1877 * @param $limit Array: set of restriction keys
1878 * @param $reason String
1879 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1880 * @param $expiry Array: per restriction type expiration
1881 * @return bool true on success
1883 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1884 global $wgUser, $wgRestrictionTypes, $wgContLang;
1886 $id = $this->mTitle
->getArticleID();
1887 if( $id <= 0 ||
wfReadOnly() ||
!$this->mTitle
->userCan('protect') ) {
1895 // Take this opportunity to purge out expired restrictions
1896 Title
::purgeExpiredRestrictions();
1898 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1899 # we expect a single selection, but the schema allows otherwise.
1901 $updated = Article
::flattenRestrictions( $limit );
1903 foreach( $wgRestrictionTypes as $action ) {
1904 if( isset( $expiry[$action] ) ) {
1905 # Get current restrictions on $action
1906 $aLimits = $this->mTitle
->getRestrictions( $action );
1907 $current[$action] = implode( '', $aLimits );
1908 # Are any actual restrictions being dealt with here?
1909 $aRChanged = count($aLimits) ||
!empty($limit[$action]);
1910 # If something changed, we need to log it. Checking $aRChanged
1911 # assures that "unprotecting" a page that is not protected does
1912 # not log just because the expiry was "changed".
1913 if( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
1919 $current = Article
::flattenRestrictions( $current );
1921 $changed = ($changed ||
$current != $updated );
1922 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1923 $protect = ( $updated != '' );
1925 # If nothing's changed, do nothing
1927 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1929 $dbw = wfGetDB( DB_MASTER
);
1931 # Prepare a null revision to be added to the history
1932 $modified = $current != '' && $protect;
1934 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1936 $comment_type = 'unprotectedarticle';
1938 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1940 # Only restrictions with the 'protect' right can cascade...
1941 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1942 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1943 # The schema allows multiple restrictions
1944 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
1946 $cascade_description = '';
1948 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1952 $comment .= ": $reason";
1954 $editComment = $comment;
1955 $encodedExpiry = array();
1956 $protect_description = '';
1957 foreach( $limit as $action => $restrictions ) {
1958 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
1959 if( $restrictions != '' ) {
1960 $protect_description .= "[$action=$restrictions] (";
1961 if( $encodedExpiry[$action] != 'infinity' ) {
1962 $protect_description .= wfMsgForContent( 'protect-expiring',
1963 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1964 $wgContLang->date( $expiry[$action], false, false ) ,
1965 $wgContLang->time( $expiry[$action], false, false ) );
1967 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1969 $protect_description .= ') ';
1972 $protect_description = trim($protect_description);
1974 if( $protect_description && $protect )
1975 $editComment .= " ($protect_description)";
1977 $editComment .= "$cascade_description";
1978 # Update restrictions table
1979 foreach( $limit as $action => $restrictions ) {
1980 if($restrictions != '' ) {
1981 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1982 array( 'pr_page' => $id,
1983 'pr_type' => $action,
1984 'pr_level' => $restrictions,
1985 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
1986 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
1988 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1989 'pr_type' => $action ), __METHOD__
);
1993 # Insert a null revision
1994 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1995 $nullRevId = $nullRevision->insertOn( $dbw );
1997 $latest = $this->getLatest();
1998 # Update page record
1999 $dbw->update( 'page',
2001 'page_touched' => $dbw->timestamp(),
2002 'page_restrictions' => '',
2003 'page_latest' => $nullRevId
2004 ), array( /* WHERE */
2006 ), 'Article::protect'
2009 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2010 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2012 # Update the protection log
2013 $log = new LogPage( 'protect' );
2015 $params = array($protect_description,$cascade ?
'cascade' : '');
2016 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
2018 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2022 } # End "changed" check
2028 * Take an array of page restrictions and flatten it to a string
2029 * suitable for insertion into the page_restrictions field.
2030 * @param $limit Array
2033 protected static function flattenRestrictions( $limit ) {
2034 if( !is_array( $limit ) ) {
2035 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2039 foreach( $limit as $action => $restrictions ) {
2040 if( $restrictions != '' ) {
2041 $bits[] = "$action=$restrictions";
2044 return implode( ':', $bits );
2048 * Auto-generates a deletion reason
2049 * @param &$hasHistory Boolean: whether the page has a history
2051 public function generateReason( &$hasHistory ) {
2053 $dbw = wfGetDB( DB_MASTER
);
2054 // Get the last revision
2055 $rev = Revision
::newFromTitle( $this->mTitle
);
2056 if( is_null( $rev ) )
2059 // Get the article's contents
2060 $contents = $rev->getText();
2062 // If the page is blank, use the text from the previous revision,
2063 // which can only be blank if there's a move/import/protect dummy revision involved
2064 if( $contents == '' ) {
2065 $prev = $rev->getPrevious();
2067 $contents = $prev->getText();
2072 // Find out if there was only one contributor
2073 // Only scan the last 20 revisions
2075 $res = $dbw->select( 'revision', 'rev_user_text',
2076 array( 'rev_page' => $this->getID() ), __METHOD__
,
2077 array( 'LIMIT' => $limit )
2079 if( $res === false )
2080 // This page has no revisions, which is very weird
2082 if( $res->numRows() > 1 )
2085 $hasHistory = false;
2086 $row = $dbw->fetchObject( $res );
2087 $onlyAuthor = $row->rev_user_text
;
2088 // Try to find a second contributor
2089 foreach( $res as $row ) {
2090 if( $row->rev_user_text
!= $onlyAuthor ) {
2091 $onlyAuthor = false;
2095 $dbw->freeResult( $res );
2097 // Generate the summary with a '$1' placeholder
2099 // The current revision is blank and the one before is also
2100 // blank. It's just not our lucky day
2101 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2104 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2106 $reason = wfMsgForContent( 'excontent', '$1' );
2109 if( $reason == '-' ) {
2110 // Allow these UI messages to be blanked out cleanly
2114 // Replace newlines with spaces to prevent uglyness
2115 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2116 // Calculate the maximum amount of chars to get
2117 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2118 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2119 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2120 // Remove possible unfinished links
2121 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2122 // Now replace the '$1' placeholder
2123 $reason = str_replace( '$1', $contents, $reason );
2129 * UI entry point for page deletion
2131 public function delete() {
2132 global $wgUser, $wgOut, $wgRequest;
2134 $confirm = $wgRequest->wasPosted() &&
2135 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2137 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2138 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2140 $reason = $this->DeleteReasonList
;
2142 if( $reason != 'other' && $this->DeleteReason
!= '' ) {
2143 // Entry from drop down menu + additional comment
2144 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2145 } elseif( $reason == 'other' ) {
2146 $reason = $this->DeleteReason
;
2148 # Flag to hide all contents of the archived revisions
2149 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2151 # This code desperately needs to be totally rewritten
2153 # Read-only check...
2154 if( wfReadOnly() ) {
2155 $wgOut->readOnlyPage();
2160 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2162 if( count( $permission_errors ) > 0 ) {
2163 $wgOut->showPermissionsErrorPage( $permission_errors );
2167 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2169 # Better double-check that it hasn't been deleted yet!
2170 $dbw = wfGetDB( DB_MASTER
);
2171 $conds = $this->mTitle
->pageCond();
2172 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2173 if( $latest === false ) {
2174 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2175 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2176 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2180 # Hack for big sites
2181 $bigHistory = $this->isBigDeletion();
2182 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2183 global $wgLang, $wgDeleteRevisionsLimit;
2184 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2185 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2190 $this->doDelete( $reason, $suppress );
2191 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2193 } elseif( $this->mTitle
->userIsWatching() ) {
2199 // Generate deletion reason
2200 $hasHistory = false;
2201 if( !$reason ) $reason = $this->generateReason($hasHistory);
2203 // If the page has a history, insert a warning
2204 if( $hasHistory && !$confirm ) {
2205 $skin = $wgUser->getSkin();
2206 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2208 global $wgLang, $wgDeleteRevisionsLimit;
2209 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2210 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2214 return $this->confirmDelete( $reason );
2218 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2220 public function isBigDeletion() {
2221 global $wgDeleteRevisionsLimit;
2222 if( $wgDeleteRevisionsLimit ) {
2223 $revCount = $this->estimateRevisionCount();
2224 return $revCount > $wgDeleteRevisionsLimit;
2230 * @return int approximate revision count
2232 public function estimateRevisionCount() {
2233 $dbr = wfGetDB( DB_SLAVE
);
2234 // For an exact count...
2235 //return $dbr->selectField( 'revision', 'COUNT(*)',
2236 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2237 return $dbr->estimateRowCount( 'revision', '*',
2238 array( 'rev_page' => $this->getId() ), __METHOD__
);
2242 * Get the last N authors
2243 * @param $num Integer: number of revisions to get
2244 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2245 * @return array Array of authors, duplicates not removed
2247 public function getLastNAuthors( $num, $revLatest = 0 ) {
2248 wfProfileIn( __METHOD__
);
2249 // First try the slave
2250 // If that doesn't have the latest revision, try the master
2252 $db = wfGetDB( DB_SLAVE
);
2254 $res = $db->select( array( 'page', 'revision' ),
2255 array( 'rev_id', 'rev_user_text' ),
2257 'page_namespace' => $this->mTitle
->getNamespace(),
2258 'page_title' => $this->mTitle
->getDBkey(),
2259 'rev_page = page_id'
2260 ), __METHOD__
, $this->getSelectOptions( array(
2261 'ORDER BY' => 'rev_timestamp DESC',
2266 wfProfileOut( __METHOD__
);
2269 $row = $db->fetchObject( $res );
2270 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2271 $db = wfGetDB( DB_MASTER
);
2276 } while ( $continue );
2278 $authors = array( $row->rev_user_text
);
2279 while ( $row = $db->fetchObject( $res ) ) {
2280 $authors[] = $row->rev_user_text
;
2282 wfProfileOut( __METHOD__
);
2287 * Output deletion confirmation dialog
2288 * @param $reason String: prefilled reason
2290 public function confirmDelete( $reason ) {
2291 global $wgOut, $wgUser;
2293 wfDebug( "Article::confirmDelete\n" );
2295 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2296 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2297 $wgOut->addWikiMsg( 'confirmdeletetext' );
2299 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2300 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2302 <td class='mw-input'>" .
2303 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2304 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2310 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2312 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2313 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2314 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2315 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2316 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2317 "<tr id=\"wpDeleteReasonListRow\">
2318 <td class='mw-label'>" .
2319 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2321 <td class='mw-input'>" .
2322 Xml
::listDropDown( 'wpDeleteReasonList',
2323 wfMsgForContent( 'deletereason-dropdown' ),
2324 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2327 <tr id=\"wpDeleteReasonRow\">
2328 <td class='mw-label'>" .
2329 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2331 <td class='mw-input'>" .
2332 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2333 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2338 <td class='mw-input'>" .
2339 Xml
::checkLabel( wfMsg( 'watchthis' ),
2340 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2346 <td class='mw-submit'>" .
2347 Xml
::submitButton( wfMsg( 'deletepage' ),
2348 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2351 Xml
::closeElement( 'table' ) .
2352 Xml
::closeElement( 'fieldset' ) .
2353 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2354 Xml
::closeElement( 'form' );
2356 if( $wgUser->isAllowed( 'editinterface' ) ) {
2357 $skin = $wgUser->getSkin();
2358 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2359 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2362 $wgOut->addHTML( $form );
2363 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2367 * Perform a deletion and output success or failure messages
2369 public function doDelete( $reason, $suppress = false ) {
2370 global $wgOut, $wgUser;
2371 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2374 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2375 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2376 $deleted = $this->mTitle
->getPrefixedText();
2378 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2379 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2381 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2383 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2384 $wgOut->returnToMain( false );
2385 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2387 if( $error == '' ) {
2388 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2389 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2390 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2392 $wgOut->showFatalError( $error );
2399 * Back-end article deletion
2400 * Deletes the article with database consistency, writes logs, purges caches
2403 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2404 global $wgUseSquid, $wgDeferredUpdateList;
2405 global $wgUseTrackbacks;
2407 wfDebug( __METHOD__
."\n" );
2409 $dbw = wfGetDB( DB_MASTER
);
2410 $ns = $this->mTitle
->getNamespace();
2411 $t = $this->mTitle
->getDBkey();
2412 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2414 if( $t == '' ||
$id == 0 ) {
2418 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2419 array_push( $wgDeferredUpdateList, $u );
2421 // Bitfields to further suppress the content
2424 // This should be 15...
2425 $bitfield |
= Revision
::DELETED_TEXT
;
2426 $bitfield |
= Revision
::DELETED_COMMENT
;
2427 $bitfield |
= Revision
::DELETED_USER
;
2428 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2430 $bitfield = 'rev_deleted';
2434 // For now, shunt the revision data into the archive table.
2435 // Text is *not* removed from the text table; bulk storage
2436 // is left intact to avoid breaking block-compression or
2437 // immutable storage schemes.
2439 // For backwards compatibility, note that some older archive
2440 // table entries will have ar_text and ar_flags fields still.
2442 // In the future, we may keep revisions and mark them with
2443 // the rev_deleted field, which is reserved for this purpose.
2444 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2446 'ar_namespace' => 'page_namespace',
2447 'ar_title' => 'page_title',
2448 'ar_comment' => 'rev_comment',
2449 'ar_user' => 'rev_user',
2450 'ar_user_text' => 'rev_user_text',
2451 'ar_timestamp' => 'rev_timestamp',
2452 'ar_minor_edit' => 'rev_minor_edit',
2453 'ar_rev_id' => 'rev_id',
2454 'ar_text_id' => 'rev_text_id',
2455 'ar_text' => '\'\'', // Be explicit to appease
2456 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2457 'ar_len' => 'rev_len',
2458 'ar_page_id' => 'page_id',
2459 'ar_deleted' => $bitfield
2462 'page_id = rev_page'
2466 # Delete restrictions for it
2467 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2469 # Now that it's safely backed up, delete it
2470 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2471 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2477 # If using cascading deletes, we can skip some explicit deletes
2478 if( !$dbw->cascadingDeletes() ) {
2479 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2481 if($wgUseTrackbacks)
2482 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2484 # Delete outgoing links
2485 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2486 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2487 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2488 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2489 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2490 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2491 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2494 # If using cleanup triggers, we can skip some manual deletes
2495 if( !$dbw->cleanupTriggers() ) {
2496 # Clean up recentchanges entries...
2497 $dbw->delete( 'recentchanges',
2498 array( 'rc_type != '.RC_LOG
,
2499 'rc_namespace' => $this->mTitle
->getNamespace(),
2500 'rc_title' => $this->mTitle
->getDBKey() ),
2502 $dbw->delete( 'recentchanges',
2503 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2508 Article
::onArticleDelete( $this->mTitle
);
2510 # Fix category table counts
2512 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2513 foreach( $res as $row ) {
2514 $cats []= $row->cl_to
;
2516 $this->updateCategoryCounts( array(), $cats );
2518 # Clear the cached article id so the interface doesn't act like we exist
2519 $this->mTitle
->resetArticleID( 0 );
2520 $this->mTitle
->mArticleID
= 0;
2522 # Log the deletion, if the page was suppressed, log it at Oversight instead
2523 $logtype = $suppress ?
'suppress' : 'delete';
2524 $log = new LogPage( $logtype );
2526 # Make sure logging got through
2527 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2535 * Roll back the most recent consecutive set of edits to a page
2536 * from the same user; fails if there are no eligible edits to
2537 * roll back to, e.g. user is the sole contributor. This function
2538 * performs permissions checks on $wgUser, then calls commitRollback()
2539 * to do the dirty work
2541 * @param $fromP String: Name of the user whose edits to rollback.
2542 * @param $summary String: Custom summary. Set to default summary if empty.
2543 * @param $token String: Rollback token.
2544 * @param $bot Boolean: If true, mark all reverted edits as bot.
2546 * @param $resultDetails Array: contains result-specific array of additional values
2547 * 'alreadyrolled' : 'current' (rev)
2548 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2550 * @return array of errors, each error formatted as
2551 * array(messagekey, param1, param2, ...).
2552 * On success, the array is empty. This array can also be passed to
2553 * OutputPage::showPermissionsErrorPage().
2555 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2557 $resultDetails = null;
2560 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2561 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2562 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2564 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2565 $errors[] = array( 'sessionfailure' );
2567 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2568 $errors[] = array( 'actionthrottledtext' );
2570 # If there were errors, bail out now
2571 if( !empty( $errors ) )
2574 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2578 * Backend implementation of doRollback(), please refer there for parameter
2579 * and return value documentation
2581 * NOTE: This function does NOT check ANY permissions, it just commits the
2582 * rollback to the DB Therefore, you should only call this function direct-
2583 * ly if you want to use custom permissions checks. If you don't, use
2584 * doRollback() instead.
2586 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2587 global $wgUseRCPatrol, $wgUser, $wgLang;
2588 $dbw = wfGetDB( DB_MASTER
);
2590 if( wfReadOnly() ) {
2591 return array( array( 'readonlytext' ) );
2594 # Get the last editor
2595 $current = Revision
::newFromTitle( $this->mTitle
);
2596 if( is_null( $current ) ) {
2597 # Something wrong... no page?
2598 return array(array('notanarticle'));
2601 $from = str_replace( '_', ' ', $fromP );
2602 if( $from != $current->getUserText() ) {
2603 $resultDetails = array( 'current' => $current );
2604 return array(array('alreadyrolled',
2605 htmlspecialchars($this->mTitle
->getPrefixedText()),
2606 htmlspecialchars($fromP),
2607 htmlspecialchars($current->getUserText())
2611 # Get the last edit not by this guy
2612 $user = intval( $current->getUser() );
2613 $user_text = $dbw->addQuotes( $current->getUserText() );
2614 $s = $dbw->selectRow( 'revision',
2615 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2616 array( 'rev_page' => $current->getPage(),
2617 "rev_user != {$user} OR rev_user_text != {$user_text}"
2619 array( 'USE INDEX' => 'page_timestamp',
2620 'ORDER BY' => 'rev_timestamp DESC' )
2622 if( $s === false ) {
2623 # No one else ever edited this page
2624 return array(array('cantrollback'));
2625 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2626 # Only admins can see this text
2627 return array(array('notvisiblerev'));
2631 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2632 # Mark all reverted edits as bot
2635 if( $wgUseRCPatrol ) {
2636 # Mark all reverted edits as patrolled
2637 $set['rc_patrolled'] = 1;
2641 $dbw->update( 'recentchanges', $set,
2643 'rc_cur_id' => $current->getPage(),
2644 'rc_user_text' => $current->getUserText(),
2645 "rc_timestamp > '{$s->rev_timestamp}'",
2650 # Generate the edit summary if necessary
2651 $target = Revision
::newFromId( $s->rev_id
);
2652 if( empty( $summary ) ){
2653 $summary = wfMsgForContent( 'revertpage' );
2656 # Allow the custom summary to use the same args as the default message
2658 $target->getUserText(), $from, $s->rev_id
,
2659 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2660 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2662 $summary = wfMsgReplaceArgs( $summary, $args );
2665 $flags = EDIT_UPDATE
;
2667 if( $wgUser->isAllowed('minoredit') )
2668 $flags |
= EDIT_MINOR
;
2670 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2671 $flags |
= EDIT_FORCE_BOT
;
2672 # Actually store the edit
2673 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2674 if( !empty( $status->value
['revision'] ) ) {
2675 $revId = $status->value
['revision']->getId();
2680 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2682 $resultDetails = array(
2683 'summary' => $summary,
2684 'current' => $current,
2685 'target' => $target,
2692 * User interface for rollback operations
2694 public function rollback() {
2695 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2698 $result = $this->doRollback(
2699 $wgRequest->getVal( 'from' ),
2700 $wgRequest->getText( 'summary' ),
2701 $wgRequest->getVal( 'token' ),
2702 $wgRequest->getBool( 'bot' ),
2706 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2707 $wgOut->rateLimited();
2710 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2711 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2712 $errArray = $result[0];
2713 $errMsg = array_shift( $errArray );
2714 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2715 if( isset( $details['current'] ) ){
2716 $current = $details['current'];
2717 if( $current->getComment() != '' ) {
2718 $wgOut->addWikiMsgArray( 'editcomment', array(
2719 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2724 # Display permissions errors before read-only message -- there's no
2725 # point in misleading the user into thinking the inability to rollback
2726 # is only temporary.
2727 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2728 # array_diff is completely broken for arrays of arrays, sigh. Re-
2729 # move any 'readonlytext' error manually.
2731 foreach( $result as $error ) {
2732 if( $error != array( 'readonlytext' ) ) {
2736 $wgOut->showPermissionsErrorPage( $out );
2739 if( $result == array( array( 'readonlytext' ) ) ) {
2740 $wgOut->readOnlyPage();
2744 $current = $details['current'];
2745 $target = $details['target'];
2746 $newId = $details['newid'];
2747 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2748 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2749 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2750 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2751 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2752 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2753 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2754 $wgOut->returnToMain( false, $this->mTitle
);
2756 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2757 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2758 $de->showDiff( '', '' );
2764 * Do standard deferred updates after page view
2766 public function viewUpdates() {
2767 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2768 # Don't update page view counters on views from bot users (bug 14044)
2769 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2770 Article
::incViewCount( $this->getID() );
2771 $u = new SiteStatsUpdate( 1, 0, 0 );
2772 array_push( $wgDeferredUpdateList, $u );
2774 # Update newtalk / watchlist notification status
2775 $wgUser->clearNotification( $this->mTitle
);
2779 * Prepare text which is about to be saved.
2780 * Returns a stdclass with source, pst and output members
2782 public function prepareTextForEdit( $text, $revid=null ) {
2783 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2785 return $this->mPreparedEdit
;
2788 $edit = (object)array();
2789 $edit->revid
= $revid;
2790 $edit->newText
= $text;
2791 $edit->pst
= $this->preSaveTransform( $text );
2792 $options = new ParserOptions
;
2793 $options->setTidy( true );
2794 $options->enableLimitReport();
2795 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2796 $edit->oldText
= $this->getContent();
2797 $this->mPreparedEdit
= $edit;
2802 * Do standard deferred updates after page edit.
2803 * Update links tables, site stats, search index and message cache.
2804 * Purges pages that include this page if the text was changed here.
2805 * Every 100th edit, prune the recent changes table.
2808 * @param $text New text of the article
2809 * @param $summary Edit summary
2810 * @param $minoredit Minor edit
2811 * @param $timestamp_of_pagechange Timestamp associated with the page change
2812 * @param $newid rev_id value of the new revision
2813 * @param $changed Whether or not the content actually changed
2815 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2816 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2818 wfProfileIn( __METHOD__
);
2821 # Be careful not to double-PST: $text is usually already PST-ed once
2822 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2823 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2824 $editInfo = $this->prepareTextForEdit( $text, $newid );
2826 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2827 $editInfo = $this->mPreparedEdit
;
2830 # Save it to the parser cache
2831 if( $wgEnableParserCache ) {
2832 $parserCache = ParserCache
::singleton();
2833 $parserCache->save( $editInfo->output
, $this, $wgUser );
2836 # Update the links tables
2837 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
, false );
2838 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2841 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2843 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2844 if( 0 == mt_rand( 0, 99 ) ) {
2845 // Flush old entries from the `recentchanges` table; we do this on
2846 // random requests so as to avoid an increase in writes for no good reason
2848 $dbw = wfGetDB( DB_MASTER
);
2849 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2850 $recentchanges = $dbw->tableName( 'recentchanges' );
2851 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2852 $dbw->query( $sql );
2856 $id = $this->getID();
2857 $title = $this->mTitle
->getPrefixedDBkey();
2858 $shortTitle = $this->mTitle
->getDBkey();
2861 wfProfileOut( __METHOD__
);
2865 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2866 array_push( $wgDeferredUpdateList, $u );
2867 $u = new SearchUpdate( $id, $title, $text );
2868 array_push( $wgDeferredUpdateList, $u );
2870 # If this is another user's talk page, update newtalk
2871 # Don't do this if $changed = false otherwise some idiot can null-edit a
2872 # load of user talk pages and piss people off, nor if it's a minor edit
2873 # by a properly-flagged bot.
2874 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2875 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2876 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2877 $other = User
::newFromName( $shortTitle, false );
2879 wfDebug( __METHOD__
.": invalid username\n" );
2880 } elseif( User
::isIP( $shortTitle ) ) {
2881 // An anonymous user
2882 $other->setNewtalk( true );
2883 } elseif( $other->isLoggedIn() ) {
2884 $other->setNewtalk( true );
2886 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2891 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2892 $wgMessageCache->replace( $shortTitle, $text );
2895 wfProfileOut( __METHOD__
);
2899 * Perform article updates on a special page creation.
2901 * @param $rev Revision object
2903 * @todo This is a shitty interface function. Kill it and replace the
2904 * other shitty functions like editUpdates and such so it's not needed
2907 public function createUpdates( $rev ) {
2908 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2909 $this->mTotalAdjustment
= 1;
2910 $this->editUpdates( $rev->getText(), $rev->getComment(),
2911 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2915 * Generate the navigation links when browsing through an article revisions
2916 * It shows the information as:
2917 * Revision as of \<date\>; view current revision
2918 * \<- Previous version | Next Version -\>
2920 * @param $oldid String: revision ID of this article revision
2922 public function setOldSubtitle( $oldid = 0 ) {
2923 global $wgLang, $wgOut, $wgUser;
2925 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
2929 $revision = Revision
::newFromId( $oldid );
2931 $current = ( $oldid == $this->mLatest
);
2932 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2933 $sk = $wgUser->getSkin();
2935 ?
wfMsgHtml( 'currentrevisionlink' )
2936 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'currentrevisionlink' ) );
2938 ?
wfMsgHtml( 'diff' )
2939 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
2940 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2942 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2943 : wfMsgHtml( 'previousrevision' );
2945 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
2946 : wfMsgHtml( 'diff' );
2947 $nextlink = $current
2948 ?
wfMsgHtml( 'nextrevision' )
2949 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2950 $nextdiff = $current
2951 ?
wfMsgHtml( 'diff' )
2952 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
2955 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2956 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2957 if( $revision->isCurrent() ) {
2958 // We don't handle top deleted edits too well
2959 $cdel = wfMsgHtml( 'rev-delundel' );
2960 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2961 // If revision was hidden from sysops
2962 $cdel = wfMsgHtml( 'rev-delundel' );
2964 $cdel = $sk->makeKnownLinkObj( $revdel,
2965 wfMsgHtml('rev-delundel'),
2966 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2967 '&oldid=' . urlencode( $oldid ) );
2968 // Bolden oversighted content
2969 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2970 $cdel = "<strong>$cdel</strong>";
2972 $cdel = "(<small>$cdel</small>) ";
2974 # Show user links if allowed to see them. Normally they
2975 # are hidden regardless, but since we can already see the text here...
2976 $userlinks = $sk->revUserTools( $revision, false );
2978 $m = wfMsg( 'revision-info-current' );
2979 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2980 ?
'revision-info-current'
2983 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" .
2985 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgHtml( 'revision-nav', $prevdiff,
2986 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2987 $wgOut->setSubtitle( $r );
2991 * This function is called right before saving the wikitext,
2992 * so we can do things like signatures and links-in-context.
2994 * @param $text String
2996 public function preSaveTransform( $text ) {
2997 global $wgParser, $wgUser;
2998 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3001 /* Caching functions */
3004 * checkLastModified returns true if it has taken care of all
3005 * output to the client that is necessary for this request.
3006 * (that is, it has sent a cached version of the page)
3008 protected function tryFileCache() {
3009 static $called = false;
3011 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3015 if( $this->isFileCacheable() ) {
3016 $cache = new HTMLFileCache( $this->mTitle
);
3017 if( $cache->isFileCacheGood( $this->mTouched
) ) {
3018 wfDebug( "Article::tryFileCache(): about to load file\n" );
3019 $cache->loadFromFileCache();
3022 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3023 ob_start( array(&$cache, 'saveToFileCache' ) );
3026 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3032 * Check if the page can be cached
3035 public function isFileCacheable() {
3037 if( HTMLFileCache
::useFileCache() ) {
3038 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3039 // Extension may have reason to disable file caching on some pages.
3041 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3048 * Loads page_touched and returns a value indicating if it should be used
3051 public function checkTouched() {
3052 if( !$this->mDataLoaded
) {
3053 $this->loadPageData();
3055 return !$this->mIsRedirect
;
3059 * Get the page_touched field
3061 public function getTouched() {
3062 # Ensure that page data has been loaded
3063 if( !$this->mDataLoaded
) {
3064 $this->loadPageData();
3066 return $this->mTouched
;
3070 * Get the page_latest field
3072 public function getLatest() {
3073 if( !$this->mDataLoaded
) {
3074 $this->loadPageData();
3076 return $this->mLatest
;
3080 * Edit an article without doing all that other stuff
3081 * The article must already exist; link tables etc
3082 * are not updated, caches are not flushed.
3084 * @param $text String: text submitted
3085 * @param $comment String: comment submitted
3086 * @param $minor Boolean: whereas it's a minor modification
3088 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3089 wfProfileIn( __METHOD__
);
3091 $dbw = wfGetDB( DB_MASTER
);
3092 $revision = new Revision( array(
3093 'page' => $this->getId(),
3095 'comment' => $comment,
3096 'minor_edit' => $minor ?
1 : 0,
3098 $revision->insertOn( $dbw );
3099 $this->updateRevisionOn( $dbw, $revision );
3101 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3103 wfProfileOut( __METHOD__
);
3107 * Used to increment the view counter
3109 * @param $id Integer: article id
3111 public static function incViewCount( $id ) {
3112 $id = intval( $id );
3113 global $wgHitcounterUpdateFreq, $wgDBtype;
3115 $dbw = wfGetDB( DB_MASTER
);
3116 $pageTable = $dbw->tableName( 'page' );
3117 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3118 $acchitsTable = $dbw->tableName( 'acchits' );
3120 if( $wgHitcounterUpdateFreq <= 1 ) {
3121 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3125 # Not important enough to warrant an error page in case of failure
3126 $oldignore = $dbw->ignoreErrors( true );
3128 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3130 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3131 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3132 # Most of the time (or on SQL errors), skip row count check
3133 $dbw->ignoreErrors( $oldignore );
3137 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3138 $row = $dbw->fetchObject( $res );
3139 $rown = intval( $row->n
);
3140 if( $rown >= $wgHitcounterUpdateFreq ){
3141 wfProfileIn( 'Article::incViewCount-collect' );
3142 $old_user_abort = ignore_user_abort( true );
3144 if($wgDBtype == 'mysql')
3145 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3146 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3147 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3148 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3150 $dbw->query("DELETE FROM $hitcounterTable");
3151 if($wgDBtype == 'mysql') {
3152 $dbw->query('UNLOCK TABLES');
3153 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3154 'WHERE page_id = hc_id');
3157 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3158 "FROM $acchitsTable WHERE page_id = hc_id");
3160 $dbw->query("DROP TABLE $acchitsTable");
3162 ignore_user_abort( $old_user_abort );
3163 wfProfileOut( 'Article::incViewCount-collect' );
3165 $dbw->ignoreErrors( $oldignore );
3169 * The onArticle*() functions are supposed to be a kind of hooks
3170 * which should be called whenever any of the specified actions
3173 * This is a good place to put code to clear caches, for instance.
3175 * This is called on page move and undelete, as well as edit
3177 * @param $title a title object
3180 public static function onArticleCreate( $title ) {
3181 # Update existence markers on article/talk tabs...
3182 if( $title->isTalkPage() ) {
3183 $other = $title->getSubjectPage();
3185 $other = $title->getTalkPage();
3187 $other->invalidateCache();
3188 $other->purgeSquid();
3190 $title->touchLinks();
3191 $title->purgeSquid();
3192 $title->deleteTitleProtection();
3195 public static function onArticleDelete( $title ) {
3196 global $wgMessageCache;
3197 # Update existence markers on article/talk tabs...
3198 if( $title->isTalkPage() ) {
3199 $other = $title->getSubjectPage();
3201 $other = $title->getTalkPage();
3203 $other->invalidateCache();
3204 $other->purgeSquid();
3206 $title->touchLinks();
3207 $title->purgeSquid();
3210 HTMLFileCache
::clearFileCache( $title );
3213 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3214 $wgMessageCache->replace( $title->getDBkey(), false );
3217 if( $title->getNamespace() == NS_FILE
) {
3218 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3219 $update->doUpdate();
3222 if( $title->getNamespace() == NS_USER_TALK
) {
3223 $user = User
::newFromName( $title->getText(), false );
3224 $user->setNewtalk( false );
3229 * Purge caches on page update etc
3231 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3232 global $wgDeferredUpdateList;
3234 // Invalidate caches of articles which include this page
3235 if( $transclusions !== 'skiptransclusions' )
3236 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3238 // Invalidate the caches of all pages which redirect here
3239 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3241 # Purge squid for this page only
3242 $title->purgeSquid();
3244 # Clear file cache for this page only
3245 HTMLFileCache
::clearFileCache( $title );
3251 * Overriden by ImagePage class, only present here to avoid a fatal error
3252 * Called for ?action=revert
3254 public function revert() {
3256 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3260 * Info about this page
3261 * Called for ?action=info when $wgAllowPageInfo is on.
3263 public function info() {
3264 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3266 if( !$wgAllowPageInfo ) {
3267 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3271 $page = $this->mTitle
->getSubjectPage();
3273 $wgOut->setPagetitle( $page->getPrefixedText() );
3274 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3275 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3277 if( !$this->mTitle
->exists() ) {
3278 $wgOut->addHTML( '<div class="noarticletext">' );
3279 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3280 // This doesn't quite make sense; the user is asking for
3281 // information about the _page_, not the message... -- RC
3282 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3284 $msg = $wgUser->isLoggedIn()
3286 : 'noarticletextanon';
3287 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3289 $wgOut->addHTML( '</div>' );
3291 $dbr = wfGetDB( DB_SLAVE
);
3293 'wl_title' => $page->getDBkey(),
3294 'wl_namespace' => $page->getNamespace() );
3295 $numwatchers = $dbr->selectField(
3300 $this->getSelectOptions() );
3302 $pageInfo = $this->pageCountInfo( $page );
3303 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3305 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3306 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3308 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3310 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3312 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3314 $wgOut->addHTML( '</ul>' );
3319 * Return the total number of edits and number of unique editors
3320 * on a given page. If page does not exist, returns false.
3322 * @param $title Title object
3325 protected function pageCountInfo( $title ) {
3326 $id = $title->getArticleId();
3330 $dbr = wfGetDB( DB_SLAVE
);
3331 $rev_clause = array( 'rev_page' => $id );
3332 $edits = $dbr->selectField(
3337 $this->getSelectOptions()
3339 $authors = $dbr->selectField(
3341 'COUNT(DISTINCT rev_user_text)',
3344 $this->getSelectOptions()
3346 return array( 'edits' => $edits, 'authors' => $authors );
3350 * Return a list of templates used by this article.
3351 * Uses the templatelinks table
3353 * @return Array of Title objects
3355 public function getUsedTemplates() {
3357 $id = $this->mTitle
->getArticleID();
3361 $dbr = wfGetDB( DB_SLAVE
);
3362 $res = $dbr->select( array( 'templatelinks' ),
3363 array( 'tl_namespace', 'tl_title' ),
3364 array( 'tl_from' => $id ),
3366 if( $res !== false ) {
3367 foreach( $res as $row ) {
3368 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3371 $dbr->freeResult( $res );
3376 * Returns a list of hidden categories this page is a member of.
3377 * Uses the page_props and categorylinks tables.
3379 * @return Array of Title objects
3381 public function getHiddenCategories() {
3383 $id = $this->mTitle
->getArticleID();
3387 $dbr = wfGetDB( DB_SLAVE
);
3388 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3390 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3391 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3393 if( $res !== false ) {
3394 foreach( $res as $row ) {
3395 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3398 $dbr->freeResult( $res );
3403 * Return an applicable autosummary if one exists for the given edit.
3404 * @param $oldtext String: the previous text of the page.
3405 * @param $newtext String: The submitted text of the page.
3406 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3407 * @return string An appropriate autosummary, or an empty string.
3409 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3410 # Decide what kind of autosummary is needed.
3412 # Redirect autosummaries
3413 $ot = Title
::newFromRedirect( $oldtext );
3414 $rt = Title
::newFromRedirect( $newtext );
3415 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3416 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3419 # New page autosummaries
3420 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3421 # If they're making a new article, give its text, truncated, in the summary.
3423 $truncatedtext = $wgContLang->truncate(
3424 str_replace("\n", ' ', $newtext),
3425 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3427 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3430 # Blanking autosummaries
3431 if( $oldtext != '' && $newtext == '' ) {
3432 return wfMsgForContent( 'autosumm-blank' );
3433 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3434 # Removing more than 90% of the article
3436 $truncatedtext = $wgContLang->truncate(
3438 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3441 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3444 # If we reach this point, there's no applicable autosummary for our case, so our
3445 # autosummary is empty.
3450 * Add the primary page-view wikitext to the output buffer
3451 * Saves the text into the parser cache if possible.
3452 * Updates templatelinks if it is out of date.
3454 * @param $text String
3455 * @param $cache Boolean
3457 public function outputWikiText( $text, $cache = true ) {
3458 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3460 $popts = $wgOut->parserOptions();
3461 $popts->setTidy(true);
3462 $popts->enableLimitReport();
3463 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3464 $popts, true, true, $this->getRevIdFetched() );
3465 $popts->setTidy(false);
3466 $popts->enableLimitReport( false );
3467 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3468 $parserCache = ParserCache
::singleton();
3469 $parserCache->save( $parserOutput, $this, $wgUser );
3471 // Make sure file cache is not used on uncacheable content.
3472 // Output that has magic words in it can still use the parser cache
3473 // (if enabled), though it will generally expire sooner.
3474 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3475 $wgUseFileCache = false;
3478 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3479 // templatelinks table may have become out of sync,
3480 // especially if using variable-based transclusions.
3481 // For paranoia, check if things have changed and if
3482 // so apply updates to the database. This will ensure
3483 // that cascaded protections apply as soon as the changes
3486 # Get templates from templatelinks
3487 $id = $this->mTitle
->getArticleID();
3489 $tlTemplates = array();
3491 $dbr = wfGetDB( DB_SLAVE
);
3492 $res = $dbr->select( array( 'templatelinks' ),
3493 array( 'tl_namespace', 'tl_title' ),
3494 array( 'tl_from' => $id ),
3499 if( $res !== false ) {
3500 foreach( $res as $row ) {
3501 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3505 # Get templates from parser output.
3506 $poTemplates_allns = $parserOutput->getTemplates();
3508 $poTemplates = array ();
3509 foreach ( $poTemplates_allns as $ns_templates ) {
3510 $poTemplates = array_merge( $poTemplates, $ns_templates );
3514 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3516 if( count( $templates_diff ) > 0 ) {
3517 # Whee, link updates time.
3518 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3523 $wgOut->addParserOutput( $parserOutput );
3527 * Update all the appropriate counts in the category table, given that
3528 * we've added the categories $added and deleted the categories $deleted.
3530 * @param $added array The names of categories that were added
3531 * @param $deleted array The names of categories that were deleted
3534 public function updateCategoryCounts( $added, $deleted ) {
3535 $ns = $this->mTitle
->getNamespace();
3536 $dbw = wfGetDB( DB_MASTER
);
3538 # First make sure the rows exist. If one of the "deleted" ones didn't
3539 # exist, we might legitimately not create it, but it's simpler to just
3540 # create it and then give it a negative value, since the value is bogus
3543 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3544 $insertCats = array_merge( $added, $deleted );
3545 if( !$insertCats ) {
3546 # Okay, nothing to do
3549 $insertRows = array();
3550 foreach( $insertCats as $cat ) {
3551 $insertRows[] = array( 'cat_title' => $cat );
3553 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3555 $addFields = array( 'cat_pages = cat_pages + 1' );
3556 $removeFields = array( 'cat_pages = cat_pages - 1' );
3557 if( $ns == NS_CATEGORY
) {
3558 $addFields[] = 'cat_subcats = cat_subcats + 1';
3559 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3560 } elseif( $ns == NS_FILE
) {
3561 $addFields[] = 'cat_files = cat_files + 1';
3562 $removeFields[] = 'cat_files = cat_files - 1';
3569 array( 'cat_title' => $added ),
3577 array( 'cat_title' => $deleted ),