8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
19 var $mComment = ''; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
37 var $mTimestamp = ''; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
46 * Constructor and clear the article
47 * @param $title Reference to a Title object.
48 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 function __construct( Title
$title, $oldId = null ) {
51 $this->mTitle
=& $title;
52 $this->mOldId
= $oldId;
56 * Tell the page view functions that this view was redirected
57 * from another page on the wiki.
58 * @param $from Title object.
60 function setRedirectedFrom( $from ) {
61 $this->mRedirectedFrom
= $from;
65 * If this page is a redirect, get its target
67 * The target will be fetched from the redirect table if possible.
68 * If this page doesn't have an entry there, call insertRedirect()
69 * @return mixed Title object, or null if this page is not a redirect
71 public function getRedirectTarget() {
72 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
74 if(!is_null($this->mRedirectTarget
))
75 return $this->mRedirectTarget
;
77 # Query the redirect table
78 $dbr = wfGetDB(DB_SLAVE
);
79 $res = $dbr->select('redirect',
80 array('rd_namespace', 'rd_title'),
81 array('rd_from' => $this->getID()),
84 $row = $dbr->fetchObject($res);
86 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
88 # This page doesn't have an entry in the redirect table
89 return $this->mRedirectTarget
= $this->insertRedirect();
93 * Insert an entry for this page into the redirect table.
95 * Don't call this function directly unless you know what you're doing.
96 * @return Title object
98 public function insertRedirect() {
99 $retval = Title
::newFromRedirect($this->getContent());
102 $dbw = wfGetDB(DB_MASTER
);
103 $dbw->replace('redirect', array('rd_from'), array(
104 'rd_from' => $this->getID(),
105 'rd_namespace' => $retval->getNamespace(),
106 'rd_title' => $retval->getDBKey()
112 * Get the Title object this page redirects to
114 * @return mixed false, Title of in-wiki target, or string with URL
116 public function followRedirect() {
117 $text = $this->getContent();
118 return self
::followRedirectText( $text );
122 * Get the Title object this text redirects to
124 * @return mixed false, Title of in-wiki target, or string with URL
126 public function followRedirectText( $text ) {
127 $rt = Title
::newFromRedirect( $text );
128 # process if title object is valid and not special:userlogout
130 if( $rt->getInterwiki() != '' ) {
131 if( $rt->isLocal() ) {
132 // Offsite wikis need an HTTP redirect.
134 // This can be hard to reverse and may produce loops,
135 // so they may be disabled in the site configuration.
137 $source = $this->mTitle
->getFullURL( 'redirect=no' );
138 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
141 if( $rt->getNamespace() == NS_SPECIAL
) {
142 // Gotta handle redirects to special pages differently:
143 // Fill the HTTP response "Location" header and ignore
144 // the rest of the page we're on.
146 // This can be hard to reverse, so they may be disabled.
148 if( $rt->isSpecial( 'Userlogout' ) ) {
151 return $rt->getFullURL();
157 // No or invalid redirect
162 * get the title object of the article
164 function getTitle() {
165 return $this->mTitle
;
173 $this->mDataLoaded
= false;
174 $this->mContentLoaded
= false;
176 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
177 $this->mRedirectedFrom
= null; # Title object if set
178 $this->mRedirectTarget
= null; # Title object if set
180 $this->mTimestamp
= $this->mComment
= '';
181 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
182 $this->mTouched
= '19700101000000';
183 $this->mForUpdate
= false;
184 $this->mIsRedirect
= false;
185 $this->mRevIdFetched
= 0;
186 $this->mRedirectUrl
= false;
187 $this->mLatest
= false;
188 $this->mPreparedEdit
= false;
192 * Note that getContent/loadContent do not follow redirects anymore.
193 * If you need to fetch redirectable content easily, try
194 * the shortcut in Article::followContent()
196 * @todo There are still side-effects in this!
197 * In general, you should use the Revision class, not Article,
198 * to fetch text for purposes other than page views.
200 * @return Return the text of this revision
202 function getContent() {
203 global $wgUser, $wgOut, $wgMessageCache;
205 wfProfileIn( __METHOD__
);
207 if ( 0 == $this->getID() ) {
208 wfProfileOut( __METHOD__
);
209 $wgOut->setRobotPolicy( 'noindex,nofollow' );
211 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
212 $wgMessageCache->loadAllMessages();
213 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
215 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
218 return "<div class='noarticletext'>\n$ret\n</div>";
220 $this->loadContent();
221 wfProfileOut( __METHOD__
);
222 return $this->mContent
;
227 * This function returns the text of a section, specified by a number ($section).
228 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
229 * the first section before any such heading (section 0).
231 * If a section contains subsections, these are also returned.
233 * @param $text String: text to look in
234 * @param $section Integer: section number
235 * @return string text of the requested section
238 function getSection($text,$section) {
240 return $wgParser->getSection( $text, $section );
244 * @return int The oldid of the article that is to be shown, 0 for the
247 function getOldID() {
248 if ( is_null( $this->mOldId
) ) {
249 $this->mOldId
= $this->getOldIDFromRequest();
251 return $this->mOldId
;
255 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
257 * @return int The old id for the request
259 function getOldIDFromRequest() {
261 $this->mRedirectUrl
= false;
262 $oldid = $wgRequest->getVal( 'oldid' );
263 if ( isset( $oldid ) ) {
264 $oldid = intval( $oldid );
265 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
266 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
270 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
272 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
273 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
291 * Load the revision (including text) into this object
293 function loadContent() {
294 if ( $this->mContentLoaded
) return;
297 $oldid = $this->getOldID();
299 # Pre-fill content with error message so that if something
300 # fails we'll have something telling us what we intended.
301 $this->mOldId
= $oldid;
302 $this->fetchContent( $oldid );
307 * Fetch a page record with the given conditions
308 * @param Database $dbr
309 * @param array $conditions
312 function pageData( $dbr, $conditions ) {
326 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
327 $row = $dbr->selectRow(
333 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
338 * @param Database $dbr
339 * @param Title $title
341 function pageDataFromTitle( $dbr, $title ) {
342 return $this->pageData( $dbr, array(
343 'page_namespace' => $title->getNamespace(),
344 'page_title' => $title->getDBkey() ) );
348 * @param Database $dbr
351 function pageDataFromId( $dbr, $id ) {
352 return $this->pageData( $dbr, array( 'page_id' => $id ) );
356 * Set the general counter, title etc data loaded from
359 * @param object $data
362 function loadPageData( $data = 'fromdb' ) {
363 if ( $data === 'fromdb' ) {
364 $dbr = wfGetDB( DB_MASTER
);
365 $data = $this->pageDataFromId( $dbr, $this->getId() );
368 $lc = LinkCache
::singleton();
370 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
372 $this->mTitle
->mArticleID
= $data->page_id
;
374 # Old-fashioned restrictions.
375 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
377 $this->mCounter
= $data->page_counter
;
378 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
379 $this->mIsRedirect
= $data->page_is_redirect
;
380 $this->mLatest
= $data->page_latest
;
382 if ( is_object( $this->mTitle
) ) {
383 $lc->addBadLinkObj( $this->mTitle
);
385 $this->mTitle
->mArticleID
= 0;
388 $this->mDataLoaded
= true;
392 * Get text of an article from database
393 * Does *NOT* follow redirects.
394 * @param int $oldid 0 for whatever the latest revision is
397 function fetchContent( $oldid = 0 ) {
398 if ( $this->mContentLoaded
) {
399 return $this->mContent
;
402 $dbr = wfGetDB( DB_MASTER
);
404 # Pre-fill content with error message so that if something
405 # fails we'll have something telling us what we intended.
406 $t = $this->mTitle
->getPrefixedText();
407 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
408 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
411 $revision = Revision
::newFromId( $oldid );
412 if( is_null( $revision ) ) {
413 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
416 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
418 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
421 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
422 $this->loadPageData( $data );
424 if( !$this->mDataLoaded
) {
425 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
427 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
430 $this->loadPageData( $data );
432 $revision = Revision
::newFromId( $this->mLatest
);
433 if( is_null( $revision ) ) {
434 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
439 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
440 // We should instead work with the Revision object when we need it...
441 $this->mContent
= $revision->revText(); // Loads if user is allowed
443 $this->mUser
= $revision->getUser();
444 $this->mUserText
= $revision->getUserText();
445 $this->mComment
= $revision->getComment();
446 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
448 $this->mRevIdFetched
= $revision->getId();
449 $this->mContentLoaded
= true;
450 $this->mRevision
=& $revision;
452 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
454 return $this->mContent
;
458 * Read/write accessor to select FOR UPDATE
460 * @param $x Mixed: FIXME
462 function forUpdate( $x = NULL ) {
463 return wfSetVar( $this->mForUpdate
, $x );
467 * Get the database which should be used for reads
470 * @deprecated - just call wfGetDB( DB_MASTER ) instead
473 wfDeprecated( __METHOD__
);
474 return wfGetDB( DB_MASTER
);
478 * Get options for all SELECT statements
480 * @param $options Array: an optional options array which'll be appended to
482 * @return Array: options
484 function getSelectOptions( $options = '' ) {
485 if ( $this->mForUpdate
) {
486 if ( is_array( $options ) ) {
487 $options[] = 'FOR UPDATE';
489 $options = 'FOR UPDATE';
496 * @return int Page ID
499 if( $this->mTitle
) {
500 return $this->mTitle
->getArticleID();
507 * @return bool Whether or not the page exists in the database
510 return $this->getId() != 0;
514 * @return int The view count for the page
516 function getCount() {
517 if ( -1 == $this->mCounter
) {
518 $id = $this->getID();
522 $dbr = wfGetDB( DB_SLAVE
);
523 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
524 'Article::getCount', $this->getSelectOptions() );
527 return $this->mCounter
;
531 * Determine whether a page would be suitable for being counted as an
532 * article in the site_stats table based on the title & its content
534 * @param $text String: text to analyze
537 function isCountable( $text ) {
538 global $wgUseCommaCount;
540 $token = $wgUseCommaCount ?
',' : '[[';
542 $this->mTitle
->isContentPage()
543 && !$this->isRedirect( $text )
544 && in_string( $token, $text );
548 * Tests if the article text represents a redirect
550 * @param $text String: FIXME
553 function isRedirect( $text = false ) {
554 if ( $text === false ) {
555 if ( $this->mDataLoaded
)
556 return $this->mIsRedirect
;
558 // Apparently loadPageData was never called
559 $this->loadContent();
560 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
562 $titleObj = Title
::newFromRedirect( $text );
564 return $titleObj !== NULL;
568 * Returns true if the currently-referenced revision is the current edit
569 * to this page (and it exists).
572 function isCurrent() {
573 # If no oldid, this is the current version.
574 if ($this->getOldID() == 0)
577 return $this->exists() &&
578 isset( $this->mRevision
) &&
579 $this->mRevision
->isCurrent();
583 * Loads everything except the text
584 * This isn't necessary for all uses, so it's only done if needed.
587 function loadLastEdit() {
588 if ( -1 != $this->mUser
)
591 # New or non-existent articles have no user information
592 $id = $this->getID();
593 if ( 0 == $id ) return;
595 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
596 if( !is_null( $this->mLastRevision
) ) {
597 $this->mUser
= $this->mLastRevision
->getUser();
598 $this->mUserText
= $this->mLastRevision
->getUserText();
599 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
600 $this->mComment
= $this->mLastRevision
->getComment();
601 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
602 $this->mRevIdFetched
= $this->mLastRevision
->getId();
606 function getTimestamp() {
607 // Check if the field has been filled by ParserCache::get()
608 if ( !$this->mTimestamp
) {
609 $this->loadLastEdit();
611 return wfTimestamp(TS_MW
, $this->mTimestamp
);
615 $this->loadLastEdit();
619 function getUserText() {
620 $this->loadLastEdit();
621 return $this->mUserText
;
624 function getComment() {
625 $this->loadLastEdit();
626 return $this->mComment
;
629 function getMinorEdit() {
630 $this->loadLastEdit();
631 return $this->mMinorEdit
;
634 function getRevIdFetched() {
635 $this->loadLastEdit();
636 return $this->mRevIdFetched
;
640 * @param $limit Integer: default 0.
641 * @param $offset Integer: default 0.
643 function getContributors($limit = 0, $offset = 0) {
644 # XXX: this is expensive; cache this info somewhere.
647 $dbr = wfGetDB( DB_SLAVE
);
648 $revTable = $dbr->tableName( 'revision' );
649 $userTable = $dbr->tableName( 'user' );
650 $user = $this->getUser();
651 $pageId = $this->getId();
653 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
654 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
655 WHERE rev_page = $pageId
656 AND rev_user != $user
657 GROUP BY rev_user, rev_user_text, user_real_name
658 ORDER BY timestamp DESC";
660 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
661 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
663 $sql .= ' '. $this->getSelectOptions();
665 $res = $dbr->query($sql, __METHOD__
);
667 while ( $line = $dbr->fetchObject( $res ) ) {
668 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
671 $dbr->freeResult($res);
676 * This is the default action of the script: just view the page of
680 global $wgUser, $wgOut, $wgRequest, $wgContLang;
681 global $wgEnableParserCache, $wgStylePath, $wgParser;
682 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
683 global $wgDefaultRobotPolicy;
684 $sk = $wgUser->getSkin();
686 wfProfileIn( __METHOD__
);
688 $parserCache = ParserCache
::singleton();
689 $ns = $this->mTitle
->getNamespace(); # shortcut
691 # Get variables from query string
692 $oldid = $this->getOldID();
694 # getOldID may want us to redirect somewhere else
695 if ( $this->mRedirectUrl
) {
696 $wgOut->redirect( $this->mRedirectUrl
);
697 wfProfileOut( __METHOD__
);
701 $diff = $wgRequest->getVal( 'diff' );
702 $rcid = $wgRequest->getVal( 'rcid' );
703 $rdfrom = $wgRequest->getVal( 'rdfrom' );
704 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
705 $purge = $wgRequest->getVal( 'action' ) == 'purge';
707 $wgOut->setArticleFlag( true );
709 # Discourage indexing of printable versions, but encourage following
710 if( $wgOut->isPrintable() ) {
711 $policy = 'noindex,follow';
712 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
713 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
714 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
715 # Honour customised robot policies for this namespace
716 $policy = $wgNamespaceRobotPolicies[$ns];
718 $policy = $wgDefaultRobotPolicy;
720 $wgOut->setRobotPolicy( $policy );
722 # If we got diff and oldid in the query, we want to see a
723 # diff page instead of the article.
725 if ( !is_null( $diff ) ) {
726 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
728 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
729 // DifferenceEngine directly fetched the revision:
730 $this->mRevIdFetched
= $de->mNewid
;
731 $de->showDiffPage( $diffOnly );
733 // Needed to get the page's current revision
734 $this->loadPageData();
735 if( $diff == 0 ||
$diff == $this->mLatest
) {
736 # Run view updates for current revision only
737 $this->viewUpdates();
739 wfProfileOut( __METHOD__
);
743 if ( empty( $oldid ) && $this->checkTouched() ) {
744 $wgOut->setETag($parserCache->getETag($this, $wgUser));
746 if( $wgOut->checkLastModified( $this->mTouched
) ){
747 wfProfileOut( __METHOD__
);
749 } else if ( $this->tryFileCache() ) {
750 # tell wgOut that output is taken care of
752 $this->viewUpdates();
753 wfProfileOut( __METHOD__
);
758 # Should the parser cache be used?
759 $pcache = $this->useParserCache( $oldid );
760 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
761 if ( $wgUser->getOption( 'stubthreshold' ) ) {
762 wfIncrStats( 'pcache_miss_stub' );
765 $wasRedirected = false;
766 if ( isset( $this->mRedirectedFrom
) ) {
767 // This is an internally redirected page view.
768 // We'll need a backlink to the source page for navigation.
769 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
770 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
771 $s = wfMsg( 'redirectedfrom', $redir );
772 $wgOut->setSubtitle( $s );
774 // Set the fragment if one was specified in the redirect
775 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
776 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
777 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
779 $wasRedirected = true;
781 } elseif ( !empty( $rdfrom ) ) {
782 // This is an externally redirected view, from some other wiki.
783 // If it was reported from a trusted site, supply a backlink.
784 global $wgRedirectSources;
785 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
786 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
787 $s = wfMsg( 'redirectedfrom', $redir );
788 $wgOut->setSubtitle( $s );
789 $wasRedirected = true;
794 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
796 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
797 // Ensure that UI elements requiring revision ID have
798 // the correct version information.
799 $wgOut->setRevisionId( $this->mLatest
);
803 # Fetch content and check for errors
804 if ( !$outputDone ) {
805 $text = $this->getContent();
806 if ( $text === false ) {
807 # Failed to load, replace text with error message
808 $t = $this->mTitle
->getPrefixedText();
810 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
811 $text = wfMsg( 'missing-article', $t, $d );
813 $text = wfMsg( 'noarticletext' );
817 # Another whitelist check in case oldid is altering the title
818 if ( !$this->mTitle
->userCanRead() ) {
819 $wgOut->loginToUse();
821 wfProfileOut( __METHOD__
);
825 # We're looking at an old revision
826 if ( !empty( $oldid ) ) {
827 $wgOut->setRobotPolicy( 'noindex,nofollow' );
828 if( is_null( $this->mRevision
) ) {
829 // FIXME: This would be a nice place to load the 'no such page' text.
831 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
832 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
833 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
834 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
835 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
836 wfProfileOut( __METHOD__
);
839 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
840 // and we are allowed to see...
846 $wgOut->setRevisionId( $this->getRevIdFetched() );
848 // Pages containing custom CSS or JavaScript get special treatment
849 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
850 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
851 // Give hooks a chance to customise the output
852 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
853 // Wrap the whole lot in a <pre> and don't parse
855 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
856 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
857 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
858 $wgOut->addHtml( "\n</pre>\n" );
860 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
861 # Don't append the subtitle if this was an old revision
862 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
863 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
864 $wgOut->addParserOutputNoText( $parseout );
865 } else if ( $pcache ) {
866 # Display content and save to parser cache
867 $this->outputWikiText( $text );
869 # Display content, don't attempt to save to parser cache
870 # Don't show section-edit links on old revisions... this way lies madness.
871 if( !$this->isCurrent() ) {
872 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
874 # Display content and don't save to parser cache
875 # With timing hack -- TS 2006-07-26
877 $this->outputWikiText( $text, false );
882 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
883 $this->mTitle
->getPrefixedDBkey()));
886 if( !$this->isCurrent() ) {
887 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
891 /* title may have been set from the cache */
892 $t = $wgOut->getPageTitle();
894 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
897 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
898 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
899 $wgOut->addWikiMsg('anontalkpagetext');
902 # If we have been passed an &rcid= parameter, we want to give the user a
903 # chance to mark this new article as patrolled.
904 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
906 "<div class='patrollink'>" .
907 wfMsgHtml( 'markaspatrolledlink',
908 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
909 "action=markpatrolled&rcid=$rcid" )
916 if ($wgUseTrackbacks)
917 $this->addTrackbacks();
919 $this->viewUpdates();
920 wfProfileOut( __METHOD__
);
924 * Should the parser cache be used?
926 protected function useParserCache( $oldid ) {
927 global $wgUser, $wgEnableParserCache;
929 return $wgEnableParserCache
930 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
933 && !$this->mTitle
->isCssOrJsPage()
934 && !$this->mTitle
->isCssJsSubpage();
939 * @param Title $target Title of destination to redirect
940 * @param Bool $appendSubtitle Object[optional]
941 * @param Bool $forceKnown Should the image be shown as a bluelink regardless of existence?
943 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
944 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
947 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
948 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
950 if( $appendSubtitle ) {
951 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
953 $sk = $wgUser->getSkin();
955 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
957 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
959 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
960 '<span class="redirectText">'.$link.'</span>';
964 function addTrackbacks() {
965 global $wgOut, $wgUser;
967 $dbr = wfGetDB(DB_SLAVE
);
969 /* FROM */ 'trackbacks',
970 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
971 /* WHERE */ array('tb_page' => $this->getID())
974 if (!$dbr->numrows($tbs))
978 while ($o = $dbr->fetchObject($tbs)) {
980 if ($wgUser->isAllowed( 'trackback' )) {
981 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
982 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
983 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
986 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
993 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
996 function deletetrackback() {
997 global $wgUser, $wgRequest, $wgOut, $wgTitle;
999 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
1000 $wgOut->addWikiMsg( 'sessionfailure' );
1004 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1006 if (count($permission_errors)>0)
1008 $wgOut->showPermissionsErrorPage( $permission_errors );
1012 $db = wfGetDB(DB_MASTER
);
1013 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1014 $wgTitle->invalidateCache();
1015 $wgOut->addWikiMsg('trackbackdeleteok');
1021 $wgOut->setArticleBodyOnly(true);
1026 * Handle action=purge
1029 global $wgUser, $wgRequest, $wgOut;
1031 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1032 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1036 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1037 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1038 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1039 $msg = str_replace( '$1',
1040 "<form method=\"post\" action=\"$action\">\n" .
1041 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1042 "</form>\n", $msg );
1044 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1045 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1046 $wgOut->addHTML( $msg );
1051 * Perform the actions of a page purging
1053 function doPurge() {
1055 // Invalidate the cache
1056 $this->mTitle
->invalidateCache();
1058 if ( $wgUseSquid ) {
1059 // Commit the transaction before the purge is sent
1060 $dbw = wfGetDB( DB_MASTER
);
1061 $dbw->immediateCommit();
1064 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1065 $update->doUpdate();
1067 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1068 global $wgMessageCache;
1069 if ( $this->getID() == 0 ) {
1072 $text = $this->getContent();
1074 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1080 * Insert a new empty page record for this article.
1081 * This *must* be followed up by creating a revision
1082 * and running $this->updateToLatest( $rev_id );
1083 * or else the record will be left in a funky state.
1084 * Best if all done inside a transaction.
1086 * @param Database $dbw
1087 * @return int The newly created page_id key
1090 function insertOn( $dbw ) {
1091 wfProfileIn( __METHOD__
);
1093 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1094 $dbw->insert( 'page', array(
1095 'page_id' => $page_id,
1096 'page_namespace' => $this->mTitle
->getNamespace(),
1097 'page_title' => $this->mTitle
->getDBkey(),
1098 'page_counter' => 0,
1099 'page_restrictions' => '',
1100 'page_is_redirect' => 0, # Will set this shortly...
1102 'page_random' => wfRandom(),
1103 'page_touched' => $dbw->timestamp(),
1104 'page_latest' => 0, # Fill this in shortly...
1105 'page_len' => 0, # Fill this in shortly...
1107 $newid = $dbw->insertId();
1109 $this->mTitle
->resetArticleId( $newid );
1111 wfProfileOut( __METHOD__
);
1116 * Update the page record to point to a newly saved revision.
1118 * @param Database $dbw
1119 * @param Revision $revision For ID number, and text used to set
1120 length and redirect status fields
1121 * @param int $lastRevision If given, will not overwrite the page field
1122 * when different from the currently set value.
1123 * Giving 0 indicates the new page flag should
1125 * @param bool $lastRevIsRedirect If given, will optimize adding and
1126 * removing rows in redirect table.
1127 * @return bool true on success, false on failure
1130 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1131 wfProfileIn( __METHOD__
);
1133 $text = $revision->getText();
1134 $rt = Title
::newFromRedirect( $text );
1136 $conditions = array( 'page_id' => $this->getId() );
1137 if( !is_null( $lastRevision ) ) {
1138 # An extra check against threads stepping on each other
1139 $conditions['page_latest'] = $lastRevision;
1142 $dbw->update( 'page',
1144 'page_latest' => $revision->getId(),
1145 'page_touched' => $dbw->timestamp(),
1146 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1147 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1148 'page_len' => strlen( $text ),
1153 $result = $dbw->affectedRows() != 0;
1156 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1159 wfProfileOut( __METHOD__
);
1164 * Add row to the redirect table if this is a redirect, remove otherwise.
1166 * @param Database $dbw
1167 * @param $redirectTitle a title object pointing to the redirect target,
1168 * or NULL if this is not a redirect
1169 * @param bool $lastRevIsRedirect If given, will optimize adding and
1170 * removing rows in redirect table.
1171 * @return bool true on success, false on failure
1174 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1176 // Always update redirects (target link might have changed)
1177 // Update/Insert if we don't know if the last revision was a redirect or not
1178 // Delete if changing from redirect to non-redirect
1179 $isRedirect = !is_null($redirectTitle);
1180 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1182 wfProfileIn( __METHOD__
);
1186 // This title is a redirect, Add/Update row in the redirect table
1187 $set = array( /* SET */
1188 'rd_namespace' => $redirectTitle->getNamespace(),
1189 'rd_title' => $redirectTitle->getDBkey(),
1190 'rd_from' => $this->getId(),
1193 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1195 // This is not a redirect, remove row from redirect table
1196 $where = array( 'rd_from' => $this->getId() );
1197 $dbw->delete( 'redirect', $where, __METHOD__
);
1200 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1201 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1202 wfProfileOut( __METHOD__
);
1203 return ( $dbw->affectedRows() != 0 );
1210 * If the given revision is newer than the currently set page_latest,
1211 * update the page record. Otherwise, do nothing.
1213 * @param Database $dbw
1214 * @param Revision $revision
1216 function updateIfNewerOn( &$dbw, $revision ) {
1217 wfProfileIn( __METHOD__
);
1219 $row = $dbw->selectRow(
1220 array( 'revision', 'page' ),
1221 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1223 'page_id' => $this->getId(),
1224 'page_latest=rev_id' ),
1227 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1228 wfProfileOut( __METHOD__
);
1231 $prev = $row->rev_id
;
1232 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1234 # No or missing previous revision; mark the page as new
1236 $lastRevIsRedirect = null;
1239 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1240 wfProfileOut( __METHOD__
);
1245 * @return string Complete article text, or null if error
1247 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1248 wfProfileIn( __METHOD__
);
1250 if( $section == '' ) {
1251 // Whole-page edit; let the text through unmolested.
1253 if( is_null( $edittime ) ) {
1254 $rev = Revision
::newFromTitle( $this->mTitle
);
1256 $dbw = wfGetDB( DB_MASTER
);
1257 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1259 if( is_null( $rev ) ) {
1260 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1261 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1264 $oldtext = $rev->getText();
1266 if( $section == 'new' ) {
1267 # Inserting a new section
1268 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1269 $text = strlen( trim( $oldtext ) ) > 0
1270 ?
"{$oldtext}\n\n{$subject}{$text}"
1271 : "{$subject}{$text}";
1273 # Replacing an existing section; roll out the big guns
1275 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1280 wfProfileOut( __METHOD__
);
1285 * @deprecated use Article::doEdit()
1287 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1288 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1289 ( $isminor ? EDIT_MINOR
: 0 ) |
1290 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1291 ( $bot ? EDIT_FORCE_BOT
: 0 );
1293 # If this is a comment, add the summary as headline
1294 if ( $comment && $summary != "" ) {
1295 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1298 $this->doEdit( $text, $summary, $flags );
1300 $dbw = wfGetDB( DB_MASTER
);
1302 if (!$this->mTitle
->userIsWatching()) {
1308 if ( $this->mTitle
->userIsWatching() ) {
1314 $this->doRedirect( $this->isRedirect( $text ) );
1318 * @deprecated use Article::doEdit()
1320 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1321 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1322 ( $minor ? EDIT_MINOR
: 0 ) |
1323 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1325 $good = $this->doEdit( $text, $summary, $flags );
1327 $dbw = wfGetDB( DB_MASTER
);
1329 if (!$this->mTitle
->userIsWatching()) {
1335 if ( $this->mTitle
->userIsWatching() ) {
1342 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1343 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1345 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1353 * Change an existing article or create a new article. Updates RC and all necessary caches,
1354 * optionally via the deferred update array.
1356 * $wgUser must be set before calling this function.
1358 * @param string $text New text
1359 * @param string $summary Edit summary
1360 * @param integer $flags bitfield:
1362 * Article is known or assumed to be non-existent, create a new one
1364 * Article is known or assumed to be pre-existing, update it
1366 * Mark this edit minor, if the user is allowed to do so
1368 * Do not log the change in recentchanges
1370 * Mark the edit a "bot" edit regardless of user rights
1371 * EDIT_DEFER_UPDATES
1372 * Defer some of the updates until the end of index.php
1374 * Fill in blank summaries with generated text where possible
1376 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1377 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1378 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1379 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1380 * to MediaWiki's performance-optimised locking strategy.
1381 * @param $baseRevId, the revision ID this edit was based off, if any
1383 * @return bool success
1385 function doEdit( $text, $summary, $flags = 0, $baseRevId = false ) {
1386 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1388 wfProfileIn( __METHOD__
);
1391 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1392 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1394 $flags |
= EDIT_UPDATE
;
1400 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1401 &$summary, $flags & EDIT_MINOR
,
1402 null, null, &$flags ) ) )
1404 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1405 wfProfileOut( __METHOD__
);
1409 # Silently ignore EDIT_MINOR if not allowed
1410 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1411 $bot = $flags & EDIT_FORCE_BOT
;
1413 $oldtext = $this->getContent();
1414 $oldsize = strlen( $oldtext );
1416 # Provide autosummaries if one is not provided and autosummaries are enabled.
1417 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1418 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1421 $editInfo = $this->prepareTextForEdit( $text );
1422 $text = $editInfo->pst
;
1423 $newsize = strlen( $text );
1425 $dbw = wfGetDB( DB_MASTER
);
1426 $now = wfTimestampNow();
1428 if ( $flags & EDIT_UPDATE
) {
1429 # Update article, but only if changed.
1431 # Make sure the revision is either completely inserted or not inserted at all
1432 if( !$wgDBtransactions ) {
1433 $userAbort = ignore_user_abort( true );
1439 $changed = ( strcmp( $text, $oldtext ) != 0 );
1442 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1443 - (int)$this->isCountable( $oldtext );
1444 $this->mTotalAdjustment
= 0;
1446 $lastRevision = $dbw->selectField(
1447 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1449 if ( !$lastRevision ) {
1450 # Article gone missing
1451 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1452 wfProfileOut( __METHOD__
);
1456 $revision = new Revision( array(
1457 'page' => $this->getId(),
1458 'comment' => $summary,
1459 'minor_edit' => $isminor,
1461 'parent_id' => $lastRevision
1465 $revisionId = $revision->insertOn( $dbw );
1468 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1471 /* Belated edit conflict! Run away!! */
1475 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1477 # Update recentchanges
1478 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1479 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1480 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1483 # Mark as patrolled if the user can do so
1484 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1485 RecentChange
::markPatrolled( $rcid );
1486 PatrolLog
::record( $rcid, true );
1489 $wgUser->incEditCount();
1494 // Keep the same revision ID, but do some updates on it
1495 $revisionId = $this->getRevIdFetched();
1496 // Update page_touched, this is usually implicit in the page update
1497 // Other cache updates are done in onArticleEdit()
1498 $this->mTitle
->invalidateCache();
1501 if( !$wgDBtransactions ) {
1502 ignore_user_abort( $userAbort );
1506 # Invalidate cache of this article and all pages using this article
1507 # as a template. Partly deferred.
1508 Article
::onArticleEdit( $this->mTitle
);
1510 # Update links tables, site stats, etc.
1511 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1514 # Create new article
1516 # Set statistics members
1517 # We work out if it's countable after PST to avoid counter drift
1518 # when articles are created with {{subst:}}
1519 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1520 $this->mTotalAdjustment
= 1;
1524 # Add the page record; stake our claim on this title!
1525 # This will fail with a database query exception if the article already exists
1526 $newid = $this->insertOn( $dbw );
1528 # Save the revision text...
1529 $revision = new Revision( array(
1531 'comment' => $summary,
1532 'minor_edit' => $isminor,
1535 $revisionId = $revision->insertOn( $dbw );
1537 $this->mTitle
->resetArticleID( $newid );
1539 # Update the page record with revision data
1540 $this->updateRevisionOn( $dbw, $revision, 0 );
1542 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1544 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1545 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1546 '', strlen( $text ), $revisionId );
1547 # Mark as patrolled if the user can
1548 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1549 RecentChange
::markPatrolled( $rcid );
1550 PatrolLog
::record( $rcid, true );
1553 $wgUser->incEditCount();
1556 # Update links, etc.
1557 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1560 Article
::onArticleCreate( $this->mTitle
);
1562 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1563 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1566 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1571 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1572 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1575 wfProfileOut( __METHOD__
);
1580 * @deprecated wrapper for doRedirect
1582 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1583 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1587 * Output a redirect back to the article.
1588 * This is typically used after an edit.
1590 * @param boolean $noRedir Add redirect=no
1591 * @param string $sectionAnchor section to redirect to, including "#"
1592 * @param string $extraQuery, extra query params
1594 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1597 $query = 'redirect=no';
1599 $query .= "&$query";
1601 $query = $extraQuery;
1603 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1607 * Mark this particular edit/page as patrolled
1609 function markpatrolled() {
1610 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1611 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1613 # Check patrol config options
1615 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1616 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1620 # If we haven't been given an rc_id value, we can't do anything
1621 $rcid = (int) $wgRequest->getVal('rcid');
1622 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1623 if ( is_null ( $rc ) )
1625 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1629 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1630 // Only new pages can be patrolled if the general patrolling is off....???
1631 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1633 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1638 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1640 if (count($permission_errors)>0)
1642 $wgOut->showPermissionsErrorPage( $permission_errors );
1646 # Handle the 'MarkPatrolled' hook
1647 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1651 #It would be nice to see where the user had actually come from, but for now just guess
1652 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1653 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1655 # If it's left up to us, check that the user is allowed to patrol this edit
1656 # If the user has the "autopatrol" right, then we'll assume there are no
1657 # other conditions stopping them doing so
1658 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1659 $rc = RecentChange
::newFromId( $rcid );
1660 # Graceful error handling, as we've done before here...
1661 # (If the recent change doesn't exist, then it doesn't matter whether
1662 # the user is allowed to patrol it or not; nothing is going to happen
1663 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1664 # The user made this edit, and can't patrol it
1665 # Tell them so, and then back off
1666 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1667 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1668 $wgOut->returnToMain( false, $return );
1673 # Check that the revision isn't patrolled already
1674 # Prevents duplicate log entries
1675 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1676 # Mark the edit as patrolled
1677 RecentChange
::markPatrolled( $rcid );
1678 PatrolLog
::record( $rcid );
1679 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1683 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1684 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1685 $wgOut->returnToMain( false, $return );
1689 * User-interface handler for the "watch" action
1694 global $wgUser, $wgOut;
1696 if ( $wgUser->isAnon() ) {
1697 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1700 if ( wfReadOnly() ) {
1701 $wgOut->readOnlyPage();
1705 if( $this->doWatch() ) {
1706 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1707 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1709 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1712 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1716 * Add this page to $wgUser's watchlist
1717 * @return bool true on successful watch operation
1719 function doWatch() {
1721 if( $wgUser->isAnon() ) {
1725 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1726 $wgUser->addWatch( $this->mTitle
);
1728 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1735 * User interface handler for the "unwatch" action.
1737 function unwatch() {
1739 global $wgUser, $wgOut;
1741 if ( $wgUser->isAnon() ) {
1742 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1745 if ( wfReadOnly() ) {
1746 $wgOut->readOnlyPage();
1750 if( $this->doUnwatch() ) {
1751 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1752 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1754 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1757 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1761 * Stop watching a page
1762 * @return bool true on successful unwatch
1764 function doUnwatch() {
1766 if( $wgUser->isAnon() ) {
1770 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1771 $wgUser->removeWatch( $this->mTitle
);
1773 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1780 * action=protect handler
1782 function protect() {
1783 $form = new ProtectionForm( $this );
1788 * action=unprotect handler (alias)
1790 function unprotect() {
1795 * Update the article's restriction field, and leave a log entry.
1797 * @param array $limit set of restriction keys
1798 * @param string $reason
1799 * @return bool true on success
1801 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1802 global $wgUser, $wgRestrictionTypes, $wgContLang;
1804 $id = $this->mTitle
->getArticleID();
1805 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1813 // Take this opportunity to purge out expired restrictions
1814 Title
::purgeExpiredRestrictions();
1816 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1817 # we expect a single selection, but the schema allows otherwise.
1819 foreach( $wgRestrictionTypes as $action )
1820 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1822 $current = Article
::flattenRestrictions( $current );
1823 $updated = Article
::flattenRestrictions( $limit );
1825 $changed = ( $current != $updated );
1826 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1827 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1828 $protect = ( $updated != '' );
1830 # If nothing's changed, do nothing
1832 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1834 $dbw = wfGetDB( DB_MASTER
);
1836 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1838 $expiry_description = '';
1839 if ( $encodedExpiry != 'infinity' ) {
1840 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1843 # Prepare a null revision to be added to the history
1844 $modified = $current != '' && $protect;
1846 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1848 $comment_type = 'unprotectedarticle';
1850 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1852 # Only restrictions with the 'protect' right can cascade...
1853 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1854 foreach( $limit as $action => $restriction ) {
1855 # FIXME: can $restriction be an array or what? (same as fixme above)
1856 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1862 $cascade_description = '';
1864 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1868 $comment .= ": $reason";
1870 $comment .= " [$updated]";
1871 if ( $expiry_description && $protect )
1872 $comment .= "$expiry_description";
1874 $comment .= "$cascade_description";
1876 # Update restrictions table
1877 foreach( $limit as $action => $restrictions ) {
1878 if ($restrictions != '' ) {
1879 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1880 array( 'pr_page' => $id, 'pr_type' => $action
1881 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1882 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1884 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1885 'pr_type' => $action ), __METHOD__
);
1889 # Insert a null revision
1890 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1891 $nullRevId = $nullRevision->insertOn( $dbw );
1893 $latest = $this->getLatest();
1894 # Update page record
1895 $dbw->update( 'page',
1897 'page_touched' => $dbw->timestamp(),
1898 'page_restrictions' => '',
1899 'page_latest' => $nullRevId
1900 ), array( /* WHERE */
1902 ), 'Article::protect'
1905 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest) );
1906 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1908 # Update the protection log
1909 $log = new LogPage( 'protect' );
1911 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
,
1912 trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1914 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1918 } # End "changed" check
1924 * Take an array of page restrictions and flatten it to a string
1925 * suitable for insertion into the page_restrictions field.
1926 * @param array $limit
1930 function flattenRestrictions( $limit ) {
1931 if( !is_array( $limit ) ) {
1932 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1936 foreach( $limit as $action => $restrictions ) {
1937 if( $restrictions != '' ) {
1938 $bits[] = "$action=$restrictions";
1941 return implode( ':', $bits );
1945 * Auto-generates a deletion reason
1946 * @param bool &$hasHistory Whether the page has a history
1948 public function generateReason(&$hasHistory)
1951 $dbw = wfGetDB(DB_MASTER
);
1952 // Get the last revision
1953 $rev = Revision
::newFromTitle($this->mTitle
);
1956 // Get the article's contents
1957 $contents = $rev->getText();
1959 // If the page is blank, use the text from the previous revision,
1960 // which can only be blank if there's a move/import/protect dummy revision involved
1963 $prev = $rev->getPrevious();
1966 $contents = $prev->getText();
1971 // Find out if there was only one contributor
1972 // Only scan the last 20 revisions
1974 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1975 array('LIMIT' => $limit));
1977 // This page has no revisions, which is very weird
1979 if($res->numRows() > 1)
1982 $hasHistory = false;
1983 $row = $dbw->fetchObject($res);
1984 $onlyAuthor = $row->rev_user_text
;
1985 // Try to find a second contributor
1986 foreach( $res as $row ) {
1987 if($row->rev_user_text
!= $onlyAuthor) {
1988 $onlyAuthor = false;
1992 $dbw->freeResult($res);
1994 // Generate the summary with a '$1' placeholder
1996 // The current revision is blank and the one before is also
1997 // blank. It's just not our lucky day
1998 $reason = wfMsgForContent('exbeforeblank', '$1');
2001 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
2003 $reason = wfMsgForContent('excontent', '$1');
2006 // Replace newlines with spaces to prevent uglyness
2007 $contents = preg_replace("/[\n\r]/", ' ', $contents);
2008 // Calculate the maximum amount of chars to get
2009 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2010 $maxLength = 255 - (strlen($reason) - 2) - 3;
2011 $contents = $wgContLang->truncate($contents, $maxLength, '...');
2012 // Remove possible unfinished links
2013 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2014 // Now replace the '$1' placeholder
2015 $reason = str_replace( '$1', $contents, $reason );
2021 * UI entry point for page deletion
2024 global $wgUser, $wgOut, $wgRequest;
2026 $confirm = $wgRequest->wasPosted() &&
2027 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2029 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2030 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2032 $reason = $this->DeleteReasonList
;
2034 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2035 // Entry from drop down menu + additional comment
2036 $reason .= ': ' . $this->DeleteReason
;
2037 } elseif ( $reason == 'other' ) {
2038 $reason = $this->DeleteReason
;
2040 # Flag to hide all contents of the archived revisions
2041 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2043 # This code desperately needs to be totally rewritten
2045 # Read-only check...
2046 if ( wfReadOnly() ) {
2047 $wgOut->readOnlyPage();
2052 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2054 if (count($permission_errors)>0) {
2055 $wgOut->showPermissionsErrorPage( $permission_errors );
2059 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2061 # Better double-check that it hasn't been deleted yet!
2062 $dbw = wfGetDB( DB_MASTER
);
2063 $conds = $this->mTitle
->pageCond();
2064 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2065 if ( $latest === false ) {
2066 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2070 # Hack for big sites
2071 $bigHistory = $this->isBigDeletion();
2072 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2073 global $wgLang, $wgDeleteRevisionsLimit;
2074 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2075 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2080 $this->doDelete( $reason, $suppress );
2081 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2083 } elseif( $this->mTitle
->userIsWatching() ) {
2089 // Generate deletion reason
2090 $hasHistory = false;
2091 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2093 // If the page has a history, insert a warning
2094 if( $hasHistory && !$confirm ) {
2095 $skin=$wgUser->getSkin();
2096 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2098 global $wgLang, $wgDeleteRevisionsLimit;
2099 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2100 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2104 return $this->confirmDelete( $reason );
2108 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2110 function isBigDeletion() {
2111 global $wgDeleteRevisionsLimit;
2112 if( $wgDeleteRevisionsLimit ) {
2113 $revCount = $this->estimateRevisionCount();
2114 return $revCount > $wgDeleteRevisionsLimit;
2120 * @return int approximate revision count
2122 function estimateRevisionCount() {
2124 // For an exact count...
2125 //return $dbr->selectField( 'revision', 'COUNT(*)',
2126 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2127 return $dbr->estimateRowCount( 'revision', '*',
2128 array( 'rev_page' => $this->getId() ), __METHOD__
);
2132 * Get the last N authors
2133 * @param int $num Number of revisions to get
2134 * @param string $revLatest The latest rev_id, selected from the master (optional)
2135 * @return array Array of authors, duplicates not removed
2137 function getLastNAuthors( $num, $revLatest = 0 ) {
2138 wfProfileIn( __METHOD__
);
2140 // First try the slave
2141 // If that doesn't have the latest revision, try the master
2143 $db = wfGetDB( DB_SLAVE
);
2145 $res = $db->select( array( 'page', 'revision' ),
2146 array( 'rev_id', 'rev_user_text' ),
2148 'page_namespace' => $this->mTitle
->getNamespace(),
2149 'page_title' => $this->mTitle
->getDBkey(),
2150 'rev_page = page_id'
2151 ), __METHOD__
, $this->getSelectOptions( array(
2152 'ORDER BY' => 'rev_timestamp DESC',
2157 wfProfileOut( __METHOD__
);
2160 $row = $db->fetchObject( $res );
2161 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2162 $db = wfGetDB( DB_MASTER
);
2167 } while ( $continue );
2169 $authors = array( $row->rev_user_text
);
2170 while ( $row = $db->fetchObject( $res ) ) {
2171 $authors[] = $row->rev_user_text
;
2173 wfProfileOut( __METHOD__
);
2178 * Output deletion confirmation dialog
2179 * @param $reason string Prefilled reason
2181 function confirmDelete( $reason ) {
2182 global $wgOut, $wgUser, $wgContLang;
2183 $align = $wgContLang->isRtl() ?
'left' : 'right';
2185 wfDebug( "Article::confirmDelete\n" );
2187 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2188 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2189 $wgOut->addWikiMsg( 'confirmdeletetext' );
2191 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2192 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2193 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2194 $suppress .= "</td></tr>";
2199 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2200 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2201 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2202 Xml
::openElement( 'table' ) .
2203 "<tr id=\"wpDeleteReasonListRow\">
2204 <td align='$align'>" .
2205 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2208 Xml
::listDropDown( 'wpDeleteReasonList',
2209 wfMsgForContent( 'deletereason-dropdown' ),
2210 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2213 <tr id=\"wpDeleteReasonRow\">
2214 <td align='$align'>" .
2215 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2218 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2224 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2231 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2234 Xml
::closeElement( 'table' ) .
2235 Xml
::closeElement( 'fieldset' ) .
2236 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2237 Xml
::closeElement( 'form' );
2239 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2240 $skin = $wgUser->getSkin();
2241 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2242 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2245 $wgOut->addHTML( $form );
2246 $this->showLogExtract( $wgOut );
2251 * Show relevant lines from the deletion log
2253 function showLogExtract( $out ) {
2254 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2255 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2260 * Perform a deletion and output success or failure messages
2262 function doDelete( $reason, $suppress = false ) {
2263 global $wgOut, $wgUser;
2264 wfDebug( __METHOD__
."\n" );
2266 $id = $this->getId();
2270 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error))) {
2271 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2272 $deleted = $this->mTitle
->getPrefixedText();
2274 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2275 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2277 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2279 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2280 $wgOut->returnToMain( false );
2281 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2284 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2286 $wgOut->showFatalError( $error );
2292 * Back-end article deletion
2293 * Deletes the article with database consistency, writes logs, purges caches
2296 function doDeleteArticle( $reason, $suppress = false ) {
2297 global $wgUseSquid, $wgDeferredUpdateList;
2298 global $wgUseTrackbacks;
2300 wfDebug( __METHOD__
."\n" );
2302 $dbw = wfGetDB( DB_MASTER
);
2303 $ns = $this->mTitle
->getNamespace();
2304 $t = $this->mTitle
->getDBkey();
2305 $id = $this->mTitle
->getArticleID();
2307 if ( $t == '' ||
$id == 0 ) {
2311 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2312 array_push( $wgDeferredUpdateList, $u );
2314 // Bitfields to further suppress the content
2317 // This should be 15...
2318 $bitfield |
= Revision
::DELETED_TEXT
;
2319 $bitfield |
= Revision
::DELETED_COMMENT
;
2320 $bitfield |
= Revision
::DELETED_USER
;
2321 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2323 $bitfield = 'rev_deleted';
2327 // For now, shunt the revision data into the archive table.
2328 // Text is *not* removed from the text table; bulk storage
2329 // is left intact to avoid breaking block-compression or
2330 // immutable storage schemes.
2332 // For backwards compatibility, note that some older archive
2333 // table entries will have ar_text and ar_flags fields still.
2335 // In the future, we may keep revisions and mark them with
2336 // the rev_deleted field, which is reserved for this purpose.
2337 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2339 'ar_namespace' => 'page_namespace',
2340 'ar_title' => 'page_title',
2341 'ar_comment' => 'rev_comment',
2342 'ar_user' => 'rev_user',
2343 'ar_user_text' => 'rev_user_text',
2344 'ar_timestamp' => 'rev_timestamp',
2345 'ar_minor_edit' => 'rev_minor_edit',
2346 'ar_rev_id' => 'rev_id',
2347 'ar_text_id' => 'rev_text_id',
2348 'ar_text' => '\'\'', // Be explicit to appease
2349 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2350 'ar_len' => 'rev_len',
2351 'ar_page_id' => 'page_id',
2352 'ar_deleted' => $bitfield
2355 'page_id = rev_page'
2359 # Delete restrictions for it
2360 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2362 # Fix category table counts
2364 $res = $dbw->select( 'categorylinks', 'cl_to',
2365 array( 'cl_from' => $id ), __METHOD__
);
2366 foreach( $res as $row ) {
2367 $cats []= $row->cl_to
;
2369 $this->updateCategoryCounts( array(), $cats );
2371 # Now that it's safely backed up, delete it
2372 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2373 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2379 # If using cascading deletes, we can skip some explicit deletes
2380 if ( !$dbw->cascadingDeletes() ) {
2381 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2383 if ($wgUseTrackbacks)
2384 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2386 # Delete outgoing links
2387 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2388 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2389 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2390 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2391 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2392 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2393 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2396 # If using cleanup triggers, we can skip some manual deletes
2397 if ( !$dbw->cleanupTriggers() ) {
2399 # Clean up recentchanges entries...
2400 $dbw->delete( 'recentchanges',
2401 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2407 Article
::onArticleDelete( $this->mTitle
);
2409 # Clear the cached article id so the interface doesn't act like we exist
2410 $this->mTitle
->resetArticleID( 0 );
2411 $this->mTitle
->mArticleID
= 0;
2413 # Log the deletion, if the page was suppressed, log it at Oversight instead
2414 $logtype = $suppress ?
'suppress' : 'delete';
2415 $log = new LogPage( $logtype );
2417 # Make sure logging got through
2418 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2424 * Roll back the most recent consecutive set of edits to a page
2425 * from the same user; fails if there are no eligible edits to
2426 * roll back to, e.g. user is the sole contributor. This function
2427 * performs permissions checks on $wgUser, then calls commitRollback()
2428 * to do the dirty work
2430 * @param string $fromP - Name of the user whose edits to rollback.
2431 * @param string $summary - Custom summary. Set to default summary if empty.
2432 * @param string $token - Rollback token.
2433 * @param bool $bot - If true, mark all reverted edits as bot.
2435 * @param array $resultDetails contains result-specific array of additional values
2436 * 'alreadyrolled' : 'current' (rev)
2437 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2439 * @return array of errors, each error formatted as
2440 * array(messagekey, param1, param2, ...).
2441 * On success, the array is empty. This array can also be passed to
2442 * OutputPage::showPermissionsErrorPage().
2444 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2446 $resultDetails = null;
2449 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2450 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2451 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2452 $errors[] = array( 'sessionfailure' );
2454 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2455 $errors[] = array( 'actionthrottledtext' );
2457 # If there were errors, bail out now
2461 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2465 * Backend implementation of doRollback(), please refer there for parameter
2466 * and return value documentation
2468 * NOTE: This function does NOT check ANY permissions, it just commits the
2469 * rollback to the DB Therefore, you should only call this function direct-
2470 * ly if you want to use custom permissions checks. If you don't, use
2471 * doRollback() instead.
2473 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2474 global $wgUseRCPatrol, $wgUser, $wgLang;
2475 $dbw = wfGetDB( DB_MASTER
);
2477 if( wfReadOnly() ) {
2478 return array( array( 'readonlytext' ) );
2481 # Get the last editor
2482 $current = Revision
::newFromTitle( $this->mTitle
);
2483 if( is_null( $current ) ) {
2484 # Something wrong... no page?
2485 return array(array('notanarticle'));
2488 $from = str_replace( '_', ' ', $fromP );
2489 if( $from != $current->getUserText() ) {
2490 $resultDetails = array( 'current' => $current );
2491 return array(array('alreadyrolled',
2492 htmlspecialchars($this->mTitle
->getPrefixedText()),
2493 htmlspecialchars($fromP),
2494 htmlspecialchars($current->getUserText())
2498 # Get the last edit not by this guy
2499 $user = intval( $current->getUser() );
2500 $user_text = $dbw->addQuotes( $current->getUserText() );
2501 $s = $dbw->selectRow( 'revision',
2502 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2503 array( 'rev_page' => $current->getPage(),
2504 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2506 array( 'USE INDEX' => 'page_timestamp',
2507 'ORDER BY' => 'rev_timestamp DESC' )
2509 if( $s === false ) {
2510 # No one else ever edited this page
2511 return array(array('cantrollback'));
2512 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2513 # Only admins can see this text
2514 return array(array('notvisiblerev'));
2518 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2519 # Mark all reverted edits as bot
2522 if ( $wgUseRCPatrol ) {
2523 # Mark all reverted edits as patrolled
2524 $set['rc_patrolled'] = 1;
2528 $dbw->update( 'recentchanges', $set,
2530 'rc_cur_id' => $current->getPage(),
2531 'rc_user_text' => $current->getUserText(),
2532 "rc_timestamp > '{$s->rev_timestamp}'",
2537 # Generate the edit summary if necessary
2538 $target = Revision
::newFromId( $s->rev_id
);
2539 if( empty( $summary ) ){
2540 $summary = wfMsgForContent( 'revertpage' );
2543 # Allow the custom summary to use the same args as the default message
2545 $target->getUserText(), $from, $s->rev_id
,
2546 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2547 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2549 $summary = wfMsgReplaceArgs( $summary, $args );
2552 $flags = EDIT_UPDATE
;
2554 if ($wgUser->isAllowed('minoredit'))
2555 $flags |
= EDIT_MINOR
;
2557 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2558 $flags |
= EDIT_FORCE_BOT
;
2559 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2561 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2563 $resultDetails = array(
2564 'summary' => $summary,
2565 'current' => $current,
2566 'target' => $target,
2572 * User interface for rollback operations
2574 function rollback() {
2575 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2578 $result = $this->doRollback(
2579 $wgRequest->getVal( 'from' ),
2580 $wgRequest->getText( 'summary' ),
2581 $wgRequest->getVal( 'token' ),
2582 $wgRequest->getBool( 'bot' ),
2586 if( in_array( array( 'blocked' ), $result ) ) {
2587 $wgOut->blockedPage();
2590 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2591 $wgOut->rateLimited();
2594 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2595 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2596 $errArray = $result[0];
2597 $errMsg = array_shift( $errArray );
2598 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2599 if( isset( $details['current'] ) ){
2600 $current = $details['current'];
2601 if( $current->getComment() != '' ) {
2602 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2607 # Display permissions errors before read-only message -- there's no
2608 # point in misleading the user into thinking the inability to rollback
2609 # is only temporary.
2610 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2611 # array_diff is completely broken for arrays of arrays, sigh. Re-
2612 # move any 'readonlytext' error manually.
2614 foreach( $result as $error ) {
2615 if( $error != array( 'readonlytext' ) ) {
2619 $wgOut->showPermissionsErrorPage( $out );
2622 if( $result == array( array('readonlytext') ) ) {
2623 $wgOut->readOnlyPage();
2627 $current = $details['current'];
2628 $target = $details['target'];
2629 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2630 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2631 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2632 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2633 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2634 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2635 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2636 $wgOut->returnToMain( false, $this->mTitle
);
2638 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2639 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), 'next', false, true );
2640 $de->showDiff( '', '' );
2646 * Do standard deferred updates after page view
2649 function viewUpdates() {
2650 global $wgDeferredUpdateList, $wgUser;
2652 if ( 0 != $this->getID() ) {
2653 # Don't update page view counters on views from bot users (bug 14044)
2654 global $wgDisableCounters;
2655 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2656 Article
::incViewCount( $this->getID() );
2657 $u = new SiteStatsUpdate( 1, 0, 0 );
2658 array_push( $wgDeferredUpdateList, $u );
2662 # Update newtalk / watchlist notification status
2663 $wgUser->clearNotification( $this->mTitle
);
2667 * Prepare text which is about to be saved.
2668 * Returns a stdclass with source, pst and output members
2670 function prepareTextForEdit( $text, $revid=null ) {
2671 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2673 return $this->mPreparedEdit
;
2676 $edit = (object)array();
2677 $edit->revid
= $revid;
2678 $edit->newText
= $text;
2679 $edit->pst
= $this->preSaveTransform( $text );
2680 $options = new ParserOptions
;
2681 $options->setTidy( true );
2682 $options->enableLimitReport();
2683 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2684 $edit->oldText
= $this->getContent();
2685 $this->mPreparedEdit
= $edit;
2690 * Do standard deferred updates after page edit.
2691 * Update links tables, site stats, search index and message cache.
2692 * Every 100th edit, prune the recent changes table.
2695 * @param $text New text of the article
2696 * @param $summary Edit summary
2697 * @param $minoredit Minor edit
2698 * @param $timestamp_of_pagechange Timestamp associated with the page change
2699 * @param $newid rev_id value of the new revision
2700 * @param $changed Whether or not the content actually changed
2702 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2703 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2705 wfProfileIn( __METHOD__
);
2708 # Be careful not to double-PST: $text is usually already PST-ed once
2709 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2710 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2711 $editInfo = $this->prepareTextForEdit( $text, $newid );
2713 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2714 $editInfo = $this->mPreparedEdit
;
2717 # Save it to the parser cache
2718 if ( $wgEnableParserCache ) {
2719 $parserCache = ParserCache
::singleton();
2720 $parserCache->save( $editInfo->output
, $this, $wgUser );
2723 # Update the links tables
2724 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2727 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2728 if ( 0 == mt_rand( 0, 99 ) ) {
2729 // Flush old entries from the `recentchanges` table; we do this on
2730 // random requests so as to avoid an increase in writes for no good reason
2732 $dbw = wfGetDB( DB_MASTER
);
2733 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2734 $recentchanges = $dbw->tableName( 'recentchanges' );
2735 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2736 $dbw->query( $sql );
2740 $id = $this->getID();
2741 $title = $this->mTitle
->getPrefixedDBkey();
2742 $shortTitle = $this->mTitle
->getDBkey();
2745 wfProfileOut( __METHOD__
);
2749 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2750 array_push( $wgDeferredUpdateList, $u );
2751 $u = new SearchUpdate( $id, $title, $text );
2752 array_push( $wgDeferredUpdateList, $u );
2754 # If this is another user's talk page, update newtalk
2755 # Don't do this if $changed = false otherwise some idiot can null-edit a
2756 # load of user talk pages and piss people off, nor if it's a minor edit
2757 # by a properly-flagged bot.
2758 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2759 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2760 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2761 $other = User
::newFromName( $shortTitle );
2762 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2763 // An anonymous user
2764 $other = new User();
2765 $other->setName( $shortTitle );
2768 $other->setNewtalk( true );
2773 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2774 $wgMessageCache->replace( $shortTitle, $text );
2777 wfProfileOut( __METHOD__
);
2781 * Perform article updates on a special page creation.
2783 * @param Revision $rev
2785 * @todo This is a shitty interface function. Kill it and replace the
2786 * other shitty functions like editUpdates and such so it's not needed
2789 function createUpdates( $rev ) {
2790 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2791 $this->mTotalAdjustment
= 1;
2792 $this->editUpdates( $rev->getText(), $rev->getComment(),
2793 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2797 * Generate the navigation links when browsing through an article revisions
2798 * It shows the information as:
2799 * Revision as of \<date\>; view current revision
2800 * \<- Previous version | Next Version -\>
2803 * @param string $oldid Revision ID of this article revision
2805 function setOldSubtitle( $oldid=0 ) {
2806 global $wgLang, $wgOut, $wgUser;
2808 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2812 $revision = Revision
::newFromId( $oldid );
2814 $current = ( $oldid == $this->mLatest
);
2815 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2816 $sk = $wgUser->getSkin();
2818 ?
wfMsg( 'currentrevisionlink' )
2819 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2822 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2823 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2825 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2826 : wfMsg( 'previousrevision' );
2828 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2830 $nextlink = $current
2831 ?
wfMsg( 'nextrevision' )
2832 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2833 $nextdiff = $current
2835 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2838 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2839 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2840 if( $revision->isCurrent() ) {
2841 // We don't handle top deleted edits too well
2842 $cdel = wfMsgHtml('rev-delundel');
2843 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2844 // If revision was hidden from sysops
2845 $cdel = wfMsgHtml('rev-delundel');
2847 $cdel = $sk->makeKnownLinkObj( $revdel,
2848 wfMsgHtml('rev-delundel'),
2849 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2850 '&oldid=' . urlencode( $oldid ) );
2851 // Bolden oversighted content
2852 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2853 $cdel = "<strong>$cdel</strong>";
2855 $cdel = "(<small>$cdel</small>) ";
2857 # Show user links if allowed to see them. Normally they
2858 # are hidden regardless, but since we can already see the text here...
2859 $userlinks = $sk->revUserTools( $revision, false );
2861 $m = wfMsg( 'revision-info-current' );
2862 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2863 ?
'revision-info-current'
2866 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2868 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2869 $wgOut->setSubtitle( $r );
2873 * This function is called right before saving the wikitext,
2874 * so we can do things like signatures and links-in-context.
2876 * @param string $text
2878 function preSaveTransform( $text ) {
2879 global $wgParser, $wgUser;
2880 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2883 /* Caching functions */
2886 * checkLastModified returns true if it has taken care of all
2887 * output to the client that is necessary for this request.
2888 * (that is, it has sent a cached version of the page)
2890 function tryFileCache() {
2891 static $called = false;
2893 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2897 if($this->isFileCacheable()) {
2898 $touched = $this->mTouched
;
2899 $cache = new HTMLFileCache( $this->mTitle
);
2900 if($cache->isFileCacheGood( $touched )) {
2901 wfDebug( "Article::tryFileCache(): about to load file\n" );
2902 $cache->loadFromFileCache();
2905 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2906 ob_start( array(&$cache, 'saveToFileCache' ) );
2909 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2914 * Check if the page can be cached
2917 function isFileCacheable() {
2918 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2919 $action = $wgRequest->getVal( 'action' );
2920 $oldid = $wgRequest->getVal( 'oldid' );
2921 $diff = $wgRequest->getVal( 'diff' );
2922 $redirect = $wgRequest->getVal( 'redirect' );
2923 $printable = $wgRequest->getVal( 'printable' );
2924 $page = $wgRequest->getVal( 'page' );
2926 //check for non-standard user language; this covers uselang,
2927 //and extensions for auto-detecting user language.
2928 $ulang = $wgLang->getCode();
2929 $clang = $wgContLang->getCode();
2931 $cacheable = $wgUseFileCache
2932 && (!$wgShowIPinHeader)
2933 && ($this->getID() != 0)
2934 && ($wgUser->isAnon())
2935 && (!$wgUser->getNewtalk())
2936 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2937 && (empty( $action ) ||
$action == 'view')
2940 && (!isset($redirect))
2941 && (!isset($printable))
2943 && (!$this->mRedirectedFrom
)
2944 && ($ulang === $clang);
2947 //extension may have reason to disable file caching on some pages.
2948 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2955 * Loads page_touched and returns a value indicating if it should be used
2958 function checkTouched() {
2959 if( !$this->mDataLoaded
) {
2960 $this->loadPageData();
2962 return !$this->mIsRedirect
;
2966 * Get the page_touched field
2968 function getTouched() {
2969 # Ensure that page data has been loaded
2970 if( !$this->mDataLoaded
) {
2971 $this->loadPageData();
2973 return $this->mTouched
;
2977 * Get the page_latest field
2979 function getLatest() {
2980 if ( !$this->mDataLoaded
) {
2981 $this->loadPageData();
2983 return $this->mLatest
;
2987 * Edit an article without doing all that other stuff
2988 * The article must already exist; link tables etc
2989 * are not updated, caches are not flushed.
2991 * @param string $text text submitted
2992 * @param string $comment comment submitted
2993 * @param bool $minor whereas it's a minor modification
2995 function quickEdit( $text, $comment = '', $minor = 0 ) {
2996 wfProfileIn( __METHOD__
);
2998 $dbw = wfGetDB( DB_MASTER
);
3000 $revision = new Revision( array(
3001 'page' => $this->getId(),
3003 'comment' => $comment,
3004 'minor_edit' => $minor ?
1 : 0,
3006 $revision->insertOn( $dbw );
3007 $this->updateRevisionOn( $dbw, $revision );
3010 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3012 wfProfileOut( __METHOD__
);
3016 * Used to increment the view counter
3019 * @param integer $id article id
3021 function incViewCount( $id ) {
3022 $id = intval( $id );
3023 global $wgHitcounterUpdateFreq, $wgDBtype;
3025 $dbw = wfGetDB( DB_MASTER
);
3026 $pageTable = $dbw->tableName( 'page' );
3027 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3028 $acchitsTable = $dbw->tableName( 'acchits' );
3030 if( $wgHitcounterUpdateFreq <= 1 ) {
3031 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3035 # Not important enough to warrant an error page in case of failure
3036 $oldignore = $dbw->ignoreErrors( true );
3038 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3040 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3041 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3042 # Most of the time (or on SQL errors), skip row count check
3043 $dbw->ignoreErrors( $oldignore );
3047 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3048 $row = $dbw->fetchObject( $res );
3049 $rown = intval( $row->n
);
3050 if( $rown >= $wgHitcounterUpdateFreq ){
3051 wfProfileIn( 'Article::incViewCount-collect' );
3052 $old_user_abort = ignore_user_abort( true );
3054 if ($wgDBtype == 'mysql')
3055 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3056 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3057 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3058 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3060 $dbw->query("DELETE FROM $hitcounterTable");
3061 if ($wgDBtype == 'mysql') {
3062 $dbw->query('UNLOCK TABLES');
3063 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3064 'WHERE page_id = hc_id');
3067 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3068 "FROM $acchitsTable WHERE page_id = hc_id");
3070 $dbw->query("DROP TABLE $acchitsTable");
3072 ignore_user_abort( $old_user_abort );
3073 wfProfileOut( 'Article::incViewCount-collect' );
3075 $dbw->ignoreErrors( $oldignore );
3079 * The onArticle*() functions are supposed to be a kind of hooks
3080 * which should be called whenever any of the specified actions
3083 * This is a good place to put code to clear caches, for instance.
3085 * This is called on page move and undelete, as well as edit
3087 * @param $title_obj a title object
3090 static function onArticleCreate($title) {
3091 # The talk page isn't in the regular link tables, so we need to update manually:
3092 if ( $title->isTalkPage() ) {
3093 $other = $title->getSubjectPage();
3095 $other = $title->getTalkPage();
3097 $other->invalidateCache();
3098 $other->purgeSquid();
3100 $title->touchLinks();
3101 $title->purgeSquid();
3102 $title->deleteTitleProtection();
3105 static function onArticleDelete( $title ) {
3106 global $wgUseFileCache, $wgMessageCache;
3108 // Update existence markers on article/talk tabs...
3109 if( $title->isTalkPage() ) {
3110 $other = $title->getSubjectPage();
3112 $other = $title->getTalkPage();
3114 $other->invalidateCache();
3115 $other->purgeSquid();
3117 $title->touchLinks();
3118 $title->purgeSquid();
3121 if ( $wgUseFileCache ) {
3122 $cm = new HTMLFileCache( $title );
3123 @unlink
( $cm->fileCacheName() );
3127 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3128 $wgMessageCache->replace( $title->getDBkey(), false );
3131 if( $title->getNamespace() == NS_IMAGE
) {
3132 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3133 $update->doUpdate();
3136 if( $title->getNamespace() == NS_USER_TALK
) {
3137 $user = User
::newFromName( $title->getText(), false );
3138 $user->setNewtalk( false );
3143 * Purge caches on page update etc
3145 static function onArticleEdit( $title ) {
3146 global $wgDeferredUpdateList, $wgUseFileCache;
3148 // Invalidate caches of articles which include this page
3149 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3151 // Invalidate the caches of all pages which redirect here
3152 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3154 # Purge squid for this page only
3155 $title->purgeSquid();
3158 if ( $wgUseFileCache ) {
3159 $cm = new HTMLFileCache( $title );
3160 @unlink
( $cm->fileCacheName() );
3167 * Overriden by ImagePage class, only present here to avoid a fatal error
3168 * Called for ?action=revert
3170 public function revert(){
3172 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3176 * Info about this page
3177 * Called for ?action=info when $wgAllowPageInfo is on.
3182 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3184 if ( !$wgAllowPageInfo ) {
3185 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3189 $page = $this->mTitle
->getSubjectPage();
3191 $wgOut->setPagetitle( $page->getPrefixedText() );
3192 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3193 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3195 if( !$this->mTitle
->exists() ) {
3196 $wgOut->addHtml( '<div class="noarticletext">' );
3197 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3198 // This doesn't quite make sense; the user is asking for
3199 // information about the _page_, not the message... -- RC
3200 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3202 $msg = $wgUser->isLoggedIn()
3204 : 'noarticletextanon';
3205 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3207 $wgOut->addHtml( '</div>' );
3209 $dbr = wfGetDB( DB_SLAVE
);
3211 'wl_title' => $page->getDBkey(),
3212 'wl_namespace' => $page->getNamespace() );
3213 $numwatchers = $dbr->selectField(
3218 $this->getSelectOptions() );
3220 $pageInfo = $this->pageCountInfo( $page );
3221 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3223 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3224 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3226 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3228 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3230 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3232 $wgOut->addHTML( '</ul>' );
3238 * Return the total number of edits and number of unique editors
3239 * on a given page. If page does not exist, returns false.
3241 * @param Title $title
3245 function pageCountInfo( $title ) {
3246 $id = $title->getArticleId();
3251 $dbr = wfGetDB( DB_SLAVE
);
3253 $rev_clause = array( 'rev_page' => $id );
3255 $edits = $dbr->selectField(
3260 $this->getSelectOptions() );
3262 $authors = $dbr->selectField(
3264 'COUNT(DISTINCT rev_user_text)',
3267 $this->getSelectOptions() );
3269 return array( 'edits' => $edits, 'authors' => $authors );
3273 * Return a list of templates used by this article.
3274 * Uses the templatelinks table
3276 * @return array Array of Title objects
3278 function getUsedTemplates() {
3280 $id = $this->mTitle
->getArticleID();
3285 $dbr = wfGetDB( DB_SLAVE
);
3286 $res = $dbr->select( array( 'templatelinks' ),
3287 array( 'tl_namespace', 'tl_title' ),
3288 array( 'tl_from' => $id ),
3290 if( false !== $res ) {
3291 foreach( $res as $row ) {
3292 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3295 $dbr->freeResult( $res );
3300 * Returns a list of hidden categories this page is a member of.
3301 * Uses the page_props and categorylinks tables.
3303 * @return array Array of Title objects
3305 function getHiddenCategories() {
3307 $id = $this->mTitle
->getArticleID();
3312 $dbr = wfGetDB( DB_SLAVE
);
3313 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3315 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3316 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3318 if ( false !== $res ) {
3319 foreach( $res as $row ) {
3320 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3323 $dbr->freeResult( $res );
3328 * Return an applicable autosummary if one exists for the given edit.
3329 * @param string $oldtext The previous text of the page.
3330 * @param string $newtext The submitted text of the page.
3331 * @param bitmask $flags A bitmask of flags submitted for the edit.
3332 * @return string An appropriate autosummary, or an empty string.
3334 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3335 # Decide what kind of autosummary is needed.
3337 # Redirect autosummaries
3338 $rt = Title
::newFromRedirect( $newtext );
3339 if( is_object( $rt ) ) {
3340 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3343 # New page autosummaries
3344 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3345 # If they're making a new article, give its text, truncated, in the summary.
3347 $truncatedtext = $wgContLang->truncate(
3348 str_replace("\n", ' ', $newtext),
3349 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3351 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3354 # Blanking autosummaries
3355 if( $oldtext != '' && $newtext == '' ) {
3356 return wfMsgForContent('autosumm-blank');
3357 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3358 # Removing more than 90% of the article
3360 $truncatedtext = $wgContLang->truncate(
3362 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3365 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3368 # If we reach this point, there's no applicable autosummary for our case, so our
3369 # autosummary is empty.
3374 * Add the primary page-view wikitext to the output buffer
3375 * Saves the text into the parser cache if possible.
3376 * Updates templatelinks if it is out of date.
3378 * @param string $text
3379 * @param bool $cache
3381 public function outputWikiText( $text, $cache = true ) {
3382 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3384 $popts = $wgOut->parserOptions();
3385 $popts->setTidy(true);
3386 $popts->enableLimitReport();
3387 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3388 $popts, true, true, $this->getRevIdFetched() );
3389 $popts->setTidy(false);
3390 $popts->enableLimitReport( false );
3391 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3392 $parserCache = ParserCache
::singleton();
3393 $parserCache->save( $parserOutput, $this, $wgUser );
3396 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3397 // templatelinks table may have become out of sync,
3398 // especially if using variable-based transclusions.
3399 // For paranoia, check if things have changed and if
3400 // so apply updates to the database. This will ensure
3401 // that cascaded protections apply as soon as the changes
3404 # Get templates from templatelinks
3405 $id = $this->mTitle
->getArticleID();
3407 $tlTemplates = array();
3409 $dbr = wfGetDB( DB_SLAVE
);
3410 $res = $dbr->select( array( 'templatelinks' ),
3411 array( 'tl_namespace', 'tl_title' ),
3412 array( 'tl_from' => $id ),
3417 if ( false !== $res ) {
3418 foreach( $res as $row ) {
3419 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3423 # Get templates from parser output.
3424 $poTemplates_allns = $parserOutput->getTemplates();
3426 $poTemplates = array ();
3427 foreach ( $poTemplates_allns as $ns_templates ) {
3428 $poTemplates = array_merge( $poTemplates, $ns_templates );
3432 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3434 if ( count( $templates_diff ) > 0 ) {
3435 # Whee, link updates time.
3436 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3438 $dbw = wfGetDb( DB_MASTER
);
3447 $wgOut->addParserOutput( $parserOutput );
3451 * Update all the appropriate counts in the category table, given that
3452 * we've added the categories $added and deleted the categories $deleted.
3454 * @param $added array The names of categories that were added
3455 * @param $deleted array The names of categories that were deleted
3458 public function updateCategoryCounts( $added, $deleted ) {
3459 $ns = $this->mTitle
->getNamespace();
3460 $dbw = wfGetDB( DB_MASTER
);
3462 # First make sure the rows exist. If one of the "deleted" ones didn't
3463 # exist, we might legitimately not create it, but it's simpler to just
3464 # create it and then give it a negative value, since the value is bogus
3467 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3468 $insertCats = array_merge( $added, $deleted );
3469 if( !$insertCats ) {
3470 # Okay, nothing to do
3473 $insertRows = array();
3474 foreach( $insertCats as $cat ) {
3475 $insertRows[] = array( 'cat_title' => $cat );
3477 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3479 $addFields = array( 'cat_pages = cat_pages + 1' );
3480 $removeFields = array( 'cat_pages = cat_pages - 1' );
3481 if( $ns == NS_CATEGORY
) {
3482 $addFields[] = 'cat_subcats = cat_subcats + 1';
3483 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3484 } elseif( $ns == NS_IMAGE
) {
3485 $addFields[] = 'cat_files = cat_files + 1';
3486 $removeFields[] = 'cat_files = cat_files - 1';
3493 array( 'cat_title' => $added ),
3501 array( 'cat_title' => $deleted ),