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 if( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
785 # User/User_talk subpages are not modified. (bug 11443)
786 if( !$this->mTitle
->isSubpage() ) {
787 $block = new Block();
788 if( $block->load( $this->mTitle
->getBaseText() ) ) {
789 $wgOut->setRobotpolicy( 'noindex,nofollow' );
794 # Should the parser cache be used?
795 $pcache = $this->useParserCache( $oldid );
796 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
797 if( $wgUser->getOption( 'stubthreshold' ) ) {
798 wfIncrStats( 'pcache_miss_stub' );
801 $wasRedirected = false;
802 if( isset( $this->mRedirectedFrom
) ) {
803 // This is an internally redirected page view.
804 // We'll need a backlink to the source page for navigation.
805 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
806 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
807 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
808 $wgOut->setSubtitle( $s );
810 // Set the fragment if one was specified in the redirect
811 if( strval( $this->mTitle
->getFragment() ) != '' ) {
812 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
813 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
815 $wasRedirected = true;
817 } elseif( !empty( $rdfrom ) ) {
818 // This is an externally redirected view, from some other wiki.
819 // If it was reported from a trusted site, supply a backlink.
820 global $wgRedirectSources;
821 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
822 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
823 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
824 $wgOut->setSubtitle( $s );
825 $wasRedirected = true;
830 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
831 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
832 // Ensure that UI elements requiring revision ID have
833 // the correct version information.
834 $wgOut->setRevisionId( $this->mLatest
);
837 # Fetch content and check for errors
839 # If the article does not exist and was deleted, show the log
840 if( $this->getID() == 0 ) {
841 $this->showDeletionLog();
843 $text = $this->getContent();
844 // For now, check also for ID until getContent actually returns
845 // false for pages that do not exists
846 if( $text === false ||
$this->getID() === 0 ) {
847 # Failed to load, replace text with error message
848 $t = $this->mTitle
->getPrefixedText();
850 $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
851 $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
853 $text = wfMsgExt( 'noarticletext', 'parsemag' );
858 if( $this->getID() === 0 ) {
859 $wgOut->setRobotPolicy( 'noindex,nofollow' );
860 $text = "<div class='noarticletext'>\n$text\n</div>";
861 if( !$this->hasViewableContent() ) {
862 // If there's no backing content, send a 404 Not Found
863 // for better machine handling of broken links.
869 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
872 # Another whitelist check in case oldid is altering the title
873 if( !$this->mTitle
->userCanRead() ) {
874 $wgOut->loginToUse();
877 wfProfileOut( __METHOD__
);
881 # For ?curid=x urls, disallow indexing
882 if( $wgRequest->getInt('curid') )
883 $wgOut->setRobotPolicy( 'noindex,follow' );
885 # We're looking at an old revision
886 if( !empty( $oldid ) ) {
887 $wgOut->setRobotPolicy( 'noindex,nofollow' );
888 if( is_null( $this->mRevision
) ) {
889 // FIXME: This would be a nice place to load the 'no such page' text.
891 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
892 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
893 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
894 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
895 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
896 wfProfileOut( __METHOD__
);
899 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
900 // and we are allowed to see...
906 $wgOut->setRevisionId( $this->getRevIdFetched() );
908 // Pages containing custom CSS or JavaScript get special treatment
909 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
910 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
911 // Give hooks a chance to customise the output
912 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
913 // Wrap the whole lot in a <pre> and don't parse
915 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
916 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
917 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
918 $wgOut->addHTML( "\n</pre>\n" );
920 } else if( $rt = Title
::newFromRedirect( $text ) ) {
921 # Don't append the subtitle if this was an old revision
922 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
923 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
924 $wgOut->addParserOutputNoText( $parseout );
925 } else if( $pcache ) {
926 # Display content and save to parser cache
927 $this->outputWikiText( $text );
929 # Display content, don't attempt to save to parser cache
930 # Don't show section-edit links on old revisions... this way lies madness.
931 if( !$this->isCurrent() ) {
932 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
934 # Display content and don't save to parser cache
935 # With timing hack -- TS 2006-07-26
937 $this->outputWikiText( $text, false );
942 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
943 $this->mTitle
->getPrefixedDBkey()));
946 if( !$this->isCurrent() ) {
947 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
951 /* title may have been set from the cache */
952 $t = $wgOut->getPageTitle();
954 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
956 # For the main page, overwrite the <title> element with the con-
957 # tents of 'pagetitle-view-mainpage' instead of the default (if
959 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
960 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
961 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
965 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
966 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
967 $wgOut->addWikiMsg('anontalkpagetext');
970 # If we have been passed an &rcid= parameter, we want to give the user a
971 # chance to mark this new article as patrolled.
972 if( !empty($rcid) && $this->mTitle
->exists() && $this->mTitle
->userCan('patrol') ) {
974 "<div class='patrollink'>" .
975 wfMsgHtml( 'markaspatrolledlink',
976 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
977 "action=markpatrolled&rcid=$rcid" )
984 if( $wgUseTrackbacks ) {
985 $this->addTrackbacks();
988 $this->viewUpdates();
989 wfProfileOut( __METHOD__
);
992 protected function showDeletionLog() {
993 global $wgUser, $wgOut;
994 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
995 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
996 if( $pager->getNumRows() > 0 ) {
998 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
999 $wgOut->addWikiMsg( 'deleted-notice' );
1001 $loglist->beginLogEventsList() .
1003 $loglist->endLogEventsList()
1005 if( $pager->getNumRows() > 10 ) {
1006 $wgOut->addHTML( $wgUser->getSkin()->link(
1007 SpecialPage
::getTitleFor( 'Log' ),
1008 wfMsgHtml( 'deletelog-fulllog' ),
1010 array( 'type' => 'delete', 'page' => $this->mTitle
->getPrefixedText() )
1013 $wgOut->addHTML( '</div>' );
1018 * Should the parser cache be used?
1020 protected function useParserCache( $oldid ) {
1021 global $wgUser, $wgEnableParserCache;
1023 return $wgEnableParserCache
1024 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1027 && !$this->mTitle
->isCssOrJsPage()
1028 && !$this->mTitle
->isCssJsSubpage();
1033 * @param $target Title object of destination to redirect
1034 * @param $appendSubtitle Boolean [optional]
1035 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1037 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1038 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1040 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1041 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
1043 if( $appendSubtitle ) {
1044 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1046 $sk = $wgUser->getSkin();
1048 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1050 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1052 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1053 '<span class="redirectText">'.$link.'</span>';
1057 public function addTrackbacks() {
1058 global $wgOut, $wgUser;
1059 $dbr = wfGetDB( DB_SLAVE
);
1060 $tbs = $dbr->select( 'trackbacks',
1061 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1062 array('tb_page' => $this->getID() )
1064 if( !$dbr->numRows($tbs) ) return;
1067 while( $o = $dbr->fetchObject($tbs) ) {
1069 if( $wgUser->isAllowed( 'trackback' ) ) {
1070 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1071 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1072 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1075 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1082 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1083 $this->mTitle
->invalidateCache();
1086 public function deletetrackback() {
1087 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1088 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1089 $wgOut->addWikiMsg( 'sessionfailure' );
1093 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1094 if( count($permission_errors) ) {
1095 $wgOut->showPermissionsErrorPage( $permission_errors );
1099 $db = wfGetDB( DB_MASTER
);
1100 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1102 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1103 $this->mTitle
->invalidateCache();
1106 public function render() {
1108 $wgOut->setArticleBodyOnly(true);
1113 * Handle action=purge
1115 public function purge() {
1116 global $wgUser, $wgRequest, $wgOut;
1117 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1118 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1123 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1124 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1125 $form = "<form method=\"post\" action=\"$action\">\n" .
1126 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1128 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1129 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1130 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1131 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1132 $wgOut->addHTML( $top . $form . $bottom );
1137 * Perform the actions of a page purging
1139 public function doPurge() {
1141 // Invalidate the cache
1142 $this->mTitle
->invalidateCache();
1145 // Commit the transaction before the purge is sent
1146 $dbw = wfGetDB( DB_MASTER
);
1147 $dbw->immediateCommit();
1150 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1151 $update->doUpdate();
1153 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1154 global $wgMessageCache;
1155 if( $this->getID() == 0 ) {
1158 $text = $this->getRawText();
1160 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1165 * Insert a new empty page record for this article.
1166 * This *must* be followed up by creating a revision
1167 * and running $this->updateToLatest( $rev_id );
1168 * or else the record will be left in a funky state.
1169 * Best if all done inside a transaction.
1171 * @param $dbw Database
1172 * @return int The newly created page_id key, or false if the title already existed
1175 public function insertOn( $dbw ) {
1176 wfProfileIn( __METHOD__
);
1178 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1179 $dbw->insert( 'page', array(
1180 'page_id' => $page_id,
1181 'page_namespace' => $this->mTitle
->getNamespace(),
1182 'page_title' => $this->mTitle
->getDBkey(),
1183 'page_counter' => 0,
1184 'page_restrictions' => '',
1185 'page_is_redirect' => 0, # Will set this shortly...
1187 'page_random' => wfRandom(),
1188 'page_touched' => $dbw->timestamp(),
1189 'page_latest' => 0, # Fill this in shortly...
1190 'page_len' => 0, # Fill this in shortly...
1191 ), __METHOD__
, 'IGNORE' );
1193 $affected = $dbw->affectedRows();
1195 $newid = $dbw->insertId();
1196 $this->mTitle
->resetArticleId( $newid );
1198 wfProfileOut( __METHOD__
);
1199 return $affected ?
$newid : false;
1203 * Update the page record to point to a newly saved revision.
1205 * @param $dbw Database object
1206 * @param $revision Revision: For ID number, and text used to set
1207 length and redirect status fields
1208 * @param $lastRevision Integer: if given, will not overwrite the page field
1209 * when different from the currently set value.
1210 * Giving 0 indicates the new page flag should be set
1212 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1213 * removing rows in redirect table.
1214 * @return bool true on success, false on failure
1217 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1218 wfProfileIn( __METHOD__
);
1220 $text = $revision->getText();
1221 $rt = Title
::newFromRedirect( $text );
1223 $conditions = array( 'page_id' => $this->getId() );
1224 if( !is_null( $lastRevision ) ) {
1225 # An extra check against threads stepping on each other
1226 $conditions['page_latest'] = $lastRevision;
1229 $dbw->update( 'page',
1231 'page_latest' => $revision->getId(),
1232 'page_touched' => $dbw->timestamp(),
1233 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1234 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1235 'page_len' => strlen( $text ),
1240 $result = $dbw->affectedRows() != 0;
1242 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1245 wfProfileOut( __METHOD__
);
1250 * Add row to the redirect table if this is a redirect, remove otherwise.
1252 * @param $dbw Database
1253 * @param $redirectTitle a title object pointing to the redirect target,
1254 * or NULL if this is not a redirect
1255 * @param $lastRevIsRedirect If given, will optimize adding and
1256 * removing rows in redirect table.
1257 * @return bool true on success, false on failure
1260 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1261 // Always update redirects (target link might have changed)
1262 // Update/Insert if we don't know if the last revision was a redirect or not
1263 // Delete if changing from redirect to non-redirect
1264 $isRedirect = !is_null($redirectTitle);
1265 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1266 wfProfileIn( __METHOD__
);
1268 // This title is a redirect, Add/Update row in the redirect table
1269 $set = array( /* SET */
1270 'rd_namespace' => $redirectTitle->getNamespace(),
1271 'rd_title' => $redirectTitle->getDBkey(),
1272 'rd_from' => $this->getId(),
1274 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1276 // This is not a redirect, remove row from redirect table
1277 $where = array( 'rd_from' => $this->getId() );
1278 $dbw->delete( 'redirect', $where, __METHOD__
);
1280 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1281 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1283 wfProfileOut( __METHOD__
);
1284 return ( $dbw->affectedRows() != 0 );
1290 * If the given revision is newer than the currently set page_latest,
1291 * update the page record. Otherwise, do nothing.
1293 * @param $dbw Database object
1294 * @param $revision Revision object
1296 public function updateIfNewerOn( &$dbw, $revision ) {
1297 wfProfileIn( __METHOD__
);
1298 $row = $dbw->selectRow(
1299 array( 'revision', 'page' ),
1300 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1302 'page_id' => $this->getId(),
1303 'page_latest=rev_id' ),
1306 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1307 wfProfileOut( __METHOD__
);
1310 $prev = $row->rev_id
;
1311 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1313 # No or missing previous revision; mark the page as new
1315 $lastRevIsRedirect = null;
1317 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1318 wfProfileOut( __METHOD__
);
1323 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1324 * @return string Complete article text, or null if error
1326 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1327 wfProfileIn( __METHOD__
);
1328 if( strval( $section ) == '' ) {
1329 // Whole-page edit; let the whole text through
1331 if( is_null($edittime) ) {
1332 $rev = Revision
::newFromTitle( $this->mTitle
);
1334 $dbw = wfGetDB( DB_MASTER
);
1335 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1338 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1339 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1342 $oldtext = $rev->getText();
1344 if( $section == 'new' ) {
1345 # Inserting a new section
1346 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1347 $text = strlen( trim( $oldtext ) ) > 0
1348 ?
"{$oldtext}\n\n{$subject}{$text}"
1349 : "{$subject}{$text}";
1351 # Replacing an existing section; roll out the big guns
1353 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1356 wfProfileOut( __METHOD__
);
1361 * @deprecated use Article::doEdit()
1363 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1364 wfDeprecated( __METHOD__
);
1365 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1366 ( $isminor ? EDIT_MINOR
: 0 ) |
1367 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1368 ( $bot ? EDIT_FORCE_BOT
: 0 );
1370 # If this is a comment, add the summary as headline
1371 if( $comment && $summary != "" ) {
1372 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1375 $this->doEdit( $text, $summary, $flags );
1377 $dbw = wfGetDB( DB_MASTER
);
1379 if(!$this->mTitle
->userIsWatching()) {
1385 if( $this->mTitle
->userIsWatching() ) {
1391 $this->doRedirect( $this->isRedirect( $text ) );
1395 * @deprecated use Article::doEdit()
1397 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1398 wfDeprecated( __METHOD__
);
1399 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1400 ( $minor ? EDIT_MINOR
: 0 ) |
1401 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1403 $status = $this->doEdit( $text, $summary, $flags );
1404 if( !$status->isOK() ) {
1408 $dbw = wfGetDB( DB_MASTER
);
1410 if(!$this->mTitle
->userIsWatching()) {
1416 if( $this->mTitle
->userIsWatching() ) {
1423 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1424 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1426 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1433 * Change an existing article or create a new article. Updates RC and all necessary caches,
1434 * optionally via the deferred update array.
1436 * $wgUser must be set before calling this function.
1438 * @param $text String: new text
1439 * @param $summary String: edit summary
1440 * @param $flags Integer bitfield:
1442 * Article is known or assumed to be non-existent, create a new one
1444 * Article is known or assumed to be pre-existing, update it
1446 * Mark this edit minor, if the user is allowed to do so
1448 * Do not log the change in recentchanges
1450 * Mark the edit a "bot" edit regardless of user rights
1451 * EDIT_DEFER_UPDATES
1452 * Defer some of the updates until the end of index.php
1454 * Fill in blank summaries with generated text where possible
1456 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1457 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1458 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1459 * edit-already-exists error will be returned. These two conditions are also possible with
1460 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1462 * @param $baseRevId the revision ID this edit was based off, if any
1463 * @param $user Optional user object, $wgUser will be used if not passed
1465 * @return Status object. Possible errors:
1466 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1467 * edit-gone-missing: In update mode, but the article didn't exist
1468 * edit-conflict: In update mode, the article changed unexpectedly
1469 * edit-no-change: Warning that the text was the same as before
1470 * edit-already-exists: In creation mode, but the article already exists
1472 * Extensions may define additional errors.
1474 * $return->value will contain an associative array with members as follows:
1475 * new: Boolean indicating if the function attempted to create a new article
1476 * revision: The revision object for the inserted revision, or null
1478 * Compatibility note: this function previously returned a boolean value indicating success/failure
1480 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1481 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1483 # Low-level sanity check
1484 if( $this->mTitle
->getText() == '' ) {
1485 throw new MWException( 'Something is trying to edit an article with an empty title' );
1488 wfProfileIn( __METHOD__
);
1490 $user = is_null($user) ?
$wgUser : $user;
1491 $status = Status
::newGood( array() );
1493 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1494 $this->loadPageData();
1496 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1497 $aid = $this->mTitle
->getArticleID();
1499 $flags |
= EDIT_UPDATE
;
1505 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1506 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1508 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1509 wfProfileOut( __METHOD__
);
1510 if( $status->isOK() ) {
1511 $status->fatal( 'edit-hook-aborted');
1516 # Silently ignore EDIT_MINOR if not allowed
1517 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1518 $bot = $flags & EDIT_FORCE_BOT
;
1520 $oldtext = $this->getRawText(); // current revision
1521 $oldsize = strlen( $oldtext );
1523 # Provide autosummaries if one is not provided and autosummaries are enabled.
1524 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1525 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1528 $editInfo = $this->prepareTextForEdit( $text );
1529 $text = $editInfo->pst
;
1530 $newsize = strlen( $text );
1532 $dbw = wfGetDB( DB_MASTER
);
1533 $now = wfTimestampNow();
1535 if( $flags & EDIT_UPDATE
) {
1536 # Update article, but only if changed.
1537 $status->value
['new'] = false;
1538 # Make sure the revision is either completely inserted or not inserted at all
1539 if( !$wgDBtransactions ) {
1540 $userAbort = ignore_user_abort( true );
1545 $changed = ( strcmp( $text, $oldtext ) != 0 );
1548 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1549 - (int)$this->isCountable( $oldtext );
1550 $this->mTotalAdjustment
= 0;
1552 if( !$this->mLatest
) {
1553 # Article gone missing
1554 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1555 $status->fatal( 'edit-gone-missing' );
1556 wfProfileOut( __METHOD__
);
1560 $revision = new Revision( array(
1561 'page' => $this->getId(),
1562 'comment' => $summary,
1563 'minor_edit' => $isminor,
1565 'parent_id' => $this->mLatest
,
1566 'user' => $user->getId(),
1567 'user_text' => $user->getName(),
1571 $revisionId = $revision->insertOn( $dbw );
1575 # Note that we use $this->mLatest instead of fetching a value from the master DB
1576 # during the course of this function. This makes sure that EditPage can detect
1577 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1578 # before this function is called. A previous function used a separate query, this
1579 # creates a window where concurrent edits can cause an ignored edit conflict.
1580 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1583 /* Belated edit conflict! Run away!! */
1584 $status->fatal( 'edit-conflict' );
1585 # Delete the invalid revision if the DB is not transactional
1586 if( !$wgDBtransactions ) {
1587 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1592 global $wgUseRCPatrol;
1593 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1594 # Update recentchanges
1595 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1596 # Mark as patrolled if the user can do so
1597 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan('autopatrol');
1598 # Add RC row to the DB
1599 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1600 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1601 $revisionId, $patrolled
1603 # Log auto-patrolled edits
1605 PatrolLog
::record( $rc, true );
1608 $user->incEditCount();
1612 $status->warning( 'edit-no-change' );
1614 // Keep the same revision ID, but do some updates on it
1615 $revisionId = $this->getRevIdFetched();
1616 // Update page_touched, this is usually implicit in the page update
1617 // Other cache updates are done in onArticleEdit()
1618 $this->mTitle
->invalidateCache();
1621 if( !$wgDBtransactions ) {
1622 ignore_user_abort( $userAbort );
1624 // Now that ignore_user_abort is restored, we can respond to fatal errors
1625 if( !$status->isOK() ) {
1626 wfProfileOut( __METHOD__
);
1630 # Invalidate cache of this article and all pages using this article
1631 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1632 Article
::onArticleEdit( $this->mTitle
, 'skiptransclusions' );
1633 # Update links tables, site stats, etc.
1634 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1636 # Create new article
1637 $status->value
['new'] = true;
1639 # Set statistics members
1640 # We work out if it's countable after PST to avoid counter drift
1641 # when articles are created with {{subst:}}
1642 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1643 $this->mTotalAdjustment
= 1;
1647 # Add the page record; stake our claim on this title!
1648 # This will return false if the article already exists
1649 $newid = $this->insertOn( $dbw );
1651 if( $newid === false ) {
1653 $status->fatal( 'edit-already-exists' );
1654 wfProfileOut( __METHOD__
);
1658 # Save the revision text...
1659 $revision = new Revision( array(
1661 'comment' => $summary,
1662 'minor_edit' => $isminor,
1664 'user' => $user->getId(),
1665 'user_text' => $user->getName(),
1667 $revisionId = $revision->insertOn( $dbw );
1669 $this->mTitle
->resetArticleID( $newid );
1671 # Update the page record with revision data
1672 $this->updateRevisionOn( $dbw, $revision, 0 );
1674 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1675 # Update recentchanges
1676 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1677 global $wgUseRCPatrol, $wgUseNPPatrol;
1678 # Mark as patrolled if the user can do so
1679 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $this->mTitle
->userCan('autopatrol');
1680 # Add RC row to the DB
1681 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1682 '', strlen($text), $revisionId, $patrolled );
1683 # Log auto-patrolled edits
1685 PatrolLog
::record( $rc, true );
1688 $user->incEditCount();
1691 # Update links, etc.
1692 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1695 Article
::onArticleCreate( $this->mTitle
);
1697 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1698 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1701 # Do updates right now unless deferral was requested
1702 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1706 // Return the new revision (or null) to the caller
1707 $status->value
['revision'] = $revision;
1709 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1710 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status ) );
1712 wfProfileOut( __METHOD__
);
1717 * @deprecated wrapper for doRedirect
1719 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1720 wfDeprecated( __METHOD__
);
1721 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1725 * Output a redirect back to the article.
1726 * This is typically used after an edit.
1728 * @param $noRedir Boolean: add redirect=no
1729 * @param $sectionAnchor String: section to redirect to, including "#"
1730 * @param $extraQuery String: extra query params
1732 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1735 $query = 'redirect=no';
1737 $query .= "&$query";
1739 $query = $extraQuery;
1741 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1745 * Mark this particular edit/page as patrolled
1747 public function markpatrolled() {
1748 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1749 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1751 # If we haven't been given an rc_id value, we can't do anything
1752 $rcid = (int) $wgRequest->getVal('rcid');
1753 $rc = RecentChange
::newFromId($rcid);
1754 if( is_null($rc) ) {
1755 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1759 #It would be nice to see where the user had actually come from, but for now just guess
1760 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1761 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1763 $dbw = wfGetDB( DB_MASTER
);
1764 $errors = $rc->doMarkPatrolled();
1766 if( in_array(array('rcpatroldisabled'), $errors) ) {
1767 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1771 if( in_array(array('hookaborted'), $errors) ) {
1772 // The hook itself has handled any output
1776 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1777 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1778 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1779 $wgOut->returnToMain( false, $return );
1783 if( !empty($errors) ) {
1784 $wgOut->showPermissionsErrorPage( $errors );
1789 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1790 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1791 $wgOut->returnToMain( false, $return );
1795 * User-interface handler for the "watch" action
1798 public function watch() {
1799 global $wgUser, $wgOut;
1800 if( $wgUser->isAnon() ) {
1801 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1804 if( wfReadOnly() ) {
1805 $wgOut->readOnlyPage();
1808 if( $this->doWatch() ) {
1809 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1810 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1811 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1813 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1817 * Add this page to $wgUser's watchlist
1818 * @return bool true on successful watch operation
1820 public function doWatch() {
1822 if( $wgUser->isAnon() ) {
1825 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1826 $wgUser->addWatch( $this->mTitle
);
1827 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1833 * User interface handler for the "unwatch" action.
1835 public function unwatch() {
1836 global $wgUser, $wgOut;
1837 if( $wgUser->isAnon() ) {
1838 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1841 if( wfReadOnly() ) {
1842 $wgOut->readOnlyPage();
1845 if( $this->doUnwatch() ) {
1846 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1847 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1848 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1850 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1854 * Stop watching a page
1855 * @return bool true on successful unwatch
1857 public function doUnwatch() {
1859 if( $wgUser->isAnon() ) {
1862 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1863 $wgUser->removeWatch( $this->mTitle
);
1864 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1870 * action=protect handler
1872 public function protect() {
1873 $form = new ProtectionForm( $this );
1878 * action=unprotect handler (alias)
1880 public function unprotect() {
1885 * Update the article's restriction field, and leave a log entry.
1887 * @param $limit Array: set of restriction keys
1888 * @param $reason String
1889 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1890 * @param $expiry Array: per restriction type expiration
1891 * @return bool true on success
1893 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1894 global $wgUser, $wgRestrictionTypes, $wgContLang;
1896 $id = $this->mTitle
->getArticleID();
1897 if( $id <= 0 ||
wfReadOnly() ||
!$this->mTitle
->userCan('protect') ) {
1905 // Take this opportunity to purge out expired restrictions
1906 Title
::purgeExpiredRestrictions();
1908 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1909 # we expect a single selection, but the schema allows otherwise.
1911 $updated = Article
::flattenRestrictions( $limit );
1913 foreach( $wgRestrictionTypes as $action ) {
1914 if( isset( $expiry[$action] ) ) {
1915 # Get current restrictions on $action
1916 $aLimits = $this->mTitle
->getRestrictions( $action );
1917 $current[$action] = implode( '', $aLimits );
1918 # Are any actual restrictions being dealt with here?
1919 $aRChanged = count($aLimits) ||
!empty($limit[$action]);
1920 # If something changed, we need to log it. Checking $aRChanged
1921 # assures that "unprotecting" a page that is not protected does
1922 # not log just because the expiry was "changed".
1923 if( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
1929 $current = Article
::flattenRestrictions( $current );
1931 $changed = ($changed ||
$current != $updated );
1932 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1933 $protect = ( $updated != '' );
1935 # If nothing's changed, do nothing
1937 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1939 $dbw = wfGetDB( DB_MASTER
);
1941 # Prepare a null revision to be added to the history
1942 $modified = $current != '' && $protect;
1944 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1946 $comment_type = 'unprotectedarticle';
1948 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1950 # Only restrictions with the 'protect' right can cascade...
1951 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1952 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1953 # The schema allows multiple restrictions
1954 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
1956 $cascade_description = '';
1958 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1962 $comment .= ": $reason";
1964 $editComment = $comment;
1965 $encodedExpiry = array();
1966 $protect_description = '';
1967 foreach( $limit as $action => $restrictions ) {
1968 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
1969 if( $restrictions != '' ) {
1970 $protect_description .= "[$action=$restrictions] (";
1971 if( $encodedExpiry[$action] != 'infinity' ) {
1972 $protect_description .= wfMsgForContent( 'protect-expiring',
1973 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1974 $wgContLang->date( $expiry[$action], false, false ) ,
1975 $wgContLang->time( $expiry[$action], false, false ) );
1977 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1979 $protect_description .= ') ';
1982 $protect_description = trim($protect_description);
1984 if( $protect_description && $protect )
1985 $editComment .= " ($protect_description)";
1987 $editComment .= "$cascade_description";
1988 # Update restrictions table
1989 foreach( $limit as $action => $restrictions ) {
1990 if($restrictions != '' ) {
1991 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1992 array( 'pr_page' => $id,
1993 'pr_type' => $action,
1994 'pr_level' => $restrictions,
1995 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
1996 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
1998 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1999 'pr_type' => $action ), __METHOD__
);
2003 # Insert a null revision
2004 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2005 $nullRevId = $nullRevision->insertOn( $dbw );
2007 $latest = $this->getLatest();
2008 # Update page record
2009 $dbw->update( 'page',
2011 'page_touched' => $dbw->timestamp(),
2012 'page_restrictions' => '',
2013 'page_latest' => $nullRevId
2014 ), array( /* WHERE */
2016 ), 'Article::protect'
2019 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2020 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2022 # Update the protection log
2023 $log = new LogPage( 'protect' );
2025 $params = array($protect_description,$cascade ?
'cascade' : '');
2026 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
2028 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2032 } # End "changed" check
2038 * Take an array of page restrictions and flatten it to a string
2039 * suitable for insertion into the page_restrictions field.
2040 * @param $limit Array
2043 protected static function flattenRestrictions( $limit ) {
2044 if( !is_array( $limit ) ) {
2045 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2049 foreach( $limit as $action => $restrictions ) {
2050 if( $restrictions != '' ) {
2051 $bits[] = "$action=$restrictions";
2054 return implode( ':', $bits );
2058 * Auto-generates a deletion reason
2059 * @param &$hasHistory Boolean: whether the page has a history
2061 public function generateReason( &$hasHistory ) {
2063 $dbw = wfGetDB( DB_MASTER
);
2064 // Get the last revision
2065 $rev = Revision
::newFromTitle( $this->mTitle
);
2066 if( is_null( $rev ) )
2069 // Get the article's contents
2070 $contents = $rev->getText();
2072 // If the page is blank, use the text from the previous revision,
2073 // which can only be blank if there's a move/import/protect dummy revision involved
2074 if( $contents == '' ) {
2075 $prev = $rev->getPrevious();
2077 $contents = $prev->getText();
2082 // Find out if there was only one contributor
2083 // Only scan the last 20 revisions
2085 $res = $dbw->select( 'revision', 'rev_user_text',
2086 array( 'rev_page' => $this->getID() ), __METHOD__
,
2087 array( 'LIMIT' => $limit )
2089 if( $res === false )
2090 // This page has no revisions, which is very weird
2092 if( $res->numRows() > 1 )
2095 $hasHistory = false;
2096 $row = $dbw->fetchObject( $res );
2097 $onlyAuthor = $row->rev_user_text
;
2098 // Try to find a second contributor
2099 foreach( $res as $row ) {
2100 if( $row->rev_user_text
!= $onlyAuthor ) {
2101 $onlyAuthor = false;
2105 $dbw->freeResult( $res );
2107 // Generate the summary with a '$1' placeholder
2109 // The current revision is blank and the one before is also
2110 // blank. It's just not our lucky day
2111 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2114 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2116 $reason = wfMsgForContent( 'excontent', '$1' );
2119 if( $reason == '-' ) {
2120 // Allow these UI messages to be blanked out cleanly
2124 // Replace newlines with spaces to prevent uglyness
2125 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2126 // Calculate the maximum amount of chars to get
2127 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2128 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2129 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2130 // Remove possible unfinished links
2131 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2132 // Now replace the '$1' placeholder
2133 $reason = str_replace( '$1', $contents, $reason );
2139 * UI entry point for page deletion
2141 public function delete() {
2142 global $wgUser, $wgOut, $wgRequest;
2144 $confirm = $wgRequest->wasPosted() &&
2145 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2147 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2148 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2150 $reason = $this->DeleteReasonList
;
2152 if( $reason != 'other' && $this->DeleteReason
!= '' ) {
2153 // Entry from drop down menu + additional comment
2154 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2155 } elseif( $reason == 'other' ) {
2156 $reason = $this->DeleteReason
;
2158 # Flag to hide all contents of the archived revisions
2159 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2161 # This code desperately needs to be totally rewritten
2163 # Read-only check...
2164 if( wfReadOnly() ) {
2165 $wgOut->readOnlyPage();
2170 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2172 if( count( $permission_errors ) > 0 ) {
2173 $wgOut->showPermissionsErrorPage( $permission_errors );
2177 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2179 # Better double-check that it hasn't been deleted yet!
2180 $dbw = wfGetDB( DB_MASTER
);
2181 $conds = $this->mTitle
->pageCond();
2182 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2183 if( $latest === false ) {
2184 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2185 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2186 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2190 # Hack for big sites
2191 $bigHistory = $this->isBigDeletion();
2192 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2193 global $wgLang, $wgDeleteRevisionsLimit;
2194 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2195 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2200 $this->doDelete( $reason, $suppress );
2201 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2203 } elseif( $this->mTitle
->userIsWatching() ) {
2209 // Generate deletion reason
2210 $hasHistory = false;
2211 if( !$reason ) $reason = $this->generateReason($hasHistory);
2213 // If the page has a history, insert a warning
2214 if( $hasHistory && !$confirm ) {
2215 $skin = $wgUser->getSkin();
2216 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2218 global $wgLang, $wgDeleteRevisionsLimit;
2219 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2220 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2224 return $this->confirmDelete( $reason );
2228 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2230 public function isBigDeletion() {
2231 global $wgDeleteRevisionsLimit;
2232 if( $wgDeleteRevisionsLimit ) {
2233 $revCount = $this->estimateRevisionCount();
2234 return $revCount > $wgDeleteRevisionsLimit;
2240 * @return int approximate revision count
2242 public function estimateRevisionCount() {
2243 $dbr = wfGetDB( DB_SLAVE
);
2244 // For an exact count...
2245 //return $dbr->selectField( 'revision', 'COUNT(*)',
2246 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2247 return $dbr->estimateRowCount( 'revision', '*',
2248 array( 'rev_page' => $this->getId() ), __METHOD__
);
2252 * Get the last N authors
2253 * @param $num Integer: number of revisions to get
2254 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2255 * @return array Array of authors, duplicates not removed
2257 public function getLastNAuthors( $num, $revLatest = 0 ) {
2258 wfProfileIn( __METHOD__
);
2259 // First try the slave
2260 // If that doesn't have the latest revision, try the master
2262 $db = wfGetDB( DB_SLAVE
);
2264 $res = $db->select( array( 'page', 'revision' ),
2265 array( 'rev_id', 'rev_user_text' ),
2267 'page_namespace' => $this->mTitle
->getNamespace(),
2268 'page_title' => $this->mTitle
->getDBkey(),
2269 'rev_page = page_id'
2270 ), __METHOD__
, $this->getSelectOptions( array(
2271 'ORDER BY' => 'rev_timestamp DESC',
2276 wfProfileOut( __METHOD__
);
2279 $row = $db->fetchObject( $res );
2280 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2281 $db = wfGetDB( DB_MASTER
);
2286 } while ( $continue );
2288 $authors = array( $row->rev_user_text
);
2289 while ( $row = $db->fetchObject( $res ) ) {
2290 $authors[] = $row->rev_user_text
;
2292 wfProfileOut( __METHOD__
);
2297 * Output deletion confirmation dialog
2298 * @param $reason String: prefilled reason
2300 public function confirmDelete( $reason ) {
2301 global $wgOut, $wgUser;
2303 wfDebug( "Article::confirmDelete\n" );
2305 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2306 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2307 $wgOut->addWikiMsg( 'confirmdeletetext' );
2309 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2310 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2312 <td class='mw-input'>" .
2313 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2314 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2320 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2322 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2323 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2324 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2325 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2326 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2327 "<tr id=\"wpDeleteReasonListRow\">
2328 <td class='mw-label'>" .
2329 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2331 <td class='mw-input'>" .
2332 Xml
::listDropDown( 'wpDeleteReasonList',
2333 wfMsgForContent( 'deletereason-dropdown' ),
2334 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2337 <tr id=\"wpDeleteReasonRow\">
2338 <td class='mw-label'>" .
2339 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2341 <td class='mw-input'>" .
2342 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2343 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2348 <td class='mw-input'>" .
2349 Xml
::checkLabel( wfMsg( 'watchthis' ),
2350 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2356 <td class='mw-submit'>" .
2357 Xml
::submitButton( wfMsg( 'deletepage' ),
2358 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2361 Xml
::closeElement( 'table' ) .
2362 Xml
::closeElement( 'fieldset' ) .
2363 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2364 Xml
::closeElement( 'form' );
2366 if( $wgUser->isAllowed( 'editinterface' ) ) {
2367 $skin = $wgUser->getSkin();
2368 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2369 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2372 $wgOut->addHTML( $form );
2373 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2377 * Perform a deletion and output success or failure messages
2379 public function doDelete( $reason, $suppress = false ) {
2380 global $wgOut, $wgUser;
2381 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2384 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2385 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2386 $deleted = $this->mTitle
->getPrefixedText();
2388 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2389 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2391 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2393 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2394 $wgOut->returnToMain( false );
2395 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2397 if( $error == '' ) {
2398 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2399 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2400 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2402 $wgOut->showFatalError( $error );
2409 * Back-end article deletion
2410 * Deletes the article with database consistency, writes logs, purges caches
2413 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2414 global $wgUseSquid, $wgDeferredUpdateList;
2415 global $wgUseTrackbacks;
2417 wfDebug( __METHOD__
."\n" );
2419 $dbw = wfGetDB( DB_MASTER
);
2420 $ns = $this->mTitle
->getNamespace();
2421 $t = $this->mTitle
->getDBkey();
2422 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2424 if( $t == '' ||
$id == 0 ) {
2428 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2429 array_push( $wgDeferredUpdateList, $u );
2431 // Bitfields to further suppress the content
2434 // This should be 15...
2435 $bitfield |
= Revision
::DELETED_TEXT
;
2436 $bitfield |
= Revision
::DELETED_COMMENT
;
2437 $bitfield |
= Revision
::DELETED_USER
;
2438 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2440 $bitfield = 'rev_deleted';
2444 // For now, shunt the revision data into the archive table.
2445 // Text is *not* removed from the text table; bulk storage
2446 // is left intact to avoid breaking block-compression or
2447 // immutable storage schemes.
2449 // For backwards compatibility, note that some older archive
2450 // table entries will have ar_text and ar_flags fields still.
2452 // In the future, we may keep revisions and mark them with
2453 // the rev_deleted field, which is reserved for this purpose.
2454 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2456 'ar_namespace' => 'page_namespace',
2457 'ar_title' => 'page_title',
2458 'ar_comment' => 'rev_comment',
2459 'ar_user' => 'rev_user',
2460 'ar_user_text' => 'rev_user_text',
2461 'ar_timestamp' => 'rev_timestamp',
2462 'ar_minor_edit' => 'rev_minor_edit',
2463 'ar_rev_id' => 'rev_id',
2464 'ar_text_id' => 'rev_text_id',
2465 'ar_text' => '\'\'', // Be explicit to appease
2466 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2467 'ar_len' => 'rev_len',
2468 'ar_page_id' => 'page_id',
2469 'ar_deleted' => $bitfield
2472 'page_id = rev_page'
2476 # Delete restrictions for it
2477 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2479 # Now that it's safely backed up, delete it
2480 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2481 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2487 # If using cascading deletes, we can skip some explicit deletes
2488 if( !$dbw->cascadingDeletes() ) {
2489 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2491 if($wgUseTrackbacks)
2492 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2494 # Delete outgoing links
2495 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2496 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2497 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2498 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2499 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2500 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2501 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2504 # If using cleanup triggers, we can skip some manual deletes
2505 if( !$dbw->cleanupTriggers() ) {
2506 # Clean up recentchanges entries...
2507 $dbw->delete( 'recentchanges',
2508 array( 'rc_type != '.RC_LOG
,
2509 'rc_namespace' => $this->mTitle
->getNamespace(),
2510 'rc_title' => $this->mTitle
->getDBKey() ),
2512 $dbw->delete( 'recentchanges',
2513 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2518 Article
::onArticleDelete( $this->mTitle
);
2520 # Fix category table counts
2522 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2523 foreach( $res as $row ) {
2524 $cats []= $row->cl_to
;
2526 $this->updateCategoryCounts( array(), $cats );
2528 # Clear the cached article id so the interface doesn't act like we exist
2529 $this->mTitle
->resetArticleID( 0 );
2530 $this->mTitle
->mArticleID
= 0;
2532 # Log the deletion, if the page was suppressed, log it at Oversight instead
2533 $logtype = $suppress ?
'suppress' : 'delete';
2534 $log = new LogPage( $logtype );
2536 # Make sure logging got through
2537 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2545 * Roll back the most recent consecutive set of edits to a page
2546 * from the same user; fails if there are no eligible edits to
2547 * roll back to, e.g. user is the sole contributor. This function
2548 * performs permissions checks on $wgUser, then calls commitRollback()
2549 * to do the dirty work
2551 * @param $fromP String: Name of the user whose edits to rollback.
2552 * @param $summary String: Custom summary. Set to default summary if empty.
2553 * @param $token String: Rollback token.
2554 * @param $bot Boolean: If true, mark all reverted edits as bot.
2556 * @param $resultDetails Array: contains result-specific array of additional values
2557 * 'alreadyrolled' : 'current' (rev)
2558 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2560 * @return array of errors, each error formatted as
2561 * array(messagekey, param1, param2, ...).
2562 * On success, the array is empty. This array can also be passed to
2563 * OutputPage::showPermissionsErrorPage().
2565 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2567 $resultDetails = null;
2570 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2571 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2572 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2574 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2575 $errors[] = array( 'sessionfailure' );
2577 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2578 $errors[] = array( 'actionthrottledtext' );
2580 # If there were errors, bail out now
2581 if( !empty( $errors ) )
2584 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2588 * Backend implementation of doRollback(), please refer there for parameter
2589 * and return value documentation
2591 * NOTE: This function does NOT check ANY permissions, it just commits the
2592 * rollback to the DB Therefore, you should only call this function direct-
2593 * ly if you want to use custom permissions checks. If you don't, use
2594 * doRollback() instead.
2596 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2597 global $wgUseRCPatrol, $wgUser, $wgLang;
2598 $dbw = wfGetDB( DB_MASTER
);
2600 if( wfReadOnly() ) {
2601 return array( array( 'readonlytext' ) );
2604 # Get the last editor
2605 $current = Revision
::newFromTitle( $this->mTitle
);
2606 if( is_null( $current ) ) {
2607 # Something wrong... no page?
2608 return array(array('notanarticle'));
2611 $from = str_replace( '_', ' ', $fromP );
2612 if( $from != $current->getUserText() ) {
2613 $resultDetails = array( 'current' => $current );
2614 return array(array('alreadyrolled',
2615 htmlspecialchars($this->mTitle
->getPrefixedText()),
2616 htmlspecialchars($fromP),
2617 htmlspecialchars($current->getUserText())
2621 # Get the last edit not by this guy
2622 $user = intval( $current->getUser() );
2623 $user_text = $dbw->addQuotes( $current->getUserText() );
2624 $s = $dbw->selectRow( 'revision',
2625 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2626 array( 'rev_page' => $current->getPage(),
2627 "rev_user != {$user} OR rev_user_text != {$user_text}"
2629 array( 'USE INDEX' => 'page_timestamp',
2630 'ORDER BY' => 'rev_timestamp DESC' )
2632 if( $s === false ) {
2633 # No one else ever edited this page
2634 return array(array('cantrollback'));
2635 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2636 # Only admins can see this text
2637 return array(array('notvisiblerev'));
2641 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2642 # Mark all reverted edits as bot
2645 if( $wgUseRCPatrol ) {
2646 # Mark all reverted edits as patrolled
2647 $set['rc_patrolled'] = 1;
2651 $dbw->update( 'recentchanges', $set,
2653 'rc_cur_id' => $current->getPage(),
2654 'rc_user_text' => $current->getUserText(),
2655 "rc_timestamp > '{$s->rev_timestamp}'",
2660 # Generate the edit summary if necessary
2661 $target = Revision
::newFromId( $s->rev_id
);
2662 if( empty( $summary ) ){
2663 $summary = wfMsgForContent( 'revertpage' );
2666 # Allow the custom summary to use the same args as the default message
2668 $target->getUserText(), $from, $s->rev_id
,
2669 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2670 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2672 $summary = wfMsgReplaceArgs( $summary, $args );
2675 $flags = EDIT_UPDATE
;
2677 if( $wgUser->isAllowed('minoredit') )
2678 $flags |
= EDIT_MINOR
;
2680 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2681 $flags |
= EDIT_FORCE_BOT
;
2682 # Actually store the edit
2683 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2684 if( !empty( $status->value
['revision'] ) ) {
2685 $revId = $status->value
['revision']->getId();
2690 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2692 $resultDetails = array(
2693 'summary' => $summary,
2694 'current' => $current,
2695 'target' => $target,
2702 * User interface for rollback operations
2704 public function rollback() {
2705 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2708 $result = $this->doRollback(
2709 $wgRequest->getVal( 'from' ),
2710 $wgRequest->getText( 'summary' ),
2711 $wgRequest->getVal( 'token' ),
2712 $wgRequest->getBool( 'bot' ),
2716 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2717 $wgOut->rateLimited();
2720 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2721 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2722 $errArray = $result[0];
2723 $errMsg = array_shift( $errArray );
2724 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2725 if( isset( $details['current'] ) ){
2726 $current = $details['current'];
2727 if( $current->getComment() != '' ) {
2728 $wgOut->addWikiMsgArray( 'editcomment', array(
2729 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2734 # Display permissions errors before read-only message -- there's no
2735 # point in misleading the user into thinking the inability to rollback
2736 # is only temporary.
2737 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2738 # array_diff is completely broken for arrays of arrays, sigh. Re-
2739 # move any 'readonlytext' error manually.
2741 foreach( $result as $error ) {
2742 if( $error != array( 'readonlytext' ) ) {
2746 $wgOut->showPermissionsErrorPage( $out );
2749 if( $result == array( array( 'readonlytext' ) ) ) {
2750 $wgOut->readOnlyPage();
2754 $current = $details['current'];
2755 $target = $details['target'];
2756 $newId = $details['newid'];
2757 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2758 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2759 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2760 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2761 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2762 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2763 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2764 $wgOut->returnToMain( false, $this->mTitle
);
2766 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2767 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2768 $de->showDiff( '', '' );
2774 * Do standard deferred updates after page view
2776 public function viewUpdates() {
2777 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2778 # Don't update page view counters on views from bot users (bug 14044)
2779 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2780 Article
::incViewCount( $this->getID() );
2781 $u = new SiteStatsUpdate( 1, 0, 0 );
2782 array_push( $wgDeferredUpdateList, $u );
2784 # Update newtalk / watchlist notification status
2785 $wgUser->clearNotification( $this->mTitle
);
2789 * Prepare text which is about to be saved.
2790 * Returns a stdclass with source, pst and output members
2792 public function prepareTextForEdit( $text, $revid=null ) {
2793 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2795 return $this->mPreparedEdit
;
2798 $edit = (object)array();
2799 $edit->revid
= $revid;
2800 $edit->newText
= $text;
2801 $edit->pst
= $this->preSaveTransform( $text );
2802 $options = new ParserOptions
;
2803 $options->setTidy( true );
2804 $options->enableLimitReport();
2805 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2806 $edit->oldText
= $this->getContent();
2807 $this->mPreparedEdit
= $edit;
2812 * Do standard deferred updates after page edit.
2813 * Update links tables, site stats, search index and message cache.
2814 * Purges pages that include this page if the text was changed here.
2815 * Every 100th edit, prune the recent changes table.
2818 * @param $text New text of the article
2819 * @param $summary Edit summary
2820 * @param $minoredit Minor edit
2821 * @param $timestamp_of_pagechange Timestamp associated with the page change
2822 * @param $newid rev_id value of the new revision
2823 * @param $changed Whether or not the content actually changed
2825 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2826 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2828 wfProfileIn( __METHOD__
);
2831 # Be careful not to double-PST: $text is usually already PST-ed once
2832 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2833 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2834 $editInfo = $this->prepareTextForEdit( $text, $newid );
2836 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2837 $editInfo = $this->mPreparedEdit
;
2840 # Save it to the parser cache
2841 if( $wgEnableParserCache ) {
2842 $parserCache = ParserCache
::singleton();
2843 $parserCache->save( $editInfo->output
, $this, $wgUser );
2846 # Update the links tables
2847 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
, false );
2848 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2851 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2853 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2854 if( 0 == mt_rand( 0, 99 ) ) {
2855 // Flush old entries from the `recentchanges` table; we do this on
2856 // random requests so as to avoid an increase in writes for no good reason
2858 $dbw = wfGetDB( DB_MASTER
);
2859 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2860 $recentchanges = $dbw->tableName( 'recentchanges' );
2861 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2862 $dbw->query( $sql );
2866 $id = $this->getID();
2867 $title = $this->mTitle
->getPrefixedDBkey();
2868 $shortTitle = $this->mTitle
->getDBkey();
2871 wfProfileOut( __METHOD__
);
2875 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2876 array_push( $wgDeferredUpdateList, $u );
2877 $u = new SearchUpdate( $id, $title, $text );
2878 array_push( $wgDeferredUpdateList, $u );
2880 # If this is another user's talk page, update newtalk
2881 # Don't do this if $changed = false otherwise some idiot can null-edit a
2882 # load of user talk pages and piss people off, nor if it's a minor edit
2883 # by a properly-flagged bot.
2884 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2885 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2886 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2887 $other = User
::newFromName( $shortTitle, false );
2889 wfDebug( __METHOD__
.": invalid username\n" );
2890 } elseif( User
::isIP( $shortTitle ) ) {
2891 // An anonymous user
2892 $other->setNewtalk( true );
2893 } elseif( $other->isLoggedIn() ) {
2894 $other->setNewtalk( true );
2896 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2901 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2902 $wgMessageCache->replace( $shortTitle, $text );
2905 wfProfileOut( __METHOD__
);
2909 * Perform article updates on a special page creation.
2911 * @param $rev Revision object
2913 * @todo This is a shitty interface function. Kill it and replace the
2914 * other shitty functions like editUpdates and such so it's not needed
2917 public function createUpdates( $rev ) {
2918 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2919 $this->mTotalAdjustment
= 1;
2920 $this->editUpdates( $rev->getText(), $rev->getComment(),
2921 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2925 * Generate the navigation links when browsing through an article revisions
2926 * It shows the information as:
2927 * Revision as of \<date\>; view current revision
2928 * \<- Previous version | Next Version -\>
2930 * @param $oldid String: revision ID of this article revision
2932 public function setOldSubtitle( $oldid = 0 ) {
2933 global $wgLang, $wgOut, $wgUser;
2935 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
2939 $revision = Revision
::newFromId( $oldid );
2941 $current = ( $oldid == $this->mLatest
);
2942 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2943 $sk = $wgUser->getSkin();
2945 ?
wfMsgHtml( 'currentrevisionlink' )
2946 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'currentrevisionlink' ) );
2948 ?
wfMsgHtml( 'diff' )
2949 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
2950 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2952 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2953 : wfMsgHtml( 'previousrevision' );
2955 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
2956 : wfMsgHtml( 'diff' );
2957 $nextlink = $current
2958 ?
wfMsgHtml( 'nextrevision' )
2959 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2960 $nextdiff = $current
2961 ?
wfMsgHtml( 'diff' )
2962 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
2965 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2966 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2967 if( $revision->isCurrent() ) {
2968 // We don't handle top deleted edits too well
2969 $cdel = wfMsgHtml( 'rev-delundel' );
2970 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2971 // If revision was hidden from sysops
2972 $cdel = wfMsgHtml( 'rev-delundel' );
2974 $cdel = $sk->makeKnownLinkObj( $revdel,
2975 wfMsgHtml('rev-delundel'),
2976 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2977 '&oldid=' . urlencode( $oldid ) );
2978 // Bolden oversighted content
2979 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2980 $cdel = "<strong>$cdel</strong>";
2982 $cdel = "(<small>$cdel</small>) ";
2984 # Show user links if allowed to see them. Normally they
2985 # are hidden regardless, but since we can already see the text here...
2986 $userlinks = $sk->revUserTools( $revision, false );
2988 $m = wfMsg( 'revision-info-current' );
2989 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2990 ?
'revision-info-current'
2993 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" .
2995 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgHtml( 'revision-nav', $prevdiff,
2996 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2997 $wgOut->setSubtitle( $r );
3001 * This function is called right before saving the wikitext,
3002 * so we can do things like signatures and links-in-context.
3004 * @param $text String
3006 public function preSaveTransform( $text ) {
3007 global $wgParser, $wgUser;
3008 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3011 /* Caching functions */
3014 * checkLastModified returns true if it has taken care of all
3015 * output to the client that is necessary for this request.
3016 * (that is, it has sent a cached version of the page)
3018 protected function tryFileCache() {
3019 static $called = false;
3021 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3025 if( $this->isFileCacheable() ) {
3026 $cache = new HTMLFileCache( $this->mTitle
);
3027 if( $cache->isFileCacheGood( $this->mTouched
) ) {
3028 wfDebug( "Article::tryFileCache(): about to load file\n" );
3029 $cache->loadFromFileCache();
3032 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3033 ob_start( array(&$cache, 'saveToFileCache' ) );
3036 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3042 * Check if the page can be cached
3045 public function isFileCacheable() {
3047 if( HTMLFileCache
::useFileCache() ) {
3048 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3049 // Extension may have reason to disable file caching on some pages.
3051 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3058 * Loads page_touched and returns a value indicating if it should be used
3061 public function checkTouched() {
3062 if( !$this->mDataLoaded
) {
3063 $this->loadPageData();
3065 return !$this->mIsRedirect
;
3069 * Get the page_touched field
3071 public function getTouched() {
3072 # Ensure that page data has been loaded
3073 if( !$this->mDataLoaded
) {
3074 $this->loadPageData();
3076 return $this->mTouched
;
3080 * Get the page_latest field
3082 public function getLatest() {
3083 if( !$this->mDataLoaded
) {
3084 $this->loadPageData();
3086 return $this->mLatest
;
3090 * Edit an article without doing all that other stuff
3091 * The article must already exist; link tables etc
3092 * are not updated, caches are not flushed.
3094 * @param $text String: text submitted
3095 * @param $comment String: comment submitted
3096 * @param $minor Boolean: whereas it's a minor modification
3098 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3099 wfProfileIn( __METHOD__
);
3101 $dbw = wfGetDB( DB_MASTER
);
3102 $revision = new Revision( array(
3103 'page' => $this->getId(),
3105 'comment' => $comment,
3106 'minor_edit' => $minor ?
1 : 0,
3108 $revision->insertOn( $dbw );
3109 $this->updateRevisionOn( $dbw, $revision );
3111 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3113 wfProfileOut( __METHOD__
);
3117 * Used to increment the view counter
3119 * @param $id Integer: article id
3121 public static function incViewCount( $id ) {
3122 $id = intval( $id );
3123 global $wgHitcounterUpdateFreq, $wgDBtype;
3125 $dbw = wfGetDB( DB_MASTER
);
3126 $pageTable = $dbw->tableName( 'page' );
3127 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3128 $acchitsTable = $dbw->tableName( 'acchits' );
3130 if( $wgHitcounterUpdateFreq <= 1 ) {
3131 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3135 # Not important enough to warrant an error page in case of failure
3136 $oldignore = $dbw->ignoreErrors( true );
3138 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3140 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3141 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3142 # Most of the time (or on SQL errors), skip row count check
3143 $dbw->ignoreErrors( $oldignore );
3147 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3148 $row = $dbw->fetchObject( $res );
3149 $rown = intval( $row->n
);
3150 if( $rown >= $wgHitcounterUpdateFreq ){
3151 wfProfileIn( 'Article::incViewCount-collect' );
3152 $old_user_abort = ignore_user_abort( true );
3154 if($wgDBtype == 'mysql')
3155 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3156 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3157 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3158 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3160 $dbw->query("DELETE FROM $hitcounterTable");
3161 if($wgDBtype == 'mysql') {
3162 $dbw->query('UNLOCK TABLES');
3163 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3164 'WHERE page_id = hc_id');
3167 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3168 "FROM $acchitsTable WHERE page_id = hc_id");
3170 $dbw->query("DROP TABLE $acchitsTable");
3172 ignore_user_abort( $old_user_abort );
3173 wfProfileOut( 'Article::incViewCount-collect' );
3175 $dbw->ignoreErrors( $oldignore );
3179 * The onArticle*() functions are supposed to be a kind of hooks
3180 * which should be called whenever any of the specified actions
3183 * This is a good place to put code to clear caches, for instance.
3185 * This is called on page move and undelete, as well as edit
3187 * @param $title a title object
3190 public static function onArticleCreate( $title ) {
3191 # Update existence markers on article/talk tabs...
3192 if( $title->isTalkPage() ) {
3193 $other = $title->getSubjectPage();
3195 $other = $title->getTalkPage();
3197 $other->invalidateCache();
3198 $other->purgeSquid();
3200 $title->touchLinks();
3201 $title->purgeSquid();
3202 $title->deleteTitleProtection();
3205 public static function onArticleDelete( $title ) {
3206 global $wgMessageCache;
3207 # Update existence markers on article/talk tabs...
3208 if( $title->isTalkPage() ) {
3209 $other = $title->getSubjectPage();
3211 $other = $title->getTalkPage();
3213 $other->invalidateCache();
3214 $other->purgeSquid();
3216 $title->touchLinks();
3217 $title->purgeSquid();
3220 HTMLFileCache
::clearFileCache( $title );
3223 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3224 $wgMessageCache->replace( $title->getDBkey(), false );
3227 if( $title->getNamespace() == NS_FILE
) {
3228 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3229 $update->doUpdate();
3232 if( $title->getNamespace() == NS_USER_TALK
) {
3233 $user = User
::newFromName( $title->getText(), false );
3234 $user->setNewtalk( false );
3239 * Purge caches on page update etc
3241 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3242 global $wgDeferredUpdateList;
3244 // Invalidate caches of articles which include this page
3245 if( $transclusions !== 'skiptransclusions' )
3246 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3248 // Invalidate the caches of all pages which redirect here
3249 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3251 # Purge squid for this page only
3252 $title->purgeSquid();
3254 # Clear file cache for this page only
3255 HTMLFileCache
::clearFileCache( $title );
3261 * Overriden by ImagePage class, only present here to avoid a fatal error
3262 * Called for ?action=revert
3264 public function revert() {
3266 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3270 * Info about this page
3271 * Called for ?action=info when $wgAllowPageInfo is on.
3273 public function info() {
3274 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3276 if( !$wgAllowPageInfo ) {
3277 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3281 $page = $this->mTitle
->getSubjectPage();
3283 $wgOut->setPagetitle( $page->getPrefixedText() );
3284 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3285 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3287 if( !$this->mTitle
->exists() ) {
3288 $wgOut->addHTML( '<div class="noarticletext">' );
3289 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3290 // This doesn't quite make sense; the user is asking for
3291 // information about the _page_, not the message... -- RC
3292 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3294 $msg = $wgUser->isLoggedIn()
3296 : 'noarticletextanon';
3297 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3299 $wgOut->addHTML( '</div>' );
3301 $dbr = wfGetDB( DB_SLAVE
);
3303 'wl_title' => $page->getDBkey(),
3304 'wl_namespace' => $page->getNamespace() );
3305 $numwatchers = $dbr->selectField(
3310 $this->getSelectOptions() );
3312 $pageInfo = $this->pageCountInfo( $page );
3313 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3315 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3316 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3318 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3320 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3322 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3324 $wgOut->addHTML( '</ul>' );
3329 * Return the total number of edits and number of unique editors
3330 * on a given page. If page does not exist, returns false.
3332 * @param $title Title object
3335 protected function pageCountInfo( $title ) {
3336 $id = $title->getArticleId();
3340 $dbr = wfGetDB( DB_SLAVE
);
3341 $rev_clause = array( 'rev_page' => $id );
3342 $edits = $dbr->selectField(
3347 $this->getSelectOptions()
3349 $authors = $dbr->selectField(
3351 'COUNT(DISTINCT rev_user_text)',
3354 $this->getSelectOptions()
3356 return array( 'edits' => $edits, 'authors' => $authors );
3360 * Return a list of templates used by this article.
3361 * Uses the templatelinks table
3363 * @return Array of Title objects
3365 public function getUsedTemplates() {
3367 $id = $this->mTitle
->getArticleID();
3371 $dbr = wfGetDB( DB_SLAVE
);
3372 $res = $dbr->select( array( 'templatelinks' ),
3373 array( 'tl_namespace', 'tl_title' ),
3374 array( 'tl_from' => $id ),
3376 if( $res !== false ) {
3377 foreach( $res as $row ) {
3378 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3381 $dbr->freeResult( $res );
3386 * Returns a list of hidden categories this page is a member of.
3387 * Uses the page_props and categorylinks tables.
3389 * @return Array of Title objects
3391 public function getHiddenCategories() {
3393 $id = $this->mTitle
->getArticleID();
3397 $dbr = wfGetDB( DB_SLAVE
);
3398 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3400 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3401 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3403 if( $res !== false ) {
3404 foreach( $res as $row ) {
3405 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3408 $dbr->freeResult( $res );
3413 * Return an applicable autosummary if one exists for the given edit.
3414 * @param $oldtext String: the previous text of the page.
3415 * @param $newtext String: The submitted text of the page.
3416 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3417 * @return string An appropriate autosummary, or an empty string.
3419 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3420 # Decide what kind of autosummary is needed.
3422 # Redirect autosummaries
3423 $ot = Title
::newFromRedirect( $oldtext );
3424 $rt = Title
::newFromRedirect( $newtext );
3425 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3426 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3429 # New page autosummaries
3430 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3431 # If they're making a new article, give its text, truncated, in the summary.
3433 $truncatedtext = $wgContLang->truncate(
3434 str_replace("\n", ' ', $newtext),
3435 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3437 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3440 # Blanking autosummaries
3441 if( $oldtext != '' && $newtext == '' ) {
3442 return wfMsgForContent( 'autosumm-blank' );
3443 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3444 # Removing more than 90% of the article
3446 $truncatedtext = $wgContLang->truncate(
3448 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3451 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3454 # If we reach this point, there's no applicable autosummary for our case, so our
3455 # autosummary is empty.
3460 * Add the primary page-view wikitext to the output buffer
3461 * Saves the text into the parser cache if possible.
3462 * Updates templatelinks if it is out of date.
3464 * @param $text String
3465 * @param $cache Boolean
3467 public function outputWikiText( $text, $cache = true ) {
3468 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3470 $popts = $wgOut->parserOptions();
3471 $popts->setTidy(true);
3472 $popts->enableLimitReport();
3473 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3474 $popts, true, true, $this->getRevIdFetched() );
3475 $popts->setTidy(false);
3476 $popts->enableLimitReport( false );
3477 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3478 $parserCache = ParserCache
::singleton();
3479 $parserCache->save( $parserOutput, $this, $wgUser );
3481 // Make sure file cache is not used on uncacheable content.
3482 // Output that has magic words in it can still use the parser cache
3483 // (if enabled), though it will generally expire sooner.
3484 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3485 $wgUseFileCache = false;
3488 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3489 // templatelinks table may have become out of sync,
3490 // especially if using variable-based transclusions.
3491 // For paranoia, check if things have changed and if
3492 // so apply updates to the database. This will ensure
3493 // that cascaded protections apply as soon as the changes
3496 # Get templates from templatelinks
3497 $id = $this->mTitle
->getArticleID();
3499 $tlTemplates = array();
3501 $dbr = wfGetDB( DB_SLAVE
);
3502 $res = $dbr->select( array( 'templatelinks' ),
3503 array( 'tl_namespace', 'tl_title' ),
3504 array( 'tl_from' => $id ),
3509 if( $res !== false ) {
3510 foreach( $res as $row ) {
3511 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3515 # Get templates from parser output.
3516 $poTemplates_allns = $parserOutput->getTemplates();
3518 $poTemplates = array ();
3519 foreach ( $poTemplates_allns as $ns_templates ) {
3520 $poTemplates = array_merge( $poTemplates, $ns_templates );
3524 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3526 if( count( $templates_diff ) > 0 ) {
3527 # Whee, link updates time.
3528 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3533 $wgOut->addParserOutput( $parserOutput );
3537 * Update all the appropriate counts in the category table, given that
3538 * we've added the categories $added and deleted the categories $deleted.
3540 * @param $added array The names of categories that were added
3541 * @param $deleted array The names of categories that were deleted
3544 public function updateCategoryCounts( $added, $deleted ) {
3545 $ns = $this->mTitle
->getNamespace();
3546 $dbw = wfGetDB( DB_MASTER
);
3548 # First make sure the rows exist. If one of the "deleted" ones didn't
3549 # exist, we might legitimately not create it, but it's simpler to just
3550 # create it and then give it a negative value, since the value is bogus
3553 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3554 $insertCats = array_merge( $added, $deleted );
3555 if( !$insertCats ) {
3556 # Okay, nothing to do
3559 $insertRows = array();
3560 foreach( $insertCats as $cat ) {
3561 $insertRows[] = array( 'cat_title' => $cat );
3563 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3565 $addFields = array( 'cat_pages = cat_pages + 1' );
3566 $removeFields = array( 'cat_pages = cat_pages - 1' );
3567 if( $ns == NS_CATEGORY
) {
3568 $addFields[] = 'cat_subcats = cat_subcats + 1';
3569 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3570 } elseif( $ns == NS_FILE
) {
3571 $addFields[] = 'cat_files = cat_files + 1';
3572 $removeFields[] = 'cat_files = cat_files - 1';
3579 array( 'cat_title' => $added ),
3587 array( 'cat_title' => $deleted ),