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 $row = $dbr->selectRow( 'redirect',
88 array('rd_namespace', 'rd_title'),
89 array('rd_from' => $this->getID() ),
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
::newFromRedirectRecurse( $text ); // recurse through to only get the final target
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 * Get the text that needs to be saved in order to undo all revisions
266 * between $undo and $undoafter. Revisions must belong to the same page,
267 * must exist and must not be deleted
268 * @param $undo Revision
269 * @param $undoafter Revision Must be an earlier revision than $undo
270 * @return mixed string on success, false on failure
272 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
273 $undo_text = $undo->getText();
274 $undoafter_text = $undoafter->getText();
275 $cur_text = $this->getContent();
276 if ( $cur_text == $undo_text ) {
277 # No use doing a merge if it's just a straight revert.
278 return $undoafter_text;
281 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
287 * @return int The oldid of the article that is to be shown, 0 for the
290 public function getOldID() {
291 if( is_null( $this->mOldId
) ) {
292 $this->mOldId
= $this->getOldIDFromRequest();
294 return $this->mOldId
;
298 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
300 * @return int The old id for the request
302 public function getOldIDFromRequest() {
304 $this->mRedirectUrl
= false;
305 $oldid = $wgRequest->getVal( 'oldid' );
306 if( isset( $oldid ) ) {
307 $oldid = intval( $oldid );
308 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
309 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
313 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
315 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
316 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
329 * Load the revision (including text) into this object
331 function loadContent() {
332 if( $this->mContentLoaded
) return;
333 wfProfileIn( __METHOD__
);
335 $oldid = $this->getOldID();
336 # Pre-fill content with error message so that if something
337 # fails we'll have something telling us what we intended.
338 $this->mOldId
= $oldid;
339 $this->fetchContent( $oldid );
340 wfProfileOut( __METHOD__
);
345 * Fetch a page record with the given conditions
346 * @param $dbr Database object
347 * @param $conditions Array
349 protected function pageData( $dbr, $conditions ) {
363 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
364 $row = $dbr->selectRow(
370 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
375 * @param $dbr Database object
376 * @param $title Title object
378 public function pageDataFromTitle( $dbr, $title ) {
379 return $this->pageData( $dbr, array(
380 'page_namespace' => $title->getNamespace(),
381 'page_title' => $title->getDBkey() ) );
385 * @param $dbr Database
388 protected function pageDataFromId( $dbr, $id ) {
389 return $this->pageData( $dbr, array( 'page_id' => $id ) );
393 * Set the general counter, title etc data loaded from
396 * @param $data Database row object or "fromdb"
398 public function loadPageData( $data = 'fromdb' ) {
399 if( $data === 'fromdb' ) {
400 $dbr = wfGetDB( DB_MASTER
);
401 $data = $this->pageDataFromId( $dbr, $this->getId() );
404 $lc = LinkCache
::singleton();
406 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
408 $this->mTitle
->mArticleID
= $data->page_id
;
410 # Old-fashioned restrictions
411 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
413 $this->mCounter
= $data->page_counter
;
414 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
415 $this->mIsRedirect
= $data->page_is_redirect
;
416 $this->mLatest
= $data->page_latest
;
418 if( is_object( $this->mTitle
) ) {
419 $lc->addBadLinkObj( $this->mTitle
);
421 $this->mTitle
->mArticleID
= 0;
424 $this->mDataLoaded
= true;
428 * Get text of an article from database
429 * Does *NOT* follow redirects.
430 * @param $oldid Int: 0 for whatever the latest revision is
433 function fetchContent( $oldid = 0 ) {
434 if( $this->mContentLoaded
) {
435 return $this->mContent
;
438 $dbr = wfGetDB( DB_MASTER
);
440 # Pre-fill content with error message so that if something
441 # fails we'll have something telling us what we intended.
442 $t = $this->mTitle
->getPrefixedText();
443 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
444 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
447 $revision = Revision
::newFromId( $oldid );
448 if( is_null( $revision ) ) {
449 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
452 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
454 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
457 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
458 $this->loadPageData( $data );
460 if( !$this->mDataLoaded
) {
461 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
463 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
466 $this->loadPageData( $data );
468 $revision = Revision
::newFromId( $this->mLatest
);
469 if( is_null( $revision ) ) {
470 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$this->mLatest}\n" );
475 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
476 // We should instead work with the Revision object when we need it...
477 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
479 $this->mUser
= $revision->getUser();
480 $this->mUserText
= $revision->getUserText();
481 $this->mComment
= $revision->getComment();
482 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
484 $this->mRevIdFetched
= $revision->getId();
485 $this->mContentLoaded
= true;
486 $this->mRevision
=& $revision;
488 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
490 return $this->mContent
;
494 * Read/write accessor to select FOR UPDATE
496 * @param $x Mixed: FIXME
498 public function forUpdate( $x = NULL ) {
499 return wfSetVar( $this->mForUpdate
, $x );
503 * Get the database which should be used for reads
506 * @deprecated - just call wfGetDB( DB_MASTER ) instead
509 wfDeprecated( __METHOD__
);
510 return wfGetDB( DB_MASTER
);
514 * Get options for all SELECT statements
516 * @param $options Array: an optional options array which'll be appended to
518 * @return Array: options
520 protected function getSelectOptions( $options = '' ) {
521 if( $this->mForUpdate
) {
522 if( is_array( $options ) ) {
523 $options[] = 'FOR UPDATE';
525 $options = 'FOR UPDATE';
532 * @return int Page ID
534 public function getID() {
535 if( $this->mTitle
) {
536 return $this->mTitle
->getArticleID();
543 * @return bool Whether or not the page exists in the database
545 public function exists() {
546 return $this->getId() > 0;
550 * Check if this page is something we're going to be showing
551 * some sort of sensible content for. If we return false, page
552 * views (plain action=view) will return an HTTP 404 response,
553 * so spiders and robots can know they're following a bad link.
557 public function hasViewableContent() {
558 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
562 * @return int The view count for the page
564 public function getCount() {
565 if( -1 == $this->mCounter
) {
566 $id = $this->getID();
570 $dbr = wfGetDB( DB_SLAVE
);
571 $this->mCounter
= $dbr->selectField( 'page',
573 array( 'page_id' => $id ),
575 $this->getSelectOptions()
579 return $this->mCounter
;
583 * Determine whether a page would be suitable for being counted as an
584 * article in the site_stats table based on the title & its content
586 * @param $text String: text to analyze
589 public function isCountable( $text ) {
590 global $wgUseCommaCount;
592 $token = $wgUseCommaCount ?
',' : '[[';
593 return $this->mTitle
->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
597 * Tests if the article text represents a redirect
599 * @param $text String: FIXME
602 public function isRedirect( $text = false ) {
603 if( $text === false ) {
604 if( $this->mDataLoaded
) {
605 return $this->mIsRedirect
;
607 // Apparently loadPageData was never called
608 $this->loadContent();
609 $titleObj = Title
::newFromRedirectRecurse( $this->fetchContent() );
611 $titleObj = Title
::newFromRedirect( $text );
613 return $titleObj !== NULL;
617 * Returns true if the currently-referenced revision is the current edit
618 * to this page (and it exists).
621 public function isCurrent() {
622 # If no oldid, this is the current version.
623 if( $this->getOldID() == 0 ) {
626 return $this->exists() && isset($this->mRevision
) && $this->mRevision
->isCurrent();
630 * Loads everything except the text
631 * This isn't necessary for all uses, so it's only done if needed.
633 protected function loadLastEdit() {
634 if( -1 != $this->mUser
)
637 # New or non-existent articles have no user information
638 $id = $this->getID();
639 if( 0 == $id ) return;
641 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
642 if( !is_null( $this->mLastRevision
) ) {
643 $this->mUser
= $this->mLastRevision
->getUser();
644 $this->mUserText
= $this->mLastRevision
->getUserText();
645 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
646 $this->mComment
= $this->mLastRevision
->getComment();
647 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
648 $this->mRevIdFetched
= $this->mLastRevision
->getId();
652 public function getTimestamp() {
653 // Check if the field has been filled by ParserCache::get()
654 if( !$this->mTimestamp
) {
655 $this->loadLastEdit();
657 return wfTimestamp(TS_MW
, $this->mTimestamp
);
660 public function getUser() {
661 $this->loadLastEdit();
665 public function getUserText() {
666 $this->loadLastEdit();
667 return $this->mUserText
;
670 public function getComment() {
671 $this->loadLastEdit();
672 return $this->mComment
;
675 public function getMinorEdit() {
676 $this->loadLastEdit();
677 return $this->mMinorEdit
;
680 /* Use this to fetch the rev ID used on page views */
681 public function getRevIdFetched() {
682 $this->loadLastEdit();
683 return $this->mRevIdFetched
;
687 * @param $limit Integer: default 0.
688 * @param $offset Integer: default 0.
690 public function getContributors($limit = 0, $offset = 0) {
691 # XXX: this is expensive; cache this info somewhere.
694 $dbr = wfGetDB( DB_SLAVE
);
695 $revTable = $dbr->tableName( 'revision' );
696 $userTable = $dbr->tableName( 'user' );
697 $user = $this->getUser();
698 $pageId = $this->getId();
700 $hideBit = Revision
::DELETED_USER
; // username hidden?
702 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
703 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
704 WHERE rev_page = $pageId
705 AND rev_user != $user
706 AND rev_deleted & $hideBit = 0
707 GROUP BY rev_user, rev_user_text, user_real_name
708 ORDER BY timestamp DESC";
710 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
711 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
713 $sql .= ' '. $this->getSelectOptions();
715 $res = $dbr->query($sql, __METHOD__
);
717 return new UserArrayFromResult( $res );
721 * This is the default action of the script: just view the page of
724 public function view() {
725 global $wgUser, $wgOut, $wgRequest, $wgContLang;
726 global $wgEnableParserCache, $wgStylePath, $wgParser;
727 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
728 global $wgDefaultRobotPolicy;
730 # Let the parser know if this is the printable version
731 if( $wgOut->isPrintable() ) {
732 $wgOut->parserOptions()->setIsPrintable( true );
735 wfProfileIn( __METHOD__
);
737 # Get variables from query string
738 $oldid = $this->getOldID();
740 # Try client and file cache
741 if( $oldid === 0 && $this->checkTouched() ) {
744 $parserCache = ParserCache
::singleton();
745 $wgOut->setETag( $parserCache->getETag($this, $wgOut->parserOptions()) );
747 # Is is client cached?
748 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
749 wfProfileOut( __METHOD__
);
752 } else if( $this->tryFileCache() ) {
753 # tell wgOut that output is taken care of
755 $this->viewUpdates();
756 wfProfileOut( __METHOD__
);
761 $ns = $this->mTitle
->getNamespace(); # shortcut
762 $sk = $wgUser->getSkin();
764 # getOldID may want us to redirect somewhere else
765 if( $this->mRedirectUrl
) {
766 $wgOut->redirect( $this->mRedirectUrl
);
767 wfProfileOut( __METHOD__
);
771 $diff = $wgRequest->getVal( 'diff' );
772 $rcid = $wgRequest->getVal( 'rcid' );
773 $rdfrom = $wgRequest->getVal( 'rdfrom' );
774 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
775 $purge = $wgRequest->getVal( 'action' ) == 'purge';
778 $wgOut->setArticleFlag( true );
780 # Discourage indexing of printable versions, but encourage following
781 if( $wgOut->isPrintable() ) {
782 $policy = 'noindex,follow';
783 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
784 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
785 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
786 # Honour customised robot policies for this namespace
787 $policy = $wgNamespaceRobotPolicies[$ns];
789 $policy = $wgDefaultRobotPolicy;
791 $wgOut->setRobotPolicy( $policy );
793 # Allow admins to see deleted content if explicitly requested
794 $delId = $diff ?
$diff : $oldid;
795 $unhide = $wgRequest->getInt('unhide') == 1
796 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $delId );
797 # If we got diff and oldid in the query, we want to see a
798 # diff page instead of the article.
799 if( !is_null( $diff ) ) {
800 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
802 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
803 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
804 // DifferenceEngine directly fetched the revision:
805 $this->mRevIdFetched
= $de->mNewid
;
806 $de->showDiffPage( $diffOnly );
808 // Needed to get the page's current revision
809 $this->loadPageData();
810 if( $diff == 0 ||
$diff == $this->mLatest
) {
811 # Run view updates for current revision only
812 $this->viewUpdates();
814 wfProfileOut( __METHOD__
);
818 if( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
819 # User/User_talk subpages are not modified. (bug 11443)
820 if( !$this->mTitle
->isSubpage() ) {
821 $block = new Block();
822 if( $block->load( $this->mTitle
->getBaseText() ) ) {
823 $wgOut->setRobotpolicy( 'noindex,nofollow' );
828 # Should the parser cache be used?
829 $pcache = $this->useParserCache( $oldid );
830 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
831 if( $wgUser->getOption( 'stubthreshold' ) ) {
832 wfIncrStats( 'pcache_miss_stub' );
835 $wasRedirected = false;
836 if( isset( $this->mRedirectedFrom
) ) {
837 // This is an internally redirected page view.
838 // We'll need a backlink to the source page for navigation.
839 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
840 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
841 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
842 $wgOut->setSubtitle( $s );
844 // Set the fragment if one was specified in the redirect
845 if( strval( $this->mTitle
->getFragment() ) != '' ) {
846 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
847 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
850 // Add a <link rel="canonical"> tag
851 $wgOut->addLink( array( 'rel' => 'canonical',
852 'href' => $this->mTitle
->getLocalURL() )
854 $wasRedirected = true;
856 } elseif( !empty( $rdfrom ) ) {
857 // This is an externally redirected view, from some other wiki.
858 // If it was reported from a trusted site, supply a backlink.
859 global $wgRedirectSources;
860 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
861 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
862 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
863 $wgOut->setSubtitle( $s );
864 $wasRedirected = true;
868 # Allow a specific header on talk pages, like [[MediaWiki:Talkpagetext]]
869 if( $this->mTitle
->isTalkPage() ) {
870 $msg = wfMsgNoTrans( 'talkpageheader' );
871 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
872 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
877 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
878 if( $pcache && $wgOut->tryParserCache( $this ) ) {
879 // Ensure that UI elements requiring revision ID have
880 // the correct version information.
881 $wgOut->setRevisionId( $this->mLatest
);
884 # Fetch content and check for errors
886 # If the article does not exist and was deleted/moved, show the log
887 if( $this->getID() == 0 ) {
890 $text = $this->getContent();
891 // For now, check also for ID until getContent actually returns
892 // false for pages that do not exists
893 if( $text === false ||
$this->getID() === 0 ) {
894 # Failed to load, replace text with error message
895 $t = $this->mTitle
->getPrefixedText();
897 $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
898 $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
899 // Always use page content for pages in the MediaWiki namespace
900 // since it contains the default message
901 } elseif ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
) {
902 $text = wfMsgExt( 'noarticletext', 'parsemag' );
907 if( $this->getID() === 0 ) {
908 $wgOut->setRobotPolicy( 'noindex,nofollow' );
909 $text = "<div class='noarticletext'>\n$text\n</div>";
910 if( !$this->hasViewableContent() ) {
911 // If there's no backing content, send a 404 Not Found
912 // for better machine handling of broken links.
918 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
921 # Another whitelist check in case oldid is altering the title
922 if( !$this->mTitle
->userCanRead() ) {
923 $wgOut->loginToUse();
926 wfProfileOut( __METHOD__
);
930 # For ?curid=x urls, disallow indexing
931 if( $wgRequest->getInt('curid') )
932 $wgOut->setRobotPolicy( 'noindex,follow' );
934 # We're looking at an old revision
935 if( !empty( $oldid ) ) {
936 $wgOut->setRobotPolicy( 'noindex,nofollow' );
937 if( is_null( $this->mRevision
) ) {
938 // FIXME: This would be a nice place to load the 'no such page' text.
940 $this->setOldSubtitle( $oldid );
941 # Allow admins to see deleted content if explicitly requested
942 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
943 // If the user is not allowed to see it...
944 if( !$this->mRevision
->userCan(Revision
::DELETED_TEXT
) ) {
945 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
946 'rev-deleted-text-permission' );
947 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
948 wfProfileOut( __METHOD__
);
950 // If the user needs to confirm that they want to see it...
951 } else if( !$unhide ) {
952 # Give explanation and add a link to view the revision...
953 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}".
954 '&unhide=1&token='.urlencode( $wgUser->editToken($oldid) ) );
955 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
956 array('rev-deleted-text-unhide',$link) );
957 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
958 wfProfileOut( __METHOD__
);
960 // We are allowed to see...
962 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
963 'rev-deleted-text-view' );
966 // Is this the current revision and otherwise cacheable? Try the parser cache...
967 if( $oldid === $this->getLatest() && $this->useParserCache( false )
968 && $wgOut->tryParserCache( $this ) )
975 // Ensure that UI elements requiring revision ID have
976 // the correct version information.
977 $wgOut->setRevisionId( $this->getRevIdFetched() );
981 // Pages containing custom CSS or JavaScript get special treatment
982 } else if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
983 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
984 // Give hooks a chance to customise the output
985 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
986 // Wrap the whole lot in a <pre> and don't parse
988 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
989 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
990 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
991 $wgOut->addHTML( "\n</pre>\n" );
993 } else if( $rt = Title
::newFromRedirectArray( $text ) ) { # get an array of redirect targets
994 # Don't append the subtitle if this was an old revision
995 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
996 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
997 $wgOut->addParserOutputNoText( $parseout );
998 } else if( $pcache ) {
999 # Display content and save to parser cache
1000 $this->outputWikiText( $text );
1002 # Display content, don't attempt to save to parser cache
1003 # Don't show section-edit links on old revisions... this way lies madness.
1004 if( !$this->isCurrent() ) {
1005 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
1007 # Display content and don't save to parser cache
1008 # With timing hack -- TS 2006-07-26
1010 $this->outputWikiText( $text, false );
1015 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
1016 $this->mTitle
->getPrefixedDBkey()));
1019 if( !$this->isCurrent() ) {
1020 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
1024 /* title may have been set from the cache */
1025 $t = $wgOut->getPageTitle();
1027 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1029 # For the main page, overwrite the <title> element with the con-
1030 # tents of 'pagetitle-view-mainpage' instead of the default (if
1031 # that's not empty).
1032 if( $this->mTitle
->equals( Title
::newMainPage() ) &&
1033 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
1034 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
1038 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1039 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1040 $wgOut->addWikiMsg('anontalkpagetext');
1043 # If we have been passed an &rcid= parameter, we want to give the user a
1044 # chance to mark this new article as patrolled.
1045 if( !empty($rcid) && $this->mTitle
->exists() && $this->mTitle
->quickUserCan('patrol') ) {
1047 "<div class='patrollink'>" .
1048 wfMsgHtml( 'markaspatrolledlink',
1049 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
1050 "action=markpatrolled&rcid=$rcid" )
1057 if( $wgUseTrackbacks ) {
1058 $this->addTrackbacks();
1061 $this->viewUpdates();
1062 wfProfileOut( __METHOD__
);
1065 protected function showLogs() {
1066 global $wgUser, $wgOut;
1067 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1068 $pager = new LogPager( $loglist, array('move', 'delete'), false, $this->mTitle
->getPrefixedText() );
1069 if( $pager->getNumRows() > 0 ) {
1070 $pager->mLimit
= 10;
1071 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1072 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1074 $loglist->beginLogEventsList() .
1076 $loglist->endLogEventsList()
1078 if( $pager->getNumRows() > 10 ) {
1079 $wgOut->addHTML( $wgUser->getSkin()->link(
1080 SpecialPage
::getTitleFor( 'Log' ),
1081 wfMsgHtml( 'log-fulllog' ),
1083 array( 'page' => $this->mTitle
->getPrefixedText() )
1086 $wgOut->addHTML( '</div>' );
1091 * Should the parser cache be used?
1093 protected function useParserCache( $oldid ) {
1094 global $wgUser, $wgEnableParserCache;
1096 return $wgEnableParserCache
1097 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1100 && !$this->mTitle
->isCssOrJsPage()
1101 && !$this->mTitle
->isCssJsSubpage();
1106 * @param $target Title object or Array of destination(s) to redirect
1107 * @param $appendSubtitle Boolean [optional]
1108 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1110 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1111 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1113 if( !is_array( $target ) ) {
1114 $target = array( $target );
1116 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1117 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1118 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1119 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of entities?
1121 if( $appendSubtitle ) {
1122 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1124 $sk = $wgUser->getSkin();
1125 // the loop prepends the arrow image before the link, so the first case needs to be outside
1126 $title = array_shift( $target );
1128 $link = $sk->makeKnownLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
1130 $link = $sk->makeLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
1132 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1133 foreach( $target as $rt ) {
1135 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1136 . $sk->makeKnownLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
1138 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1139 . $sk->makeLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
1142 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1143 '<span class="redirectText">'.$link.'</span>';
1147 public function addTrackbacks() {
1148 global $wgOut, $wgUser;
1149 $dbr = wfGetDB( DB_SLAVE
);
1150 $tbs = $dbr->select( 'trackbacks',
1151 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1152 array('tb_page' => $this->getID() )
1154 if( !$dbr->numRows($tbs) ) return;
1157 while( $o = $dbr->fetchObject($tbs) ) {
1159 if( $wgUser->isAllowed( 'trackback' ) ) {
1160 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid=" .
1161 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1162 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1165 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1172 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1173 $this->mTitle
->invalidateCache();
1176 public function deletetrackback() {
1177 global $wgUser, $wgRequest, $wgOut;
1178 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1179 $wgOut->addWikiMsg( 'sessionfailure' );
1183 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1184 if( count($permission_errors) ) {
1185 $wgOut->showPermissionsErrorPage( $permission_errors );
1189 $db = wfGetDB( DB_MASTER
);
1190 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1192 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1193 $this->mTitle
->invalidateCache();
1196 public function render() {
1198 $wgOut->setArticleBodyOnly(true);
1203 * Handle action=purge
1205 public function purge() {
1206 global $wgUser, $wgRequest, $wgOut;
1207 if( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1208 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1213 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1214 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1215 $form = "<form method=\"post\" action=\"$action\">\n" .
1216 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1218 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1219 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1220 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1221 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1222 $wgOut->addHTML( $top . $form . $bottom );
1227 * Perform the actions of a page purging
1229 public function doPurge() {
1231 // Invalidate the cache
1232 $this->mTitle
->invalidateCache();
1235 // Commit the transaction before the purge is sent
1236 $dbw = wfGetDB( DB_MASTER
);
1237 $dbw->immediateCommit();
1240 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1241 $update->doUpdate();
1243 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1244 global $wgMessageCache;
1245 if( $this->getID() == 0 ) {
1248 $text = $this->getRawText();
1250 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1255 * Insert a new empty page record for this article.
1256 * This *must* be followed up by creating a revision
1257 * and running $this->updateToLatest( $rev_id );
1258 * or else the record will be left in a funky state.
1259 * Best if all done inside a transaction.
1261 * @param $dbw Database
1262 * @return int The newly created page_id key, or false if the title already existed
1265 public function insertOn( $dbw ) {
1266 wfProfileIn( __METHOD__
);
1268 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1269 $dbw->insert( 'page', array(
1270 'page_id' => $page_id,
1271 'page_namespace' => $this->mTitle
->getNamespace(),
1272 'page_title' => $this->mTitle
->getDBkey(),
1273 'page_counter' => 0,
1274 'page_restrictions' => '',
1275 'page_is_redirect' => 0, # Will set this shortly...
1277 'page_random' => wfRandom(),
1278 'page_touched' => $dbw->timestamp(),
1279 'page_latest' => 0, # Fill this in shortly...
1280 'page_len' => 0, # Fill this in shortly...
1281 ), __METHOD__
, 'IGNORE' );
1283 $affected = $dbw->affectedRows();
1285 $newid = $dbw->insertId();
1286 $this->mTitle
->resetArticleId( $newid );
1288 wfProfileOut( __METHOD__
);
1289 return $affected ?
$newid : false;
1293 * Update the page record to point to a newly saved revision.
1295 * @param $dbw Database object
1296 * @param $revision Revision: For ID number, and text used to set
1297 length and redirect status fields
1298 * @param $lastRevision Integer: if given, will not overwrite the page field
1299 * when different from the currently set value.
1300 * Giving 0 indicates the new page flag should be set
1302 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1303 * removing rows in redirect table.
1304 * @return bool true on success, false on failure
1307 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1308 wfProfileIn( __METHOD__
);
1310 $text = $revision->getText();
1311 $rt = Title
::newFromRedirect( $text );
1313 $conditions = array( 'page_id' => $this->getId() );
1314 if( !is_null( $lastRevision ) ) {
1315 # An extra check against threads stepping on each other
1316 $conditions['page_latest'] = $lastRevision;
1319 $dbw->update( 'page',
1321 'page_latest' => $revision->getId(),
1322 'page_touched' => $dbw->timestamp(),
1323 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1324 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1325 'page_len' => strlen( $text ),
1330 $result = $dbw->affectedRows() != 0;
1332 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1335 wfProfileOut( __METHOD__
);
1340 * Add row to the redirect table if this is a redirect, remove otherwise.
1342 * @param $dbw Database
1343 * @param $redirectTitle a title object pointing to the redirect target,
1344 * or NULL if this is not a redirect
1345 * @param $lastRevIsRedirect If given, will optimize adding and
1346 * removing rows in redirect table.
1347 * @return bool true on success, false on failure
1350 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1351 // Always update redirects (target link might have changed)
1352 // Update/Insert if we don't know if the last revision was a redirect or not
1353 // Delete if changing from redirect to non-redirect
1354 $isRedirect = !is_null($redirectTitle);
1355 if($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1356 wfProfileIn( __METHOD__
);
1358 // This title is a redirect, Add/Update row in the redirect table
1359 $set = array( /* SET */
1360 'rd_namespace' => $redirectTitle->getNamespace(),
1361 'rd_title' => $redirectTitle->getDBkey(),
1362 'rd_from' => $this->getId(),
1364 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1366 // This is not a redirect, remove row from redirect table
1367 $where = array( 'rd_from' => $this->getId() );
1368 $dbw->delete( 'redirect', $where, __METHOD__
);
1370 if( $this->getTitle()->getNamespace() == NS_FILE
) {
1371 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1373 wfProfileOut( __METHOD__
);
1374 return ( $dbw->affectedRows() != 0 );
1380 * If the given revision is newer than the currently set page_latest,
1381 * update the page record. Otherwise, do nothing.
1383 * @param $dbw Database object
1384 * @param $revision Revision object
1386 public function updateIfNewerOn( &$dbw, $revision ) {
1387 wfProfileIn( __METHOD__
);
1388 $row = $dbw->selectRow(
1389 array( 'revision', 'page' ),
1390 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1392 'page_id' => $this->getId(),
1393 'page_latest=rev_id' ),
1396 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1397 wfProfileOut( __METHOD__
);
1400 $prev = $row->rev_id
;
1401 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1403 # No or missing previous revision; mark the page as new
1405 $lastRevIsRedirect = null;
1407 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1408 wfProfileOut( __METHOD__
);
1413 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1414 * @return string Complete article text, or null if error
1416 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1417 wfProfileIn( __METHOD__
);
1418 if( strval( $section ) == '' ) {
1419 // Whole-page edit; let the whole text through
1421 if( is_null($edittime) ) {
1422 $rev = Revision
::newFromTitle( $this->mTitle
);
1424 $dbw = wfGetDB( DB_MASTER
);
1425 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1428 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1429 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1432 $oldtext = $rev->getText();
1434 if( $section == 'new' ) {
1435 # Inserting a new section
1436 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1437 $text = strlen( trim( $oldtext ) ) > 0
1438 ?
"{$oldtext}\n\n{$subject}{$text}"
1439 : "{$subject}{$text}";
1441 # Replacing an existing section; roll out the big guns
1443 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1446 wfProfileOut( __METHOD__
);
1451 * @deprecated use Article::doEdit()
1453 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1454 wfDeprecated( __METHOD__
);
1455 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1456 ( $isminor ? EDIT_MINOR
: 0 ) |
1457 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1458 ( $bot ? EDIT_FORCE_BOT
: 0 );
1460 # If this is a comment, add the summary as headline
1461 if( $comment && $summary != "" ) {
1462 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1465 $this->doEdit( $text, $summary, $flags );
1467 $dbw = wfGetDB( DB_MASTER
);
1469 if(!$this->mTitle
->userIsWatching()) {
1475 if( $this->mTitle
->userIsWatching() ) {
1481 $this->doRedirect( $this->isRedirect( $text ) );
1485 * @deprecated use Article::doEdit()
1487 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1488 wfDeprecated( __METHOD__
);
1489 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1490 ( $minor ? EDIT_MINOR
: 0 ) |
1491 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1493 $status = $this->doEdit( $text, $summary, $flags );
1494 if( !$status->isOK() ) {
1498 $dbw = wfGetDB( DB_MASTER
);
1500 if(!$this->mTitle
->userIsWatching()) {
1506 if( $this->mTitle
->userIsWatching() ) {
1513 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1514 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1516 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1523 * Change an existing article or create a new article. Updates RC and all necessary caches,
1524 * optionally via the deferred update array.
1526 * $wgUser must be set before calling this function.
1528 * @param $text String: new text
1529 * @param $summary String: edit summary
1530 * @param $flags Integer bitfield:
1532 * Article is known or assumed to be non-existent, create a new one
1534 * Article is known or assumed to be pre-existing, update it
1536 * Mark this edit minor, if the user is allowed to do so
1538 * Do not log the change in recentchanges
1540 * Mark the edit a "bot" edit regardless of user rights
1541 * EDIT_DEFER_UPDATES
1542 * Defer some of the updates until the end of index.php
1544 * Fill in blank summaries with generated text where possible
1546 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1547 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1548 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1549 * edit-already-exists error will be returned. These two conditions are also possible with
1550 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1552 * @param $baseRevId the revision ID this edit was based off, if any
1553 * @param $user Optional user object, $wgUser will be used if not passed
1555 * @return Status object. Possible errors:
1556 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1557 * edit-gone-missing: In update mode, but the article didn't exist
1558 * edit-conflict: In update mode, the article changed unexpectedly
1559 * edit-no-change: Warning that the text was the same as before
1560 * edit-already-exists: In creation mode, but the article already exists
1562 * Extensions may define additional errors.
1564 * $return->value will contain an associative array with members as follows:
1565 * new: Boolean indicating if the function attempted to create a new article
1566 * revision: The revision object for the inserted revision, or null
1568 * Compatibility note: this function previously returned a boolean value indicating success/failure
1570 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1571 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1573 # Low-level sanity check
1574 if( $this->mTitle
->getText() == '' ) {
1575 throw new MWException( 'Something is trying to edit an article with an empty title' );
1578 wfProfileIn( __METHOD__
);
1580 $user = is_null($user) ?
$wgUser : $user;
1581 $status = Status
::newGood( array() );
1583 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1584 $this->loadPageData();
1586 if( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1587 $aid = $this->mTitle
->getArticleID();
1589 $flags |
= EDIT_UPDATE
;
1595 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1596 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1598 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1599 wfProfileOut( __METHOD__
);
1600 if( $status->isOK() ) {
1601 $status->fatal( 'edit-hook-aborted');
1606 # Silently ignore EDIT_MINOR if not allowed
1607 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed('minoredit');
1608 $bot = $flags & EDIT_FORCE_BOT
;
1610 $oldtext = $this->getRawText(); // current revision
1611 $oldsize = strlen( $oldtext );
1613 # Provide autosummaries if one is not provided and autosummaries are enabled.
1614 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1615 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1618 $editInfo = $this->prepareTextForEdit( $text );
1619 $text = $editInfo->pst
;
1620 $newsize = strlen( $text );
1622 $dbw = wfGetDB( DB_MASTER
);
1623 $now = wfTimestampNow();
1625 if( $flags & EDIT_UPDATE
) {
1626 # Update article, but only if changed.
1627 $status->value
['new'] = false;
1628 # Make sure the revision is either completely inserted or not inserted at all
1629 if( !$wgDBtransactions ) {
1630 $userAbort = ignore_user_abort( true );
1635 $changed = ( strcmp( $text, $oldtext ) != 0 );
1638 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1639 - (int)$this->isCountable( $oldtext );
1640 $this->mTotalAdjustment
= 0;
1642 if( !$this->mLatest
) {
1643 # Article gone missing
1644 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1645 $status->fatal( 'edit-gone-missing' );
1646 wfProfileOut( __METHOD__
);
1650 $revision = new Revision( array(
1651 'page' => $this->getId(),
1652 'comment' => $summary,
1653 'minor_edit' => $isminor,
1655 'parent_id' => $this->mLatest
,
1656 'user' => $user->getId(),
1657 'user_text' => $user->getName(),
1661 $revisionId = $revision->insertOn( $dbw );
1665 # Note that we use $this->mLatest instead of fetching a value from the master DB
1666 # during the course of this function. This makes sure that EditPage can detect
1667 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1668 # before this function is called. A previous function used a separate query, this
1669 # creates a window where concurrent edits can cause an ignored edit conflict.
1670 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1673 /* Belated edit conflict! Run away!! */
1674 $status->fatal( 'edit-conflict' );
1675 # Delete the invalid revision if the DB is not transactional
1676 if( !$wgDBtransactions ) {
1677 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1682 global $wgUseRCPatrol;
1683 # Update recentchanges
1684 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1685 # Mark as patrolled if the user can do so
1686 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan('autopatrol');
1687 # Add RC row to the DB
1688 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1689 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1690 $revisionId, $patrolled
1692 # Log auto-patrolled edits
1694 PatrolLog
::record( $rc, true );
1697 # Notify extensions of a new edit
1698 wfRunHooks( 'NewRevisionFromEditComplete', array(&$this, $revision, $baseRevId, $user) );
1699 $user->incEditCount();
1703 $status->warning( 'edit-no-change' );
1705 // Keep the same revision ID, but do some updates on it
1706 $revisionId = $this->getRevIdFetched();
1707 // Update page_touched, this is usually implicit in the page update
1708 // Other cache updates are done in onArticleEdit()
1709 $this->mTitle
->invalidateCache();
1712 if( !$wgDBtransactions ) {
1713 ignore_user_abort( $userAbort );
1715 // Now that ignore_user_abort is restored, we can respond to fatal errors
1716 if( !$status->isOK() ) {
1717 wfProfileOut( __METHOD__
);
1721 # Invalidate cache of this article and all pages using this article
1722 # as a template. Partly deferred.
1723 Article
::onArticleEdit( $this->mTitle
);
1724 # Update links tables, site stats, etc.
1725 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1727 # Create new article
1728 $status->value
['new'] = true;
1730 # Set statistics members
1731 # We work out if it's countable after PST to avoid counter drift
1732 # when articles are created with {{subst:}}
1733 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1734 $this->mTotalAdjustment
= 1;
1738 # Add the page record; stake our claim on this title!
1739 # This will return false if the article already exists
1740 $newid = $this->insertOn( $dbw );
1742 if( $newid === false ) {
1744 $status->fatal( 'edit-already-exists' );
1745 wfProfileOut( __METHOD__
);
1749 # Save the revision text...
1750 $revision = new Revision( array(
1752 'comment' => $summary,
1753 'minor_edit' => $isminor,
1755 'user' => $user->getId(),
1756 'user_text' => $user->getName(),
1758 $revisionId = $revision->insertOn( $dbw );
1760 $this->mTitle
->resetArticleID( $newid );
1762 # Update the page record with revision data
1763 $this->updateRevisionOn( $dbw, $revision, 0 );
1765 # Update recentchanges
1766 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1767 global $wgUseRCPatrol, $wgUseNPPatrol;
1768 # Mark as patrolled if the user can do so
1769 $patrolled = ($wgUseRCPatrol ||
$wgUseNPPatrol) && $this->mTitle
->userCan('autopatrol');
1770 # Add RC row to the DB
1771 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1772 '', strlen($text), $revisionId, $patrolled );
1773 # Log auto-patrolled edits
1775 PatrolLog
::record( $rc, true );
1778 # Notify extensions of a new page edit
1779 wfRunHooks( 'NewRevisionFromEditComplete', array(&$this, $revision, false, $user) );
1780 $user->incEditCount();
1783 # Update links, etc.
1784 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1787 Article
::onArticleCreate( $this->mTitle
);
1789 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1790 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1793 # Do updates right now unless deferral was requested
1794 if( !( $flags & EDIT_DEFER_UPDATES
) ) {
1798 // Return the new revision (or null) to the caller
1799 $status->value
['revision'] = $revision;
1801 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1802 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1804 wfProfileOut( __METHOD__
);
1809 * @deprecated wrapper for doRedirect
1811 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1812 wfDeprecated( __METHOD__
);
1813 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1817 * Output a redirect back to the article.
1818 * This is typically used after an edit.
1820 * @param $noRedir Boolean: add redirect=no
1821 * @param $sectionAnchor String: section to redirect to, including "#"
1822 * @param $extraQuery String: extra query params
1824 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1827 $query = 'redirect=no';
1829 $query .= "&$query";
1831 $query = $extraQuery;
1833 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1837 * Mark this particular edit/page as patrolled
1839 public function markpatrolled() {
1840 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1841 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1843 # If we haven't been given an rc_id value, we can't do anything
1844 $rcid = (int) $wgRequest->getVal('rcid');
1845 $rc = RecentChange
::newFromId($rcid);
1846 if( is_null($rc) ) {
1847 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1851 #It would be nice to see where the user had actually come from, but for now just guess
1852 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1853 $return = SpecialPage
::getTitleFor( $returnto );
1855 $dbw = wfGetDB( DB_MASTER
);
1856 $errors = $rc->doMarkPatrolled();
1858 if( in_array(array('rcpatroldisabled'), $errors) ) {
1859 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1863 if( in_array(array('hookaborted'), $errors) ) {
1864 // The hook itself has handled any output
1868 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1869 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1870 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1871 $wgOut->returnToMain( false, $return );
1875 if( !empty($errors) ) {
1876 $wgOut->showPermissionsErrorPage( $errors );
1881 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1882 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1883 $wgOut->returnToMain( false, $return );
1887 * User-interface handler for the "watch" action
1890 public function watch() {
1891 global $wgUser, $wgOut;
1892 if( $wgUser->isAnon() ) {
1893 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1896 if( wfReadOnly() ) {
1897 $wgOut->readOnlyPage();
1900 if( $this->doWatch() ) {
1901 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1902 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1903 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1905 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1909 * Add this page to $wgUser's watchlist
1910 * @return bool true on successful watch operation
1912 public function doWatch() {
1914 if( $wgUser->isAnon() ) {
1917 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1918 $wgUser->addWatch( $this->mTitle
);
1919 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1925 * User interface handler for the "unwatch" action.
1927 public function unwatch() {
1928 global $wgUser, $wgOut;
1929 if( $wgUser->isAnon() ) {
1930 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1933 if( wfReadOnly() ) {
1934 $wgOut->readOnlyPage();
1937 if( $this->doUnwatch() ) {
1938 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1939 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1940 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1942 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1946 * Stop watching a page
1947 * @return bool true on successful unwatch
1949 public function doUnwatch() {
1951 if( $wgUser->isAnon() ) {
1954 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1955 $wgUser->removeWatch( $this->mTitle
);
1956 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1962 * action=protect handler
1964 public function protect() {
1965 global $wgUser, $wgOut;
1968 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser );
1970 if( count( $permission_errors ) > 0 ) {
1971 $wgOut->showPermissionsErrorPage( $permission_errors );
1975 $form = new ProtectionForm( $this );
1980 * action=unprotect handler (alias)
1982 public function unprotect() {
1987 * Update the article's restriction field, and leave a log entry.
1989 * @param $limit Array: set of restriction keys
1990 * @param $reason String
1991 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1992 * @param $expiry Array: per restriction type expiration
1993 * @return bool true on success
1995 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1996 global $wgUser, $wgRestrictionTypes, $wgContLang;
1998 $id = $this->mTitle
->getArticleID();
2000 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2004 if ( wfReadOnly() ) {
2005 wfDebug( "updateRestrictions failed: read-only\n" );
2009 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2010 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2018 // Take this opportunity to purge out expired restrictions
2019 Title
::purgeExpiredRestrictions();
2021 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2022 # we expect a single selection, but the schema allows otherwise.
2024 $updated = Article
::flattenRestrictions( $limit );
2026 foreach( $wgRestrictionTypes as $action ) {
2027 if( isset( $expiry[$action] ) ) {
2028 # Get current restrictions on $action
2029 $aLimits = $this->mTitle
->getRestrictions( $action );
2030 $current[$action] = implode( '', $aLimits );
2031 # Are any actual restrictions being dealt with here?
2032 $aRChanged = count($aLimits) ||
!empty($limit[$action]);
2033 # If something changed, we need to log it. Checking $aRChanged
2034 # assures that "unprotecting" a page that is not protected does
2035 # not log just because the expiry was "changed".
2036 if( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2042 $current = Article
::flattenRestrictions( $current );
2044 $changed = ($changed ||
$current != $updated );
2045 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
2046 $protect = ( $updated != '' );
2048 # If nothing's changed, do nothing
2050 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2052 $dbw = wfGetDB( DB_MASTER
);
2054 # Prepare a null revision to be added to the history
2055 $modified = $current != '' && $protect;
2057 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2059 $comment_type = 'unprotectedarticle';
2061 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2063 # Only restrictions with the 'protect' right can cascade...
2064 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2065 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2066 # The schema allows multiple restrictions
2067 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2069 $cascade_description = '';
2071 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2075 $comment .= ": $reason";
2077 $editComment = $comment;
2078 $encodedExpiry = array();
2079 $protect_description = '';
2080 foreach( $limit as $action => $restrictions ) {
2081 if ( !isset($expiry[$action]) )
2082 $expiry[$action] = 'infinite';
2084 $encodedExpiry[$action] = Block
::encodeExpiry($expiry[$action], $dbw );
2085 if( $restrictions != '' ) {
2086 $protect_description .= "[$action=$restrictions] (";
2087 if( $encodedExpiry[$action] != 'infinity' ) {
2088 $protect_description .= wfMsgForContent( 'protect-expiring',
2089 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2090 $wgContLang->date( $expiry[$action], false, false ) ,
2091 $wgContLang->time( $expiry[$action], false, false ) );
2093 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2095 $protect_description .= ') ';
2098 $protect_description = trim($protect_description);
2100 if( $protect_description && $protect )
2101 $editComment .= " ($protect_description)";
2103 $editComment .= "$cascade_description";
2104 # Update restrictions table
2105 foreach( $limit as $action => $restrictions ) {
2106 if($restrictions != '' ) {
2107 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2108 array( 'pr_page' => $id,
2109 'pr_type' => $action,
2110 'pr_level' => $restrictions,
2111 'pr_cascade' => ($cascade && $action == 'edit') ?
1 : 0,
2112 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
2114 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2115 'pr_type' => $action ), __METHOD__
);
2119 # Insert a null revision
2120 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2121 $nullRevId = $nullRevision->insertOn( $dbw );
2123 $latest = $this->getLatest();
2124 # Update page record
2125 $dbw->update( 'page',
2127 'page_touched' => $dbw->timestamp(),
2128 'page_restrictions' => '',
2129 'page_latest' => $nullRevId
2130 ), array( /* WHERE */
2132 ), 'Article::protect'
2135 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2136 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2138 # Update the protection log
2139 $log = new LogPage( 'protect' );
2141 $params = array($protect_description,$cascade ?
'cascade' : '');
2142 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason), $params );
2144 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2148 } # End "changed" check
2154 * Take an array of page restrictions and flatten it to a string
2155 * suitable for insertion into the page_restrictions field.
2156 * @param $limit Array
2159 protected static function flattenRestrictions( $limit ) {
2160 if( !is_array( $limit ) ) {
2161 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2165 foreach( $limit as $action => $restrictions ) {
2166 if( $restrictions != '' ) {
2167 $bits[] = "$action=$restrictions";
2170 return implode( ':', $bits );
2174 * Auto-generates a deletion reason
2175 * @param &$hasHistory Boolean: whether the page has a history
2177 public function generateReason( &$hasHistory ) {
2179 $dbw = wfGetDB( DB_MASTER
);
2180 // Get the last revision
2181 $rev = Revision
::newFromTitle( $this->mTitle
);
2182 if( is_null( $rev ) )
2185 // Get the article's contents
2186 $contents = $rev->getText();
2188 // If the page is blank, use the text from the previous revision,
2189 // which can only be blank if there's a move/import/protect dummy revision involved
2190 if( $contents == '' ) {
2191 $prev = $rev->getPrevious();
2193 $contents = $prev->getText();
2198 // Find out if there was only one contributor
2199 // Only scan the last 20 revisions
2200 $res = $dbw->select( 'revision', 'rev_user_text',
2201 array( 'rev_page' => $this->getID(), 'rev_deleted & '.Revision
::DELETED_USER
.'=0' ),
2203 array( 'LIMIT' => 20 )
2205 if( $res === false )
2206 // This page has no revisions, which is very weird
2209 $hasHistory = ( $res->numRows() > 1 );
2210 $row = $dbw->fetchObject( $res );
2211 $onlyAuthor = $row->rev_user_text
;
2212 // Try to find a second contributor
2213 foreach( $res as $row ) {
2214 if( $row->rev_user_text
!= $onlyAuthor ) {
2215 $onlyAuthor = false;
2219 $dbw->freeResult( $res );
2221 // Generate the summary with a '$1' placeholder
2223 // The current revision is blank and the one before is also
2224 // blank. It's just not our lucky day
2225 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2228 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2230 $reason = wfMsgForContent( 'excontent', '$1' );
2233 if( $reason == '-' ) {
2234 // Allow these UI messages to be blanked out cleanly
2238 // Replace newlines with spaces to prevent uglyness
2239 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2240 // Calculate the maximum amount of chars to get
2241 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2242 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2243 $contents = $wgContLang->truncate( $contents, $maxLength );
2244 // Remove possible unfinished links
2245 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2246 // Now replace the '$1' placeholder
2247 $reason = str_replace( '$1', $contents, $reason );
2253 * UI entry point for page deletion
2255 public function delete() {
2256 global $wgUser, $wgOut, $wgRequest;
2258 $confirm = $wgRequest->wasPosted() &&
2259 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2261 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2262 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2264 $reason = $this->DeleteReasonList
;
2266 if( $reason != 'other' && $this->DeleteReason
!= '' ) {
2267 // Entry from drop down menu + additional comment
2268 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2269 } elseif( $reason == 'other' ) {
2270 $reason = $this->DeleteReason
;
2272 # Flag to hide all contents of the archived revisions
2273 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2275 # This code desperately needs to be totally rewritten
2277 # Read-only check...
2278 if( wfReadOnly() ) {
2279 $wgOut->readOnlyPage();
2284 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2286 if( count( $permission_errors ) > 0 ) {
2287 $wgOut->showPermissionsErrorPage( $permission_errors );
2291 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2293 # Better double-check that it hasn't been deleted yet!
2294 $dbw = wfGetDB( DB_MASTER
);
2295 $conds = $this->mTitle
->pageCond();
2296 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2297 if( $latest === false ) {
2298 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2299 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2300 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2304 # Hack for big sites
2305 $bigHistory = $this->isBigDeletion();
2306 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2307 global $wgLang, $wgDeleteRevisionsLimit;
2308 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2309 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2314 $this->doDelete( $reason, $suppress );
2315 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2317 } elseif( $this->mTitle
->userIsWatching() ) {
2323 // Generate deletion reason
2324 $hasHistory = false;
2325 if( !$reason ) $reason = $this->generateReason($hasHistory);
2327 // If the page has a history, insert a warning
2328 if( $hasHistory && !$confirm ) {
2329 $skin = $wgUser->getSkin();
2330 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2332 global $wgLang, $wgDeleteRevisionsLimit;
2333 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2334 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2338 return $this->confirmDelete( $reason );
2342 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2344 public function isBigDeletion() {
2345 global $wgDeleteRevisionsLimit;
2346 if( $wgDeleteRevisionsLimit ) {
2347 $revCount = $this->estimateRevisionCount();
2348 return $revCount > $wgDeleteRevisionsLimit;
2354 * @return int approximate revision count
2356 public function estimateRevisionCount() {
2357 $dbr = wfGetDB( DB_SLAVE
);
2358 // For an exact count...
2359 //return $dbr->selectField( 'revision', 'COUNT(*)',
2360 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2361 return $dbr->estimateRowCount( 'revision', '*',
2362 array( 'rev_page' => $this->getId() ), __METHOD__
);
2366 * Get the last N authors
2367 * @param $num Integer: number of revisions to get
2368 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2369 * @return array Array of authors, duplicates not removed
2371 public function getLastNAuthors( $num, $revLatest = 0 ) {
2372 wfProfileIn( __METHOD__
);
2373 // First try the slave
2374 // If that doesn't have the latest revision, try the master
2376 $db = wfGetDB( DB_SLAVE
);
2378 $res = $db->select( array( 'page', 'revision' ),
2379 array( 'rev_id', 'rev_user_text' ),
2381 'page_namespace' => $this->mTitle
->getNamespace(),
2382 'page_title' => $this->mTitle
->getDBkey(),
2383 'rev_page = page_id'
2384 ), __METHOD__
, $this->getSelectOptions( array(
2385 'ORDER BY' => 'rev_timestamp DESC',
2390 wfProfileOut( __METHOD__
);
2393 $row = $db->fetchObject( $res );
2394 if( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2395 $db = wfGetDB( DB_MASTER
);
2400 } while ( $continue );
2402 $authors = array( $row->rev_user_text
);
2403 while ( $row = $db->fetchObject( $res ) ) {
2404 $authors[] = $row->rev_user_text
;
2406 wfProfileOut( __METHOD__
);
2411 * Output deletion confirmation dialog
2412 * @param $reason String: prefilled reason
2414 public function confirmDelete( $reason ) {
2415 global $wgOut, $wgUser;
2417 wfDebug( "Article::confirmDelete\n" );
2419 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2420 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2421 $wgOut->addWikiMsg( 'confirmdeletetext' );
2423 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2424 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2426 <td class='mw-input'><strong>" .
2427 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2428 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2434 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2436 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2437 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2438 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2439 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2440 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2441 "<tr id=\"wpDeleteReasonListRow\">
2442 <td class='mw-label'>" .
2443 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2445 <td class='mw-input'>" .
2446 Xml
::listDropDown( 'wpDeleteReasonList',
2447 wfMsgForContent( 'deletereason-dropdown' ),
2448 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2451 <tr id=\"wpDeleteReasonRow\">
2452 <td class='mw-label'>" .
2453 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2455 <td class='mw-input'>" .
2456 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2457 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2462 <td class='mw-input'>" .
2463 Xml
::checkLabel( wfMsg( 'watchthis' ),
2464 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2470 <td class='mw-submit'>" .
2471 Xml
::submitButton( wfMsg( 'deletepage' ),
2472 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2475 Xml
::closeElement( 'table' ) .
2476 Xml
::closeElement( 'fieldset' ) .
2477 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2478 Xml
::closeElement( 'form' );
2480 if( $wgUser->isAllowed( 'editinterface' ) ) {
2481 $skin = $wgUser->getSkin();
2482 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2483 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2486 $wgOut->addHTML( $form );
2487 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2491 * Perform a deletion and output success or failure messages
2493 public function doDelete( $reason, $suppress = false ) {
2494 global $wgOut, $wgUser;
2495 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2498 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2499 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2500 $deleted = $this->mTitle
->getPrefixedText();
2502 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2503 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2505 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2507 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2508 $wgOut->returnToMain( false );
2509 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2511 if( $error == '' ) {
2512 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2513 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2514 LogEventsList
::showLogExtract( $wgOut, 'delete', $this->mTitle
->getPrefixedText() );
2516 $wgOut->showFatalError( $error );
2523 * Back-end article deletion
2524 * Deletes the article with database consistency, writes logs, purges caches
2527 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2528 global $wgUseSquid, $wgDeferredUpdateList;
2529 global $wgUseTrackbacks;
2531 wfDebug( __METHOD__
."\n" );
2533 $dbw = wfGetDB( DB_MASTER
);
2534 $ns = $this->mTitle
->getNamespace();
2535 $t = $this->mTitle
->getDBkey();
2536 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2538 if( $t == '' ||
$id == 0 ) {
2542 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2543 array_push( $wgDeferredUpdateList, $u );
2545 // Bitfields to further suppress the content
2548 // This should be 15...
2549 $bitfield |
= Revision
::DELETED_TEXT
;
2550 $bitfield |
= Revision
::DELETED_COMMENT
;
2551 $bitfield |
= Revision
::DELETED_USER
;
2552 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2554 $bitfield = 'rev_deleted';
2558 // For now, shunt the revision data into the archive table.
2559 // Text is *not* removed from the text table; bulk storage
2560 // is left intact to avoid breaking block-compression or
2561 // immutable storage schemes.
2563 // For backwards compatibility, note that some older archive
2564 // table entries will have ar_text and ar_flags fields still.
2566 // In the future, we may keep revisions and mark them with
2567 // the rev_deleted field, which is reserved for this purpose.
2568 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2570 'ar_namespace' => 'page_namespace',
2571 'ar_title' => 'page_title',
2572 'ar_comment' => 'rev_comment',
2573 'ar_user' => 'rev_user',
2574 'ar_user_text' => 'rev_user_text',
2575 'ar_timestamp' => 'rev_timestamp',
2576 'ar_minor_edit' => 'rev_minor_edit',
2577 'ar_rev_id' => 'rev_id',
2578 'ar_text_id' => 'rev_text_id',
2579 'ar_text' => '\'\'', // Be explicit to appease
2580 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2581 'ar_len' => 'rev_len',
2582 'ar_page_id' => 'page_id',
2583 'ar_deleted' => $bitfield
2586 'page_id = rev_page'
2590 # Delete restrictions for it
2591 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2593 # Now that it's safely backed up, delete it
2594 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2595 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2601 # Fix category table counts
2603 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2604 foreach( $res as $row ) {
2605 $cats []= $row->cl_to
;
2607 $this->updateCategoryCounts( array(), $cats );
2609 # If using cascading deletes, we can skip some explicit deletes
2610 if( !$dbw->cascadingDeletes() ) {
2611 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2613 if($wgUseTrackbacks)
2614 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2616 # Delete outgoing links
2617 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2618 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2619 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2620 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2621 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2622 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2623 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2626 # If using cleanup triggers, we can skip some manual deletes
2627 if( !$dbw->cleanupTriggers() ) {
2628 # Clean up recentchanges entries...
2629 $dbw->delete( 'recentchanges',
2630 array( 'rc_type != '.RC_LOG
,
2631 'rc_namespace' => $this->mTitle
->getNamespace(),
2632 'rc_title' => $this->mTitle
->getDBKey() ),
2634 $dbw->delete( 'recentchanges',
2635 array( 'rc_type != '.RC_LOG
, 'rc_cur_id' => $id ),
2640 Article
::onArticleDelete( $this->mTitle
);
2642 # Clear the cached article id so the interface doesn't act like we exist
2643 $this->mTitle
->resetArticleID( 0 );
2645 # Log the deletion, if the page was suppressed, log it at Oversight instead
2646 $logtype = $suppress ?
'suppress' : 'delete';
2647 $log = new LogPage( $logtype );
2649 # Make sure logging got through
2650 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2658 * Roll back the most recent consecutive set of edits to a page
2659 * from the same user; fails if there are no eligible edits to
2660 * roll back to, e.g. user is the sole contributor. This function
2661 * performs permissions checks on $wgUser, then calls commitRollback()
2662 * to do the dirty work
2664 * @param $fromP String: Name of the user whose edits to rollback.
2665 * @param $summary String: Custom summary. Set to default summary if empty.
2666 * @param $token String: Rollback token.
2667 * @param $bot Boolean: If true, mark all reverted edits as bot.
2669 * @param $resultDetails Array: contains result-specific array of additional values
2670 * 'alreadyrolled' : 'current' (rev)
2671 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2673 * @return array of errors, each error formatted as
2674 * array(messagekey, param1, param2, ...).
2675 * On success, the array is empty. This array can also be passed to
2676 * OutputPage::showPermissionsErrorPage().
2678 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2680 $resultDetails = null;
2683 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
2684 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
2685 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2687 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2688 $errors[] = array( 'sessionfailure' );
2690 if( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
2691 $errors[] = array( 'actionthrottledtext' );
2693 # If there were errors, bail out now
2694 if( !empty( $errors ) )
2697 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2701 * Backend implementation of doRollback(), please refer there for parameter
2702 * and return value documentation
2704 * NOTE: This function does NOT check ANY permissions, it just commits the
2705 * rollback to the DB Therefore, you should only call this function direct-
2706 * ly if you want to use custom permissions checks. If you don't, use
2707 * doRollback() instead.
2709 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2710 global $wgUseRCPatrol, $wgUser, $wgLang;
2711 $dbw = wfGetDB( DB_MASTER
);
2713 if( wfReadOnly() ) {
2714 return array( array( 'readonlytext' ) );
2717 # Get the last editor
2718 $current = Revision
::newFromTitle( $this->mTitle
);
2719 if( is_null( $current ) ) {
2720 # Something wrong... no page?
2721 return array(array('notanarticle'));
2724 $from = str_replace( '_', ' ', $fromP );
2725 if( $from != $current->getUserText() ) {
2726 $resultDetails = array( 'current' => $current );
2727 return array(array('alreadyrolled',
2728 htmlspecialchars($this->mTitle
->getPrefixedText()),
2729 htmlspecialchars($fromP),
2730 htmlspecialchars($current->getUserText())
2734 # Get the last edit not by this guy
2735 $user = intval( $current->getUser() );
2736 $user_text = $dbw->addQuotes( $current->getUserText() );
2737 $s = $dbw->selectRow( 'revision',
2738 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2739 array( 'rev_page' => $current->getPage(),
2740 "rev_user != {$user} OR rev_user_text != {$user_text}"
2742 array( 'USE INDEX' => 'page_timestamp',
2743 'ORDER BY' => 'rev_timestamp DESC' )
2745 if( $s === false ) {
2746 # No one else ever edited this page
2747 return array(array('cantrollback'));
2748 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2749 # Only admins can see this text
2750 return array(array('notvisiblerev'));
2754 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2755 # Mark all reverted edits as bot
2758 if( $wgUseRCPatrol ) {
2759 # Mark all reverted edits as patrolled
2760 $set['rc_patrolled'] = 1;
2764 $dbw->update( 'recentchanges', $set,
2766 'rc_cur_id' => $current->getPage(),
2767 'rc_user_text' => $current->getUserText(),
2768 "rc_timestamp > '{$s->rev_timestamp}'",
2773 # Generate the edit summary if necessary
2774 $target = Revision
::newFromId( $s->rev_id
);
2775 if( empty( $summary ) ){
2776 $summary = wfMsgForContent( 'revertpage' );
2779 # Allow the custom summary to use the same args as the default message
2781 $target->getUserText(), $from, $s->rev_id
,
2782 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2783 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2785 $summary = wfMsgReplaceArgs( $summary, $args );
2788 $flags = EDIT_UPDATE
;
2790 if( $wgUser->isAllowed('minoredit') )
2791 $flags |
= EDIT_MINOR
;
2793 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2794 $flags |
= EDIT_FORCE_BOT
;
2795 # Actually store the edit
2796 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2797 if( !empty( $status->value
['revision'] ) ) {
2798 $revId = $status->value
['revision']->getId();
2803 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2805 $resultDetails = array(
2806 'summary' => $summary,
2807 'current' => $current,
2808 'target' => $target,
2815 * User interface for rollback operations
2817 public function rollback() {
2818 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2821 $result = $this->doRollback(
2822 $wgRequest->getVal( 'from' ),
2823 $wgRequest->getText( 'summary' ),
2824 $wgRequest->getVal( 'token' ),
2825 $wgRequest->getBool( 'bot' ),
2829 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2830 $wgOut->rateLimited();
2833 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
2834 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2835 $errArray = $result[0];
2836 $errMsg = array_shift( $errArray );
2837 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2838 if( isset( $details['current'] ) ){
2839 $current = $details['current'];
2840 if( $current->getComment() != '' ) {
2841 $wgOut->addWikiMsgArray( 'editcomment', array(
2842 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2847 # Display permissions errors before read-only message -- there's no
2848 # point in misleading the user into thinking the inability to rollback
2849 # is only temporary.
2850 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2851 # array_diff is completely broken for arrays of arrays, sigh. Re-
2852 # move any 'readonlytext' error manually.
2854 foreach( $result as $error ) {
2855 if( $error != array( 'readonlytext' ) ) {
2859 $wgOut->showPermissionsErrorPage( $out );
2862 if( $result == array( array( 'readonlytext' ) ) ) {
2863 $wgOut->readOnlyPage();
2867 $current = $details['current'];
2868 $target = $details['target'];
2869 $newId = $details['newid'];
2870 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2871 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2872 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2873 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2874 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2875 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2876 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2877 $wgOut->returnToMain( false, $this->mTitle
);
2879 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2880 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
2881 $de->showDiff( '', '' );
2887 * Do standard deferred updates after page view
2889 public function viewUpdates() {
2890 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2891 # Don't update page view counters on views from bot users (bug 14044)
2892 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2893 Article
::incViewCount( $this->getID() );
2894 $u = new SiteStatsUpdate( 1, 0, 0 );
2895 array_push( $wgDeferredUpdateList, $u );
2897 # Update newtalk / watchlist notification status
2898 $wgUser->clearNotification( $this->mTitle
);
2902 * Prepare text which is about to be saved.
2903 * Returns a stdclass with source, pst and output members
2905 public function prepareTextForEdit( $text, $revid=null ) {
2906 if( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2908 return $this->mPreparedEdit
;
2911 $edit = (object)array();
2912 $edit->revid
= $revid;
2913 $edit->newText
= $text;
2914 $edit->pst
= $this->preSaveTransform( $text );
2915 $options = new ParserOptions
;
2916 $options->setTidy( true );
2917 $options->enableLimitReport();
2918 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2919 $edit->oldText
= $this->getContent();
2920 $this->mPreparedEdit
= $edit;
2925 * Do standard deferred updates after page edit.
2926 * Update links tables, site stats, search index and message cache.
2927 * Purges pages that include this page if the text was changed here.
2928 * Every 100th edit, prune the recent changes table.
2931 * @param $text New text of the article
2932 * @param $summary Edit summary
2933 * @param $minoredit Minor edit
2934 * @param $timestamp_of_pagechange Timestamp associated with the page change
2935 * @param $newid rev_id value of the new revision
2936 * @param $changed Whether or not the content actually changed
2938 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2939 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2941 wfProfileIn( __METHOD__
);
2944 # Be careful not to double-PST: $text is usually already PST-ed once
2945 if( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2946 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2947 $editInfo = $this->prepareTextForEdit( $text, $newid );
2949 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2950 $editInfo = $this->mPreparedEdit
;
2953 # Save it to the parser cache
2954 if( $wgEnableParserCache ) {
2955 $popts = new ParserOptions
;
2956 $popts->setTidy( true );
2957 $popts->enableLimitReport();
2958 $parserCache = ParserCache
::singleton();
2959 $parserCache->save( $editInfo->output
, $this, $popts );
2962 # Update the links tables
2963 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2966 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2968 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2969 if( 0 == mt_rand( 0, 99 ) ) {
2970 // Flush old entries from the `recentchanges` table; we do this on
2971 // random requests so as to avoid an increase in writes for no good reason
2973 $dbw = wfGetDB( DB_MASTER
);
2974 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2975 $recentchanges = $dbw->tableName( 'recentchanges' );
2976 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2977 $dbw->query( $sql );
2981 $id = $this->getID();
2982 $title = $this->mTitle
->getPrefixedDBkey();
2983 $shortTitle = $this->mTitle
->getDBkey();
2986 wfProfileOut( __METHOD__
);
2990 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2991 array_push( $wgDeferredUpdateList, $u );
2992 $u = new SearchUpdate( $id, $title, $text );
2993 array_push( $wgDeferredUpdateList, $u );
2995 # If this is another user's talk page, update newtalk
2996 # Don't do this if $changed = false otherwise some idiot can null-edit a
2997 # load of user talk pages and piss people off, nor if it's a minor edit
2998 # by a properly-flagged bot.
2999 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3000 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3001 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3002 $other = User
::newFromName( $shortTitle, false );
3004 wfDebug( __METHOD__
.": invalid username\n" );
3005 } elseif( User
::isIP( $shortTitle ) ) {
3006 // An anonymous user
3007 $other->setNewtalk( true );
3008 } elseif( $other->isLoggedIn() ) {
3009 $other->setNewtalk( true );
3011 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3016 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3017 $wgMessageCache->replace( $shortTitle, $text );
3020 wfProfileOut( __METHOD__
);
3024 * Perform article updates on a special page creation.
3026 * @param $rev Revision object
3028 * @todo This is a shitty interface function. Kill it and replace the
3029 * other shitty functions like editUpdates and such so it's not needed
3032 public function createUpdates( $rev ) {
3033 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3034 $this->mTotalAdjustment
= 1;
3035 $this->editUpdates( $rev->getText(), $rev->getComment(),
3036 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3040 * Generate the navigation links when browsing through an article revisions
3041 * It shows the information as:
3042 * Revision as of \<date\>; view current revision
3043 * \<- Previous version | Next Version -\>
3045 * @param $oldid String: revision ID of this article revision
3047 public function setOldSubtitle( $oldid = 0 ) {
3048 global $wgLang, $wgOut, $wgUser, $wgRequest;
3050 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3054 $revision = Revision
::newFromId( $oldid );
3056 $current = ( $oldid == $this->mLatest
);
3057 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3058 $sk = $wgUser->getSkin();
3060 ?
wfMsgHtml( 'currentrevisionlink' )
3061 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'currentrevisionlink' ) );
3063 ?
wfMsgHtml( 'diff' )
3064 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
3065 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3067 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
3068 : wfMsgHtml( 'previousrevision' );
3070 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
3071 : wfMsgHtml( 'diff' );
3072 $nextlink = $current
3073 ?
wfMsgHtml( 'nextrevision' )
3074 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
3075 $nextdiff = $current
3076 ?
wfMsgHtml( 'diff' )
3077 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
3080 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3081 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
3082 if( $revision->isCurrent() ) {
3083 // We don't handle top deleted edits too well
3084 $cdel = wfMsgHtml( 'rev-delundel' );
3085 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3086 // If revision was hidden from sysops
3087 $cdel = wfMsgHtml( 'rev-delundel' );
3089 $cdel = $sk->makeKnownLinkObj( $revdel,
3090 wfMsgHtml('rev-delundel'),
3091 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
3092 '&oldid=' . urlencode( $oldid ) );
3093 // Bolden oversighted content
3094 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
3095 $cdel = "<strong>$cdel</strong>";
3097 $cdel = "(<small>$cdel</small>) ";
3099 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3100 # Show user links if allowed to see them. If hidden, then show them only if requested...
3101 $userlinks = $sk->revUserTools( $revision, !$unhide );
3103 $m = wfMsg( 'revision-info-current' );
3104 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3105 ?
'revision-info-current'
3108 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ),
3109 $td, $userlinks, $revision->getID() ) . "</div>\n" .
3111 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3112 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3113 $wgOut->setSubtitle( $r );
3117 * This function is called right before saving the wikitext,
3118 * so we can do things like signatures and links-in-context.
3120 * @param $text String
3122 public function preSaveTransform( $text ) {
3123 global $wgParser, $wgUser;
3124 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3127 /* Caching functions */
3130 * checkLastModified returns true if it has taken care of all
3131 * output to the client that is necessary for this request.
3132 * (that is, it has sent a cached version of the page)
3134 protected function tryFileCache() {
3135 static $called = false;
3137 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3141 if( $this->isFileCacheable() ) {
3142 $cache = new HTMLFileCache( $this->mTitle
);
3143 if( $cache->isFileCacheGood( $this->mTouched
) ) {
3144 wfDebug( "Article::tryFileCache(): about to load file\n" );
3145 $cache->loadFromFileCache();
3148 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3149 ob_start( array(&$cache, 'saveToFileCache' ) );
3152 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3158 * Check if the page can be cached
3161 public function isFileCacheable() {
3163 if( HTMLFileCache
::useFileCache() ) {
3164 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3165 // Extension may have reason to disable file caching on some pages.
3167 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3174 * Loads page_touched and returns a value indicating if it should be used
3177 public function checkTouched() {
3178 if( !$this->mDataLoaded
) {
3179 $this->loadPageData();
3181 return !$this->mIsRedirect
;
3185 * Get the page_touched field
3187 public function getTouched() {
3188 # Ensure that page data has been loaded
3189 if( !$this->mDataLoaded
) {
3190 $this->loadPageData();
3192 return $this->mTouched
;
3196 * Get the page_latest field
3198 public function getLatest() {
3199 if( !$this->mDataLoaded
) {
3200 $this->loadPageData();
3202 return (int)$this->mLatest
;
3206 * Edit an article without doing all that other stuff
3207 * The article must already exist; link tables etc
3208 * are not updated, caches are not flushed.
3210 * @param $text String: text submitted
3211 * @param $comment String: comment submitted
3212 * @param $minor Boolean: whereas it's a minor modification
3214 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3215 wfProfileIn( __METHOD__
);
3217 $dbw = wfGetDB( DB_MASTER
);
3218 $revision = new Revision( array(
3219 'page' => $this->getId(),
3221 'comment' => $comment,
3222 'minor_edit' => $minor ?
1 : 0,
3224 $revision->insertOn( $dbw );
3225 $this->updateRevisionOn( $dbw, $revision );
3227 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3229 wfProfileOut( __METHOD__
);
3233 * Used to increment the view counter
3235 * @param $id Integer: article id
3237 public static function incViewCount( $id ) {
3238 $id = intval( $id );
3239 global $wgHitcounterUpdateFreq, $wgDBtype;
3241 $dbw = wfGetDB( DB_MASTER
);
3242 $pageTable = $dbw->tableName( 'page' );
3243 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3244 $acchitsTable = $dbw->tableName( 'acchits' );
3246 if( $wgHitcounterUpdateFreq <= 1 ) {
3247 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3251 # Not important enough to warrant an error page in case of failure
3252 $oldignore = $dbw->ignoreErrors( true );
3254 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3256 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3257 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3258 # Most of the time (or on SQL errors), skip row count check
3259 $dbw->ignoreErrors( $oldignore );
3263 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3264 $row = $dbw->fetchObject( $res );
3265 $rown = intval( $row->n
);
3266 if( $rown >= $wgHitcounterUpdateFreq ){
3267 wfProfileIn( 'Article::incViewCount-collect' );
3268 $old_user_abort = ignore_user_abort( true );
3270 if($wgDBtype == 'mysql')
3271 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3272 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3273 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3274 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3276 $dbw->query("DELETE FROM $hitcounterTable");
3277 if($wgDBtype == 'mysql') {
3278 $dbw->query('UNLOCK TABLES');
3279 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3280 'WHERE page_id = hc_id');
3283 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3284 "FROM $acchitsTable WHERE page_id = hc_id");
3286 $dbw->query("DROP TABLE $acchitsTable");
3288 ignore_user_abort( $old_user_abort );
3289 wfProfileOut( 'Article::incViewCount-collect' );
3291 $dbw->ignoreErrors( $oldignore );
3295 * The onArticle*() functions are supposed to be a kind of hooks
3296 * which should be called whenever any of the specified actions
3299 * This is a good place to put code to clear caches, for instance.
3301 * This is called on page move and undelete, as well as edit
3303 * @param $title a title object
3306 public static function onArticleCreate( $title ) {
3307 # Update existence markers on article/talk tabs...
3308 if( $title->isTalkPage() ) {
3309 $other = $title->getSubjectPage();
3311 $other = $title->getTalkPage();
3313 $other->invalidateCache();
3314 $other->purgeSquid();
3316 $title->touchLinks();
3317 $title->purgeSquid();
3318 $title->deleteTitleProtection();
3321 public static function onArticleDelete( $title ) {
3322 global $wgMessageCache;
3323 # Update existence markers on article/talk tabs...
3324 if( $title->isTalkPage() ) {
3325 $other = $title->getSubjectPage();
3327 $other = $title->getTalkPage();
3329 $other->invalidateCache();
3330 $other->purgeSquid();
3332 $title->touchLinks();
3333 $title->purgeSquid();
3336 HTMLFileCache
::clearFileCache( $title );
3339 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3340 $wgMessageCache->replace( $title->getDBkey(), false );
3343 if( $title->getNamespace() == NS_FILE
) {
3344 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3345 $update->doUpdate();
3348 if( $title->getNamespace() == NS_USER_TALK
) {
3349 $user = User
::newFromName( $title->getText(), false );
3350 $user->setNewtalk( false );
3353 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3357 * Purge caches on page update etc
3359 public static function onArticleEdit( $title, $flags = '' ) {
3360 global $wgDeferredUpdateList;
3362 // Invalidate caches of articles which include this page
3363 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3365 // Invalidate the caches of all pages which redirect here
3366 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3368 # Purge squid for this page only
3369 $title->purgeSquid();
3371 # Clear file cache for this page only
3372 HTMLFileCache
::clearFileCache( $title );
3378 * Overriden by ImagePage class, only present here to avoid a fatal error
3379 * Called for ?action=revert
3381 public function revert() {
3383 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3387 * Info about this page
3388 * Called for ?action=info when $wgAllowPageInfo is on.
3390 public function info() {
3391 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3393 if( !$wgAllowPageInfo ) {
3394 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3398 $page = $this->mTitle
->getSubjectPage();
3400 $wgOut->setPagetitle( $page->getPrefixedText() );
3401 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3402 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3404 if( !$this->mTitle
->exists() ) {
3405 $wgOut->addHTML( '<div class="noarticletext">' );
3406 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3407 // This doesn't quite make sense; the user is asking for
3408 // information about the _page_, not the message... -- RC
3409 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3411 $msg = $wgUser->isLoggedIn()
3413 : 'noarticletextanon';
3414 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3416 $wgOut->addHTML( '</div>' );
3418 $dbr = wfGetDB( DB_SLAVE
);
3420 'wl_title' => $page->getDBkey(),
3421 'wl_namespace' => $page->getNamespace() );
3422 $numwatchers = $dbr->selectField(
3427 $this->getSelectOptions() );
3429 $pageInfo = $this->pageCountInfo( $page );
3430 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3432 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3433 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3435 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3437 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3439 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3441 $wgOut->addHTML( '</ul>' );
3446 * Return the total number of edits and number of unique editors
3447 * on a given page. If page does not exist, returns false.
3449 * @param $title Title object
3452 public function pageCountInfo( $title ) {
3453 $id = $title->getArticleId();
3457 $dbr = wfGetDB( DB_SLAVE
);
3458 $rev_clause = array( 'rev_page' => $id );
3459 $edits = $dbr->selectField(
3464 $this->getSelectOptions()
3466 $authors = $dbr->selectField(
3468 'COUNT(DISTINCT rev_user_text)',
3471 $this->getSelectOptions()
3473 return array( 'edits' => $edits, 'authors' => $authors );
3477 * Return a list of templates used by this article.
3478 * Uses the templatelinks table
3480 * @return Array of Title objects
3482 public function getUsedTemplates() {
3484 $id = $this->mTitle
->getArticleID();
3488 $dbr = wfGetDB( DB_SLAVE
);
3489 $res = $dbr->select( array( 'templatelinks' ),
3490 array( 'tl_namespace', 'tl_title' ),
3491 array( 'tl_from' => $id ),
3493 if( $res !== false ) {
3494 foreach( $res as $row ) {
3495 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3498 $dbr->freeResult( $res );
3503 * Returns a list of hidden categories this page is a member of.
3504 * Uses the page_props and categorylinks tables.
3506 * @return Array of Title objects
3508 public function getHiddenCategories() {
3510 $id = $this->mTitle
->getArticleID();
3514 $dbr = wfGetDB( DB_SLAVE
);
3515 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3517 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3518 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3520 if( $res !== false ) {
3521 foreach( $res as $row ) {
3522 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3525 $dbr->freeResult( $res );
3530 * Return an applicable autosummary if one exists for the given edit.
3531 * @param $oldtext String: the previous text of the page.
3532 * @param $newtext String: The submitted text of the page.
3533 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3534 * @return string An appropriate autosummary, or an empty string.
3536 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3537 # Decide what kind of autosummary is needed.
3539 # Redirect autosummaries
3540 $ot = Title
::newFromRedirect( $oldtext );
3541 $rt = Title
::newFromRedirect( $newtext );
3542 if( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3543 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3546 # New page autosummaries
3547 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3548 # If they're making a new article, give its text, truncated, in the summary.
3550 $truncatedtext = $wgContLang->truncate(
3551 str_replace("\n", ' ', $newtext),
3552 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3553 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3556 # Blanking autosummaries
3557 if( $oldtext != '' && $newtext == '' ) {
3558 return wfMsgForContent( 'autosumm-blank' );
3559 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3560 # Removing more than 90% of the article
3562 $truncatedtext = $wgContLang->truncate(
3564 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3565 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3568 # If we reach this point, there's no applicable autosummary for our case, so our
3569 # autosummary is empty.
3574 * Add the primary page-view wikitext to the output buffer
3575 * Saves the text into the parser cache if possible.
3576 * Updates templatelinks if it is out of date.
3578 * @param $text String
3579 * @param $cache Boolean
3581 public function outputWikiText( $text, $cache = true ) {
3582 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3584 $popts = $wgOut->parserOptions();
3585 $popts->setTidy(true);
3586 $popts->enableLimitReport();
3587 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3588 $popts, true, true, $this->getRevIdFetched() );
3589 $popts->setTidy(false);
3590 $popts->enableLimitReport( false );
3591 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3592 $parserCache = ParserCache
::singleton();
3593 $parserCache->save( $parserOutput, $this, $popts );
3595 // Make sure file cache is not used on uncacheable content.
3596 // Output that has magic words in it can still use the parser cache
3597 // (if enabled), though it will generally expire sooner.
3598 if( $parserOutput->getCacheTime() == -1 ||
$parserOutput->containsOldMagic() ) {
3599 $wgUseFileCache = false;
3602 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3603 // templatelinks table may have become out of sync,
3604 // especially if using variable-based transclusions.
3605 // For paranoia, check if things have changed and if
3606 // so apply updates to the database. This will ensure
3607 // that cascaded protections apply as soon as the changes
3610 # Get templates from templatelinks
3611 $id = $this->mTitle
->getArticleID();
3613 $tlTemplates = array();
3615 $dbr = wfGetDB( DB_SLAVE
);
3616 $res = $dbr->select( array( 'templatelinks' ),
3617 array( 'tl_namespace', 'tl_title' ),
3618 array( 'tl_from' => $id ),
3622 foreach( $res as $row ) {
3623 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3626 # Get templates from parser output.
3627 $poTemplates = array();
3628 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3629 foreach ( $templates as $dbk => $id ) {
3630 $key = $row->tl_namespace
. ':'. $row->tl_title
;
3631 $poTemplates["$ns:$dbk"] = true;
3636 # Note that we simulate array_diff_key in PHP <5.0.x
3637 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3639 if( count( $templates_diff ) > 0 ) {
3640 # Whee, link updates time.
3641 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3646 $wgOut->addParserOutput( $parserOutput );
3650 * Update all the appropriate counts in the category table, given that
3651 * we've added the categories $added and deleted the categories $deleted.
3653 * @param $added array The names of categories that were added
3654 * @param $deleted array The names of categories that were deleted
3657 public function updateCategoryCounts( $added, $deleted ) {
3658 $ns = $this->mTitle
->getNamespace();
3659 $dbw = wfGetDB( DB_MASTER
);
3661 # First make sure the rows exist. If one of the "deleted" ones didn't
3662 # exist, we might legitimately not create it, but it's simpler to just
3663 # create it and then give it a negative value, since the value is bogus
3666 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3667 $insertCats = array_merge( $added, $deleted );
3668 if( !$insertCats ) {
3669 # Okay, nothing to do
3672 $insertRows = array();
3673 foreach( $insertCats as $cat ) {
3674 $insertRows[] = array( 'cat_title' => $cat );
3676 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3678 $addFields = array( 'cat_pages = cat_pages + 1' );
3679 $removeFields = array( 'cat_pages = cat_pages - 1' );
3680 if( $ns == NS_CATEGORY
) {
3681 $addFields[] = 'cat_subcats = cat_subcats + 1';
3682 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3683 } elseif( $ns == NS_FILE
) {
3684 $addFields[] = 'cat_files = cat_files + 1';
3685 $removeFields[] = 'cat_files = cat_files - 1';
3692 array( 'cat_title' => $added ),
3700 array( 'cat_title' => $deleted ),