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.
21 var $mContentLoaded; //!<
24 var $mGoodAdjustment; //!<
28 var $mRedirectedFrom; //!<
29 var $mRedirectUrl; //!<
30 var $mRevIdFetched; //!<
34 var $mTotalAdjustment; //!<
38 var $mRedirectTarget; //!<
43 * Constructor and clear the article
44 * @param $title Reference to a Title object.
45 * @param $oldId Integer revision ID, null to fetch from request, zero for current
47 function __construct( Title
$title, $oldId = null ) {
48 $this->mTitle
=& $title;
49 $this->mOldId
= $oldId;
54 * Tell the page view functions that this view was redirected
55 * from another page on the wiki.
56 * @param $from Title object.
58 function setRedirectedFrom( $from ) {
59 $this->mRedirectedFrom
= $from;
63 * If this page is a redirect, get its target
65 * The target will be fetched from the redirect table if possible.
66 * If this page doesn't have an entry there, call insertRedirect()
67 * @return mixed Title object, or null if this page is not a redirect
69 public function getRedirectTarget() {
70 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
72 if(!is_null($this->mRedirectTarget
))
73 return $this->mRedirectTarget
;
75 # Query the redirect table
76 $dbr = wfGetDB(DB_SLAVE
);
77 $res = $dbr->select('redirect',
78 array('rd_namespace', 'rd_title'),
79 array('rd_from' => $this->getID()),
82 $row = $dbr->fetchObject($res);
84 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
86 # This page doesn't have an entry in the redirect table
87 return $this->mRedirectTarget
= $this->insertRedirect();
91 * Insert an entry for this page into the redirect table.
93 * Don't call this function directly unless you know what you're doing.
94 * @return Title object
96 public function insertRedirect() {
97 $retval = Title
::newFromRedirect($this->getContent());
100 $dbw = wfGetDB(DB_MASTER
);
101 $dbw->replace('redirect', array('rd_from'), array(
102 'rd_from' => $this->getID(),
103 'rd_namespace' => $retval->getNamespace(),
104 'rd_title' => $retval->getDBKey()
110 * Get the Title object this page redirects to
112 * @return mixed false, Title of in-wiki target, or string with URL
114 public function followRedirect() {
115 $text = $this->getContent();
116 return self
::followRedirectText( $text );
120 * Get the Title object this text redirects to
122 * @return mixed false, Title of in-wiki target, or string with URL
124 public static function followRedirectText( $text ) {
125 $rt = Title
::newFromRedirect( $text );
126 # process if title object is valid and not special:userlogout
128 if( $rt->getInterwiki() != '' ) {
129 if( $rt->isLocal() ) {
130 // Offsite wikis need an HTTP redirect.
132 // This can be hard to reverse and may produce loops,
133 // so they may be disabled in the site configuration.
135 $source = $this->mTitle
->getFullURL( 'redirect=no' );
136 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
139 if( $rt->getNamespace() == NS_SPECIAL
) {
140 // Gotta handle redirects to special pages differently:
141 // Fill the HTTP response "Location" header and ignore
142 // the rest of the page we're on.
144 // This can be hard to reverse, so they may be disabled.
146 if( $rt->isSpecial( 'Userlogout' ) ) {
149 return $rt->getFullURL();
155 // No or invalid redirect
160 * get the title object of the article
162 function getTitle() {
163 return $this->mTitle
;
171 $this->mDataLoaded
= false;
172 $this->mContentLoaded
= false;
174 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
175 $this->mRedirectedFrom
= null; # Title object if set
176 $this->mRedirectTarget
= null; # Title object if set
178 $this->mTimestamp
= $this->mComment
= '';
179 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
180 $this->mTouched
= '19700101000000';
181 $this->mForUpdate
= false;
182 $this->mIsRedirect
= false;
183 $this->mRevIdFetched
= 0;
184 $this->mRedirectUrl
= false;
185 $this->mLatest
= false;
186 $this->mPreparedEdit
= false;
190 * Note that getContent/loadContent do not follow redirects anymore.
191 * If you need to fetch redirectable content easily, try
192 * the shortcut in Article::followContent()
194 * @todo There are still side-effects in this!
195 * In general, you should use the Revision class, not Article,
196 * to fetch text for purposes other than page views.
198 * @return Return the text of this revision
200 function getContent() {
201 global $wgUser, $wgOut, $wgMessageCache;
203 wfProfileIn( __METHOD__
);
205 if ( 0 == $this->getID() ) {
206 wfProfileOut( __METHOD__
);
207 $wgOut->setRobotpolicy( 'noindex,nofollow' );
209 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
210 $wgMessageCache->loadAllMessages();
211 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
213 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
216 return "<div class='noarticletext'>\n$ret\n</div>";
218 $this->loadContent();
219 wfProfileOut( __METHOD__
);
220 return $this->mContent
;
225 * This function returns the text of a section, specified by a number ($section).
226 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
227 * the first section before any such heading (section 0).
229 * If a section contains subsections, these are also returned.
231 * @param $text String: text to look in
232 * @param $section Integer: section number
233 * @return string text of the requested section
236 function getSection($text,$section) {
238 return $wgParser->getSection( $text, $section );
242 * @return int The oldid of the article that is to be shown, 0 for the
245 function getOldID() {
246 if ( is_null( $this->mOldId
) ) {
247 $this->mOldId
= $this->getOldIDFromRequest();
249 return $this->mOldId
;
253 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
255 * @return int The old id for the request
257 function getOldIDFromRequest() {
259 $this->mRedirectUrl
= false;
260 $oldid = $wgRequest->getVal( 'oldid' );
261 if ( isset( $oldid ) ) {
262 $oldid = intval( $oldid );
263 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
264 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
268 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
270 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
271 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
289 * Load the revision (including text) into this object
291 function loadContent() {
292 if ( $this->mContentLoaded
) return;
295 $oldid = $this->getOldID();
297 # Pre-fill content with error message so that if something
298 # fails we'll have something telling us what we intended.
299 $this->mOldId
= $oldid;
300 $this->fetchContent( $oldid );
305 * Fetch a page record with the given conditions
306 * @param Database $dbr
307 * @param array $conditions
310 function pageData( $dbr, $conditions ) {
324 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
325 $row = $dbr->selectRow(
331 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
336 * @param Database $dbr
337 * @param Title $title
339 function pageDataFromTitle( $dbr, $title ) {
340 return $this->pageData( $dbr, array(
341 'page_namespace' => $title->getNamespace(),
342 'page_title' => $title->getDBkey() ) );
346 * @param Database $dbr
349 function pageDataFromId( $dbr, $id ) {
350 return $this->pageData( $dbr, array( 'page_id' => $id ) );
354 * Set the general counter, title etc data loaded from
357 * @param object $data
360 function loadPageData( $data = 'fromdb' ) {
361 if ( $data === 'fromdb' ) {
362 $dbr = wfGetDB( DB_MASTER
);
363 $data = $this->pageDataFromId( $dbr, $this->getId() );
366 $lc = LinkCache
::singleton();
368 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
370 $this->mTitle
->mArticleID
= $data->page_id
;
372 # Old-fashioned restrictions.
373 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
375 $this->mCounter
= $data->page_counter
;
376 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
377 $this->mIsRedirect
= $data->page_is_redirect
;
378 $this->mLatest
= $data->page_latest
;
380 if ( is_object( $this->mTitle
) ) {
381 $lc->addBadLinkObj( $this->mTitle
);
383 $this->mTitle
->mArticleID
= 0;
386 $this->mDataLoaded
= true;
390 * Get text of an article from database
391 * Does *NOT* follow redirects.
392 * @param int $oldid 0 for whatever the latest revision is
395 function fetchContent( $oldid = 0 ) {
396 if ( $this->mContentLoaded
) {
397 return $this->mContent
;
400 $dbr = wfGetDB( DB_MASTER
);
402 # Pre-fill content with error message so that if something
403 # fails we'll have something telling us what we intended.
404 $t = $this->mTitle
->getPrefixedText();
405 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
406 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
409 $revision = Revision
::newFromId( $oldid );
410 if( is_null( $revision ) ) {
411 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
414 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
416 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
419 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
420 $this->loadPageData( $data );
422 if( !$this->mDataLoaded
) {
423 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
425 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
428 $this->loadPageData( $data );
430 $revision = Revision
::newFromId( $this->mLatest
);
431 if( is_null( $revision ) ) {
432 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
437 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
438 // We should instead work with the Revision object when we need it...
439 $this->mContent
= $revision->revText(); // Loads if user is allowed
441 $this->mUser
= $revision->getUser();
442 $this->mUserText
= $revision->getUserText();
443 $this->mComment
= $revision->getComment();
444 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
446 $this->mRevIdFetched
= $revision->getId();
447 $this->mContentLoaded
= true;
448 $this->mRevision
=& $revision;
450 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
452 return $this->mContent
;
456 * Read/write accessor to select FOR UPDATE
458 * @param $x Mixed: FIXME
460 function forUpdate( $x = NULL ) {
461 return wfSetVar( $this->mForUpdate
, $x );
465 * Get the database which should be used for reads
468 * @deprecated - just call wfGetDB( DB_MASTER ) instead
471 wfDeprecated( __METHOD__
);
472 return wfGetDB( DB_MASTER
);
476 * Get options for all SELECT statements
478 * @param $options Array: an optional options array which'll be appended to
480 * @return Array: options
482 function getSelectOptions( $options = '' ) {
483 if ( $this->mForUpdate
) {
484 if ( is_array( $options ) ) {
485 $options[] = 'FOR UPDATE';
487 $options = 'FOR UPDATE';
494 * @return int Page ID
497 if( $this->mTitle
) {
498 return $this->mTitle
->getArticleID();
505 * @return bool Whether or not the page exists in the database
508 return $this->getId() != 0;
512 * @return int The view count for the page
514 function getCount() {
515 if ( -1 == $this->mCounter
) {
516 $id = $this->getID();
520 $dbr = wfGetDB( DB_SLAVE
);
521 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
522 'Article::getCount', $this->getSelectOptions() );
525 return $this->mCounter
;
529 * Determine whether a page would be suitable for being counted as an
530 * article in the site_stats table based on the title & its content
532 * @param $text String: text to analyze
535 function isCountable( $text ) {
536 global $wgUseCommaCount;
538 $token = $wgUseCommaCount ?
',' : '[[';
540 $this->mTitle
->isContentPage()
541 && !$this->isRedirect( $text )
542 && in_string( $token, $text );
546 * Tests if the article text represents a redirect
548 * @param $text String: FIXME
551 function isRedirect( $text = false ) {
552 if ( $text === false ) {
553 if ( $this->mDataLoaded
)
554 return $this->mIsRedirect
;
556 // Apparently loadPageData was never called
557 $this->loadContent();
558 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
560 $titleObj = Title
::newFromRedirect( $text );
562 return $titleObj !== NULL;
566 * Returns true if the currently-referenced revision is the current edit
567 * to this page (and it exists).
570 function isCurrent() {
571 # If no oldid, this is the current version.
572 if ($this->getOldID() == 0)
575 return $this->exists() &&
576 isset( $this->mRevision
) &&
577 $this->mRevision
->isCurrent();
581 * Loads everything except the text
582 * This isn't necessary for all uses, so it's only done if needed.
585 function loadLastEdit() {
586 if ( -1 != $this->mUser
)
589 # New or non-existent articles have no user information
590 $id = $this->getID();
591 if ( 0 == $id ) return;
593 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
594 if( !is_null( $this->mLastRevision
) ) {
595 $this->mUser
= $this->mLastRevision
->getUser();
596 $this->mUserText
= $this->mLastRevision
->getUserText();
597 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
598 $this->mComment
= $this->mLastRevision
->getComment();
599 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
600 $this->mRevIdFetched
= $this->mLastRevision
->getId();
604 function getTimestamp() {
605 // Check if the field has been filled by ParserCache::get()
606 if ( !$this->mTimestamp
) {
607 $this->loadLastEdit();
609 return wfTimestamp(TS_MW
, $this->mTimestamp
);
613 $this->loadLastEdit();
617 function getUserText() {
618 $this->loadLastEdit();
619 return $this->mUserText
;
622 function getComment() {
623 $this->loadLastEdit();
624 return $this->mComment
;
627 function getMinorEdit() {
628 $this->loadLastEdit();
629 return $this->mMinorEdit
;
632 function getRevIdFetched() {
633 $this->loadLastEdit();
634 return $this->mRevIdFetched
;
638 * @todo Document, fixme $offset never used.
639 * @param $limit Integer: default 0.
640 * @param $offset Integer: default 0.
642 function getContributors($limit = 0, $offset = 0) {
643 # XXX: this is expensive; cache this info somewhere.
646 $dbr = wfGetDB( DB_SLAVE
);
647 $revTable = $dbr->tableName( 'revision' );
648 $userTable = $dbr->tableName( 'user' );
649 $user = $this->getUser();
650 $pageId = $this->getId();
652 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
653 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
654 WHERE rev_page = $pageId
655 AND rev_user != $user
656 GROUP BY rev_user, rev_user_text, user_real_name
657 ORDER BY timestamp DESC";
659 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
660 $sql .= ' '. $this->getSelectOptions();
662 $res = $dbr->query($sql, __METHOD__
);
664 while ( $line = $dbr->fetchObject( $res ) ) {
665 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
668 $dbr->freeResult($res);
673 * This is the default action of the script: just view the page of
677 global $wgUser, $wgOut, $wgRequest, $wgContLang;
678 global $wgEnableParserCache, $wgStylePath, $wgParser;
679 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
680 global $wgDefaultRobotPolicy;
681 $sk = $wgUser->getSkin();
683 wfProfileIn( __METHOD__
);
685 $parserCache = ParserCache
::singleton();
686 $ns = $this->mTitle
->getNamespace(); # shortcut
688 # Get variables from query string
689 $oldid = $this->getOldID();
691 # getOldID may want us to redirect somewhere else
692 if ( $this->mRedirectUrl
) {
693 $wgOut->redirect( $this->mRedirectUrl
);
694 wfProfileOut( __METHOD__
);
698 $diff = $wgRequest->getVal( 'diff' );
699 $rcid = $wgRequest->getVal( 'rcid' );
700 $rdfrom = $wgRequest->getVal( 'rdfrom' );
701 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
702 $purge = $wgRequest->getVal( 'action' ) == 'purge';
704 $wgOut->setArticleFlag( true );
706 # Discourage indexing of printable versions, but encourage following
707 if( $wgOut->isPrintable() ) {
708 $policy = 'noindex,follow';
709 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
710 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
711 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
712 # Honour customised robot policies for this namespace
713 $policy = $wgNamespaceRobotPolicies[$ns];
715 $policy = $wgDefaultRobotPolicy;
717 $wgOut->setRobotPolicy( $policy );
719 # If we got diff and oldid in the query, we want to see a
720 # diff page instead of the article.
722 if ( !is_null( $diff ) ) {
723 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
725 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
726 // DifferenceEngine directly fetched the revision:
727 $this->mRevIdFetched
= $de->mNewid
;
728 $de->showDiffPage( $diffOnly );
730 // Needed to get the page's current revision
731 $this->loadPageData();
732 if( $diff == 0 ||
$diff == $this->mLatest
) {
733 # Run view updates for current revision only
734 $this->viewUpdates();
736 wfProfileOut( __METHOD__
);
740 if ( empty( $oldid ) && $this->checkTouched() ) {
741 $wgOut->setETag($parserCache->getETag($this, $wgUser));
743 if( $wgOut->checkLastModified( $this->mTouched
) ){
744 wfProfileOut( __METHOD__
);
746 } else if ( $this->tryFileCache() ) {
747 # tell wgOut that output is taken care of
749 $this->viewUpdates();
750 wfProfileOut( __METHOD__
);
755 # Should the parser cache be used?
756 $pcache = $this->useParserCache( $oldid );
757 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
758 if ( $wgUser->getOption( 'stubthreshold' ) ) {
759 wfIncrStats( 'pcache_miss_stub' );
762 $wasRedirected = false;
763 if ( isset( $this->mRedirectedFrom
) ) {
764 // This is an internally redirected page view.
765 // We'll need a backlink to the source page for navigation.
766 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
767 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
768 $s = wfMsg( 'redirectedfrom', $redir );
769 $wgOut->setSubtitle( $s );
771 // Set the fragment if one was specified in the redirect
772 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
773 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
774 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
776 $wasRedirected = true;
778 } elseif ( !empty( $rdfrom ) ) {
779 // This is an externally redirected view, from some other wiki.
780 // If it was reported from a trusted site, supply a backlink.
781 global $wgRedirectSources;
782 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
783 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
784 $s = wfMsg( 'redirectedfrom', $redir );
785 $wgOut->setSubtitle( $s );
786 $wasRedirected = true;
791 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
793 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
794 // Ensure that UI elements requiring revision ID have
795 // the correct version information.
796 $wgOut->setRevisionId( $this->mLatest
);
800 # Fetch content and check for errors
801 if ( !$outputDone ) {
802 $text = $this->getContent();
803 if ( $text === false ) {
804 # Failed to load, replace text with error message
805 $t = $this->mTitle
->getPrefixedText();
807 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
808 $text = wfMsg( 'missing-article', $t, $d );
810 $text = wfMsg( 'noarticletext' );
814 # Another whitelist check in case oldid is altering the title
815 if ( !$this->mTitle
->userCanRead() ) {
816 $wgOut->loginToUse();
818 wfProfileOut( __METHOD__
);
822 # We're looking at an old revision
823 if ( !empty( $oldid ) ) {
824 $wgOut->setRobotpolicy( 'noindex,nofollow' );
825 if( is_null( $this->mRevision
) ) {
826 // FIXME: This would be a nice place to load the 'no such page' text.
828 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
829 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
830 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
831 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
832 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
833 wfProfileOut( __METHOD__
);
836 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
837 // and we are allowed to see...
843 $wgOut->setRevisionId( $this->getRevIdFetched() );
845 // Pages containing custom CSS or JavaScript get special treatment
846 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
847 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
848 // Give hooks a chance to customise the output
849 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
850 // Wrap the whole lot in a <pre> and don't parse
852 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
853 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
854 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
855 $wgOut->addHtml( "\n</pre>\n" );
857 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
858 # Don't append the subtitle if this was an old revision
859 $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() );
860 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
861 $wgOut->addParserOutputNoText( $parseout );
862 } else if ( $pcache ) {
863 # Display content and save to parser cache
864 $this->outputWikiText( $text );
866 # Display content, don't attempt to save to parser cache
867 # Don't show section-edit links on old revisions... this way lies madness.
868 if( !$this->isCurrent() ) {
869 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
871 # Display content and don't save to parser cache
872 # With timing hack -- TS 2006-07-26
874 $this->outputWikiText( $text, false );
879 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
880 $this->mTitle
->getPrefixedDBkey()));
883 if( !$this->isCurrent() ) {
884 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
888 /* title may have been set from the cache */
889 $t = $wgOut->getPageTitle();
891 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
894 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
895 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
896 $wgOut->addWikiMsg('anontalkpagetext');
899 # If we have been passed an &rcid= parameter, we want to give the user a
900 # chance to mark this new article as patrolled.
901 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
903 "<div class='patrollink'>" .
904 wfMsgHtml( 'markaspatrolledlink',
905 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
906 "action=markpatrolled&rcid=$rcid" )
913 if ($wgUseTrackbacks)
914 $this->addTrackbacks();
916 $this->viewUpdates();
917 wfProfileOut( __METHOD__
);
921 * Should the parser cache be used?
923 protected function useParserCache( $oldid ) {
924 global $wgUser, $wgEnableParserCache;
926 return $wgEnableParserCache
927 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
930 && !$this->mTitle
->isCssOrJsPage()
931 && !$this->mTitle
->isCssJsSubpage();
934 protected function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
935 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
938 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
939 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
941 if( $appendSubtitle ) {
942 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
944 $sk = $wgUser->getSkin();
946 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
948 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
950 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
951 '<span class="redirectText">'.$link.'</span>' );
955 function addTrackbacks() {
956 global $wgOut, $wgUser;
958 $dbr = wfGetDB(DB_SLAVE
);
960 /* FROM */ 'trackbacks',
961 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
962 /* WHERE */ array('tb_page' => $this->getID())
965 if (!$dbr->numrows($tbs))
969 while ($o = $dbr->fetchObject($tbs)) {
971 if ($wgUser->isAllowed( 'trackback' )) {
972 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
973 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
974 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
977 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
984 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
987 function deletetrackback() {
988 global $wgUser, $wgRequest, $wgOut, $wgTitle;
990 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
991 $wgOut->addWikiMsg( 'sessionfailure' );
995 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
997 if (count($permission_errors)>0)
999 $wgOut->showPermissionsErrorPage( $permission_errors );
1003 $db = wfGetDB(DB_MASTER
);
1004 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1005 $wgTitle->invalidateCache();
1006 $wgOut->addWikiMsg('trackbackdeleteok');
1012 $wgOut->setArticleBodyOnly(true);
1017 * Handle action=purge
1020 global $wgUser, $wgRequest, $wgOut;
1022 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1023 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1027 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1028 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1029 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1030 $msg = str_replace( '$1',
1031 "<form method=\"post\" action=\"$action\">\n" .
1032 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1033 "</form>\n", $msg );
1035 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1036 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1037 $wgOut->addHTML( $msg );
1042 * Perform the actions of a page purging
1044 function doPurge() {
1046 // Invalidate the cache
1047 $this->mTitle
->invalidateCache();
1049 if ( $wgUseSquid ) {
1050 // Commit the transaction before the purge is sent
1051 $dbw = wfGetDB( DB_MASTER
);
1052 $dbw->immediateCommit();
1055 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1056 $update->doUpdate();
1058 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1059 global $wgMessageCache;
1060 if ( $this->getID() == 0 ) {
1063 $text = $this->getContent();
1065 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1071 * Insert a new empty page record for this article.
1072 * This *must* be followed up by creating a revision
1073 * and running $this->updateToLatest( $rev_id );
1074 * or else the record will be left in a funky state.
1075 * Best if all done inside a transaction.
1077 * @param Database $dbw
1078 * @return int The newly created page_id key
1081 function insertOn( $dbw ) {
1082 wfProfileIn( __METHOD__
);
1084 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1085 $dbw->insert( 'page', array(
1086 'page_id' => $page_id,
1087 'page_namespace' => $this->mTitle
->getNamespace(),
1088 'page_title' => $this->mTitle
->getDBkey(),
1089 'page_counter' => 0,
1090 'page_restrictions' => '',
1091 'page_is_redirect' => 0, # Will set this shortly...
1093 'page_random' => wfRandom(),
1094 'page_touched' => $dbw->timestamp(),
1095 'page_latest' => 0, # Fill this in shortly...
1096 'page_len' => 0, # Fill this in shortly...
1098 $newid = $dbw->insertId();
1100 $this->mTitle
->resetArticleId( $newid );
1102 wfProfileOut( __METHOD__
);
1107 * Update the page record to point to a newly saved revision.
1109 * @param Database $dbw
1110 * @param Revision $revision For ID number, and text used to set
1111 length and redirect status fields
1112 * @param int $lastRevision If given, will not overwrite the page field
1113 * when different from the currently set value.
1114 * Giving 0 indicates the new page flag should
1116 * @param bool $lastRevIsRedirect If given, will optimize adding and
1117 * removing rows in redirect table.
1118 * @return bool true on success, false on failure
1121 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1122 wfProfileIn( __METHOD__
);
1124 $text = $revision->getText();
1125 $rt = Title
::newFromRedirect( $text );
1127 $conditions = array( 'page_id' => $this->getId() );
1128 if( !is_null( $lastRevision ) ) {
1129 # An extra check against threads stepping on each other
1130 $conditions['page_latest'] = $lastRevision;
1133 $dbw->update( 'page',
1135 'page_latest' => $revision->getId(),
1136 'page_touched' => $dbw->timestamp(),
1137 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1138 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1139 'page_len' => strlen( $text ),
1144 $result = $dbw->affectedRows() != 0;
1147 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1150 wfProfileOut( __METHOD__
);
1155 * Add row to the redirect table if this is a redirect, remove otherwise.
1157 * @param Database $dbw
1158 * @param $redirectTitle a title object pointing to the redirect target,
1159 * or NULL if this is not a redirect
1160 * @param bool $lastRevIsRedirect If given, will optimize adding and
1161 * removing rows in redirect table.
1162 * @return bool true on success, false on failure
1165 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1167 // Always update redirects (target link might have changed)
1168 // Update/Insert if we don't know if the last revision was a redirect or not
1169 // Delete if changing from redirect to non-redirect
1170 $isRedirect = !is_null($redirectTitle);
1171 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1173 wfProfileIn( __METHOD__
);
1177 // This title is a redirect, Add/Update row in the redirect table
1178 $set = array( /* SET */
1179 'rd_namespace' => $redirectTitle->getNamespace(),
1180 'rd_title' => $redirectTitle->getDBkey(),
1181 'rd_from' => $this->getId(),
1184 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1186 // This is not a redirect, remove row from redirect table
1187 $where = array( 'rd_from' => $this->getId() );
1188 $dbw->delete( 'redirect', $where, __METHOD__
);
1191 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1192 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1193 wfProfileOut( __METHOD__
);
1194 return ( $dbw->affectedRows() != 0 );
1201 * If the given revision is newer than the currently set page_latest,
1202 * update the page record. Otherwise, do nothing.
1204 * @param Database $dbw
1205 * @param Revision $revision
1207 function updateIfNewerOn( &$dbw, $revision ) {
1208 wfProfileIn( __METHOD__
);
1210 $row = $dbw->selectRow(
1211 array( 'revision', 'page' ),
1212 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1214 'page_id' => $this->getId(),
1215 'page_latest=rev_id' ),
1218 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1219 wfProfileOut( __METHOD__
);
1222 $prev = $row->rev_id
;
1223 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1225 # No or missing previous revision; mark the page as new
1227 $lastRevIsRedirect = null;
1230 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1231 wfProfileOut( __METHOD__
);
1236 * @return string Complete article text, or null if error
1238 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1239 wfProfileIn( __METHOD__
);
1241 if( $section == '' ) {
1242 // Whole-page edit; let the text through unmolested.
1244 if( is_null( $edittime ) ) {
1245 $rev = Revision
::newFromTitle( $this->mTitle
);
1247 $dbw = wfGetDB( DB_MASTER
);
1248 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1250 if( is_null( $rev ) ) {
1251 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1252 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1255 $oldtext = $rev->getText();
1257 if( $section == 'new' ) {
1258 # Inserting a new section
1259 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1260 $text = strlen( trim( $oldtext ) ) > 0
1261 ?
"{$oldtext}\n\n{$subject}{$text}"
1262 : "{$subject}{$text}";
1264 # Replacing an existing section; roll out the big guns
1266 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1271 wfProfileOut( __METHOD__
);
1276 * @deprecated use Article::doEdit()
1278 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1279 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1280 ( $isminor ? EDIT_MINOR
: 0 ) |
1281 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1282 ( $bot ? EDIT_FORCE_BOT
: 0 );
1284 # If this is a comment, add the summary as headline
1285 if ( $comment && $summary != "" ) {
1286 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1289 $this->doEdit( $text, $summary, $flags );
1291 $dbw = wfGetDB( DB_MASTER
);
1293 if (!$this->mTitle
->userIsWatching()) {
1299 if ( $this->mTitle
->userIsWatching() ) {
1305 $this->doRedirect( $this->isRedirect( $text ) );
1309 * @deprecated use Article::doEdit()
1311 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1312 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1313 ( $minor ? EDIT_MINOR
: 0 ) |
1314 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1316 $good = $this->doEdit( $text, $summary, $flags );
1318 $dbw = wfGetDB( DB_MASTER
);
1320 if (!$this->mTitle
->userIsWatching()) {
1326 if ( $this->mTitle
->userIsWatching() ) {
1333 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1334 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1336 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1344 * Change an existing article or create a new article. Updates RC and all necessary caches,
1345 * optionally via the deferred update array.
1347 * $wgUser must be set before calling this function.
1349 * @param string $text New text
1350 * @param string $summary Edit summary
1351 * @param integer $flags bitfield:
1353 * Article is known or assumed to be non-existent, create a new one
1355 * Article is known or assumed to be pre-existing, update it
1357 * Mark this edit minor, if the user is allowed to do so
1359 * Do not log the change in recentchanges
1361 * Mark the edit a "bot" edit regardless of user rights
1362 * EDIT_DEFER_UPDATES
1363 * Defer some of the updates until the end of index.php
1365 * Fill in blank summaries with generated text where possible
1367 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1368 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1369 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1370 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1371 * to MediaWiki's performance-optimised locking strategy.
1372 * @param $baseRevId, the revision ID this edit was based off, if any
1374 * @return bool success
1376 function doEdit( $text, $summary, $flags = 0, $baseRevId = false ) {
1377 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1379 wfProfileIn( __METHOD__
);
1382 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1383 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1385 $flags |
= EDIT_UPDATE
;
1391 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1392 &$summary, $flags & EDIT_MINOR
,
1393 null, null, &$flags ) ) )
1395 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1396 wfProfileOut( __METHOD__
);
1400 # Silently ignore EDIT_MINOR if not allowed
1401 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1402 $bot = $flags & EDIT_FORCE_BOT
;
1404 $oldtext = $this->getContent();
1405 $oldsize = strlen( $oldtext );
1407 # Provide autosummaries if one is not provided and autosummaries are enabled.
1408 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1409 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1412 $editInfo = $this->prepareTextForEdit( $text );
1413 $text = $editInfo->pst
;
1414 $newsize = strlen( $text );
1416 $dbw = wfGetDB( DB_MASTER
);
1417 $now = wfTimestampNow();
1419 if ( $flags & EDIT_UPDATE
) {
1420 # Update article, but only if changed.
1422 # Make sure the revision is either completely inserted or not inserted at all
1423 if( !$wgDBtransactions ) {
1424 $userAbort = ignore_user_abort( true );
1430 $changed = ( strcmp( $text, $oldtext ) != 0 );
1433 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1434 - (int)$this->isCountable( $oldtext );
1435 $this->mTotalAdjustment
= 0;
1437 $lastRevision = $dbw->selectField(
1438 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1440 if ( !$lastRevision ) {
1441 # Article gone missing
1442 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1443 wfProfileOut( __METHOD__
);
1447 $revision = new Revision( array(
1448 'page' => $this->getId(),
1449 'comment' => $summary,
1450 'minor_edit' => $isminor,
1452 'parent_id' => $lastRevision
1456 $revisionId = $revision->insertOn( $dbw );
1459 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1461 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId) );
1464 /* Belated edit conflict! Run away!! */
1468 # Update recentchanges
1469 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1470 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1471 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1474 # Mark as patrolled if the user can do so
1475 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1476 RecentChange
::markPatrolled( $rcid );
1477 PatrolLog
::record( $rcid, true );
1480 $wgUser->incEditCount();
1485 // Keep the same revision ID, but do some updates on it
1486 $revisionId = $this->getRevIdFetched();
1487 // Update page_touched, this is usually implicit in the page update
1488 // Other cache updates are done in onArticleEdit()
1489 $this->mTitle
->invalidateCache();
1492 if( !$wgDBtransactions ) {
1493 ignore_user_abort( $userAbort );
1497 # Invalidate cache of this article and all pages using this article
1498 # as a template. Partly deferred.
1499 Article
::onArticleEdit( $this->mTitle
);
1501 # Update links tables, site stats, etc.
1502 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1505 # Create new article
1507 # Set statistics members
1508 # We work out if it's countable after PST to avoid counter drift
1509 # when articles are created with {{subst:}}
1510 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1511 $this->mTotalAdjustment
= 1;
1515 # Add the page record; stake our claim on this title!
1516 # This will fail with a database query exception if the article already exists
1517 $newid = $this->insertOn( $dbw );
1519 # Save the revision text...
1520 $revision = new Revision( array(
1522 'comment' => $summary,
1523 'minor_edit' => $isminor,
1526 $revisionId = $revision->insertOn( $dbw );
1528 $this->mTitle
->resetArticleID( $newid );
1530 # Update the page record with revision data
1531 $this->updateRevisionOn( $dbw, $revision, 0 );
1533 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1535 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1536 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1537 '', strlen( $text ), $revisionId );
1538 # Mark as patrolled if the user can
1539 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1540 RecentChange
::markPatrolled( $rcid );
1541 PatrolLog
::record( $rcid, true );
1544 $wgUser->incEditCount();
1547 # Update links, etc.
1548 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1551 Article
::onArticleCreate( $this->mTitle
);
1553 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1554 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1557 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1562 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1563 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1566 wfProfileOut( __METHOD__
);
1571 * @deprecated wrapper for doRedirect
1573 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1574 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1578 * Output a redirect back to the article.
1579 * This is typically used after an edit.
1581 * @param boolean $noRedir Add redirect=no
1582 * @param string $sectionAnchor section to redirect to, including "#"
1583 * @param string $extraQuery, extra query params
1585 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1588 $query = 'redirect=no';
1590 $query .= "&$query";
1592 $query = $extraQuery;
1594 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1598 * Mark this particular edit/page as patrolled
1600 function markpatrolled() {
1601 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1602 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1604 # Check patrol config options
1606 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1607 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1611 # If we haven't been given an rc_id value, we can't do anything
1612 $rcid = (int) $wgRequest->getVal('rcid');
1613 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1614 if ( is_null ( $rc ) )
1616 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1620 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1621 // Only new pages can be patrolled if the general patrolling is off....???
1622 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1624 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1629 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1631 if (count($permission_errors)>0)
1633 $wgOut->showPermissionsErrorPage( $permission_errors );
1637 # Handle the 'MarkPatrolled' hook
1638 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1642 #It would be nice to see where the user had actually come from, but for now just guess
1643 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1644 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1646 # If it's left up to us, check that the user is allowed to patrol this edit
1647 # If the user has the "autopatrol" right, then we'll assume there are no
1648 # other conditions stopping them doing so
1649 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1650 $rc = RecentChange
::newFromId( $rcid );
1651 # Graceful error handling, as we've done before here...
1652 # (If the recent change doesn't exist, then it doesn't matter whether
1653 # the user is allowed to patrol it or not; nothing is going to happen
1654 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1655 # The user made this edit, and can't patrol it
1656 # Tell them so, and then back off
1657 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1658 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1659 $wgOut->returnToMain( false, $return );
1664 # Check that the revision isn't patrolled already
1665 # Prevents duplicate log entries
1666 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1667 # Mark the edit as patrolled
1668 RecentChange
::markPatrolled( $rcid );
1669 PatrolLog
::record( $rcid );
1670 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1674 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1675 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1676 $wgOut->returnToMain( false, $return );
1680 * User-interface handler for the "watch" action
1685 global $wgUser, $wgOut;
1687 if ( $wgUser->isAnon() ) {
1688 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1691 if ( wfReadOnly() ) {
1692 $wgOut->readOnlyPage();
1696 if( $this->doWatch() ) {
1697 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1698 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1700 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1703 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1707 * Add this page to $wgUser's watchlist
1708 * @return bool true on successful watch operation
1710 function doWatch() {
1712 if( $wgUser->isAnon() ) {
1716 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1717 $wgUser->addWatch( $this->mTitle
);
1719 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1726 * User interface handler for the "unwatch" action.
1728 function unwatch() {
1730 global $wgUser, $wgOut;
1732 if ( $wgUser->isAnon() ) {
1733 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1736 if ( wfReadOnly() ) {
1737 $wgOut->readOnlyPage();
1741 if( $this->doUnwatch() ) {
1742 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1743 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1745 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1748 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1752 * Stop watching a page
1753 * @return bool true on successful unwatch
1755 function doUnwatch() {
1757 if( $wgUser->isAnon() ) {
1761 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1762 $wgUser->removeWatch( $this->mTitle
);
1764 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1771 * action=protect handler
1773 function protect() {
1774 $form = new ProtectionForm( $this );
1779 * action=unprotect handler (alias)
1781 function unprotect() {
1786 * Update the article's restriction field, and leave a log entry.
1788 * @param array $limit set of restriction keys
1789 * @param string $reason
1790 * @return bool true on success
1792 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1793 global $wgUser, $wgRestrictionTypes, $wgContLang;
1795 $id = $this->mTitle
->getArticleID();
1796 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1804 // Take this opportunity to purge out expired restrictions
1805 Title
::purgeExpiredRestrictions();
1807 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1808 # we expect a single selection, but the schema allows otherwise.
1810 foreach( $wgRestrictionTypes as $action )
1811 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1813 $current = Article
::flattenRestrictions( $current );
1814 $updated = Article
::flattenRestrictions( $limit );
1816 $changed = ( $current != $updated );
1817 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1818 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1819 $protect = ( $updated != '' );
1821 # If nothing's changed, do nothing
1823 global $wgGroupPermissions;
1824 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1826 $dbw = wfGetDB( DB_MASTER
);
1828 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1830 $expiry_description = '';
1831 if ( $encodedExpiry != 'infinity' ) {
1832 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1835 # Prepare a null revision to be added to the history
1836 $modified = $current != '' && $protect;
1838 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1840 $comment_type = 'unprotectedarticle';
1842 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1844 # Only restrictions with the 'protect' right can cascade...
1845 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1846 foreach( $limit as $action => $restriction ) {
1847 # FIXME: can $restriction be an array or what? (same as fixme above)
1848 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1854 $cascade_description = '';
1856 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1860 $comment .= ": $reason";
1862 $comment .= " [$updated]";
1863 if ( $expiry_description && $protect )
1864 $comment .= "$expiry_description";
1866 $comment .= "$cascade_description";
1868 # Update restrictions table
1869 foreach( $limit as $action => $restrictions ) {
1870 if ($restrictions != '' ) {
1871 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1872 array( 'pr_page' => $id, 'pr_type' => $action
1873 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1874 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1876 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1877 'pr_type' => $action ), __METHOD__
);
1881 # Insert a null revision
1882 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1883 $nullRevId = $nullRevision->insertOn( $dbw );
1885 # Update page record
1886 $dbw->update( 'page',
1888 'page_touched' => $dbw->timestamp(),
1889 'page_restrictions' => '',
1890 'page_latest' => $nullRevId
1891 ), array( /* WHERE */
1893 ), 'Article::protect'
1896 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, false) );
1897 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1899 # Update the protection log
1900 $log = new LogPage( 'protect' );
1902 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
,
1903 trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1905 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1909 } # End "changed" check
1915 * Take an array of page restrictions and flatten it to a string
1916 * suitable for insertion into the page_restrictions field.
1917 * @param array $limit
1921 function flattenRestrictions( $limit ) {
1922 if( !is_array( $limit ) ) {
1923 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1927 foreach( $limit as $action => $restrictions ) {
1928 if( $restrictions != '' ) {
1929 $bits[] = "$action=$restrictions";
1932 return implode( ':', $bits );
1936 * Auto-generates a deletion reason
1937 * @param bool &$hasHistory Whether the page has a history
1939 public function generateReason(&$hasHistory)
1942 $dbw = wfGetDB(DB_MASTER
);
1943 // Get the last revision
1944 $rev = Revision
::newFromTitle($this->mTitle
);
1947 // Get the article's contents
1948 $contents = $rev->getText();
1950 // If the page is blank, use the text from the previous revision,
1951 // which can only be blank if there's a move/import/protect dummy revision involved
1954 $prev = $rev->getPrevious();
1957 $contents = $prev->getText();
1962 // Find out if there was only one contributor
1963 // Only scan the last 20 revisions
1965 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1966 array('LIMIT' => $limit));
1968 // This page has no revisions, which is very weird
1970 if($res->numRows() > 1)
1973 $hasHistory = false;
1974 $row = $dbw->fetchObject($res);
1975 $onlyAuthor = $row->rev_user_text
;
1976 // Try to find a second contributor
1977 while( $row = $dbw->fetchObject($res) ) {
1978 if($row->rev_user_text
!= $onlyAuthor) {
1979 $onlyAuthor = false;
1983 $dbw->freeResult($res);
1985 // Generate the summary with a '$1' placeholder
1987 // The current revision is blank and the one before is also
1988 // blank. It's just not our lucky day
1989 $reason = wfMsgForContent('exbeforeblank', '$1');
1992 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1994 $reason = wfMsgForContent('excontent', '$1');
1997 // Replace newlines with spaces to prevent uglyness
1998 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1999 // Calculate the maximum amount of chars to get
2000 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2001 $maxLength = 255 - (strlen($reason) - 2) - 3;
2002 $contents = $wgContLang->truncate($contents, $maxLength, '...');
2003 // Remove possible unfinished links
2004 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2005 // Now replace the '$1' placeholder
2006 $reason = str_replace( '$1', $contents, $reason );
2012 * UI entry point for page deletion
2015 global $wgUser, $wgOut, $wgRequest;
2017 $confirm = $wgRequest->wasPosted() &&
2018 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2020 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2021 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2023 $reason = $this->DeleteReasonList
;
2025 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2026 // Entry from drop down menu + additional comment
2027 $reason .= ': ' . $this->DeleteReason
;
2028 } elseif ( $reason == 'other' ) {
2029 $reason = $this->DeleteReason
;
2031 # Flag to hide all contents of the archived revisions
2032 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2034 # This code desperately needs to be totally rewritten
2036 # Read-only check...
2037 if ( wfReadOnly() ) {
2038 $wgOut->readOnlyPage();
2043 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2045 if (count($permission_errors)>0) {
2046 $wgOut->showPermissionsErrorPage( $permission_errors );
2050 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2052 # Better double-check that it hasn't been deleted yet!
2053 $dbw = wfGetDB( DB_MASTER
);
2054 $conds = $this->mTitle
->pageCond();
2055 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2056 if ( $latest === false ) {
2057 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2061 # Hack for big sites
2062 $bigHistory = $this->isBigDeletion();
2063 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2064 global $wgLang, $wgDeleteRevisionsLimit;
2065 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2066 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2071 $this->doDelete( $reason, $suppress );
2072 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2074 } elseif( $this->mTitle
->userIsWatching() ) {
2080 // Generate deletion reason
2081 $hasHistory = false;
2082 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2084 // If the page has a history, insert a warning
2085 if( $hasHistory && !$confirm ) {
2086 $skin=$wgUser->getSkin();
2087 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2089 global $wgLang, $wgDeleteRevisionsLimit;
2090 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2091 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2095 return $this->confirmDelete( '', $reason );
2099 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2101 function isBigDeletion() {
2102 global $wgDeleteRevisionsLimit;
2103 if( $wgDeleteRevisionsLimit ) {
2104 $revCount = $this->estimateRevisionCount();
2105 return $revCount > $wgDeleteRevisionsLimit;
2111 * @return int approximate revision count
2113 function estimateRevisionCount() {
2115 // For an exact count...
2116 //return $dbr->selectField( 'revision', 'COUNT(*)',
2117 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2118 return $dbr->estimateRowCount( 'revision', '*',
2119 array( 'rev_page' => $this->getId() ), __METHOD__
);
2123 * Get the last N authors
2124 * @param int $num Number of revisions to get
2125 * @param string $revLatest The latest rev_id, selected from the master (optional)
2126 * @return array Array of authors, duplicates not removed
2128 function getLastNAuthors( $num, $revLatest = 0 ) {
2129 wfProfileIn( __METHOD__
);
2131 // First try the slave
2132 // If that doesn't have the latest revision, try the master
2134 $db = wfGetDB( DB_SLAVE
);
2136 $res = $db->select( array( 'page', 'revision' ),
2137 array( 'rev_id', 'rev_user_text' ),
2139 'page_namespace' => $this->mTitle
->getNamespace(),
2140 'page_title' => $this->mTitle
->getDBkey(),
2141 'rev_page = page_id'
2142 ), __METHOD__
, $this->getSelectOptions( array(
2143 'ORDER BY' => 'rev_timestamp DESC',
2148 wfProfileOut( __METHOD__
);
2151 $row = $db->fetchObject( $res );
2152 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2153 $db = wfGetDB( DB_MASTER
);
2158 } while ( $continue );
2160 $authors = array( $row->rev_user_text
);
2161 while ( $row = $db->fetchObject( $res ) ) {
2162 $authors[] = $row->rev_user_text
;
2164 wfProfileOut( __METHOD__
);
2169 * Output deletion confirmation dialog
2170 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2171 * @param $reason string Prefilled reason
2173 function confirmDelete( $par, $reason ) {
2174 global $wgOut, $wgUser, $wgContLang;
2175 $align = $wgContLang->isRtl() ?
'left' : 'right';
2177 wfDebug( "Article::confirmDelete\n" );
2179 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2180 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2181 $wgOut->addWikiMsg( 'confirmdeletetext' );
2183 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2184 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2185 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2186 $suppress .= "</td></tr>";
2191 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2192 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2193 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2194 Xml
::openElement( 'table' ) .
2195 "<tr id=\"wpDeleteReasonListRow\">
2196 <td align='$align'>" .
2197 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2200 Xml
::listDropDown( 'wpDeleteReasonList',
2201 wfMsgForContent( 'deletereason-dropdown' ),
2202 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2205 <tr id=\"wpDeleteReasonRow\">
2206 <td align='$align'>" .
2207 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2210 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2216 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2223 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2226 Xml
::closeElement( 'table' ) .
2227 Xml
::closeElement( 'fieldset' ) .
2228 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2229 Xml
::closeElement( 'form' );
2231 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2232 $skin = $wgUser->getSkin();
2233 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2234 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2237 $wgOut->addHTML( $form );
2238 $this->showLogExtract( $wgOut );
2243 * Show relevant lines from the deletion log
2245 function showLogExtract( $out ) {
2246 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2247 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2252 * Perform a deletion and output success or failure messages
2254 function doDelete( $reason, $suppress = false ) {
2255 global $wgOut, $wgUser;
2256 wfDebug( __METHOD__
."\n" );
2258 $id = $this->getId();
2262 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error))) {
2263 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2264 $deleted = $this->mTitle
->getPrefixedText();
2266 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2267 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2269 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2271 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2272 $wgOut->returnToMain( false );
2273 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2276 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2278 $wgOut->showFatalError( $error );
2284 * Back-end article deletion
2285 * Deletes the article with database consistency, writes logs, purges caches
2288 function doDeleteArticle( $reason, $suppress = false ) {
2289 global $wgUseSquid, $wgDeferredUpdateList;
2290 global $wgUseTrackbacks;
2292 wfDebug( __METHOD__
."\n" );
2294 $dbw = wfGetDB( DB_MASTER
);
2295 $ns = $this->mTitle
->getNamespace();
2296 $t = $this->mTitle
->getDBkey();
2297 $id = $this->mTitle
->getArticleID();
2299 if ( $t == '' ||
$id == 0 ) {
2303 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2304 array_push( $wgDeferredUpdateList, $u );
2306 // Bitfields to further suppress the content
2309 // This should be 15...
2310 $bitfield |
= Revision
::DELETED_TEXT
;
2311 $bitfield |
= Revision
::DELETED_COMMENT
;
2312 $bitfield |
= Revision
::DELETED_USER
;
2313 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2315 $bitfield = 'rev_deleted';
2319 // For now, shunt the revision data into the archive table.
2320 // Text is *not* removed from the text table; bulk storage
2321 // is left intact to avoid breaking block-compression or
2322 // immutable storage schemes.
2324 // For backwards compatibility, note that some older archive
2325 // table entries will have ar_text and ar_flags fields still.
2327 // In the future, we may keep revisions and mark them with
2328 // the rev_deleted field, which is reserved for this purpose.
2329 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2331 'ar_namespace' => 'page_namespace',
2332 'ar_title' => 'page_title',
2333 'ar_comment' => 'rev_comment',
2334 'ar_user' => 'rev_user',
2335 'ar_user_text' => 'rev_user_text',
2336 'ar_timestamp' => 'rev_timestamp',
2337 'ar_minor_edit' => 'rev_minor_edit',
2338 'ar_rev_id' => 'rev_id',
2339 'ar_text_id' => 'rev_text_id',
2340 'ar_text' => '\'\'', // Be explicit to appease
2341 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2342 'ar_len' => 'rev_len',
2343 'ar_page_id' => 'page_id',
2344 'ar_deleted' => $bitfield
2347 'page_id = rev_page'
2351 # Delete restrictions for it
2352 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2354 # Fix category table counts
2356 $res = $dbw->select( 'categorylinks', 'cl_to',
2357 array( 'cl_from' => $id ), __METHOD__
);
2358 foreach( $res as $row ) {
2359 $cats []= $row->cl_to
;
2361 $this->updateCategoryCounts( array(), $cats );
2363 # Now that it's safely backed up, delete it
2364 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2365 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2371 # If using cascading deletes, we can skip some explicit deletes
2372 if ( !$dbw->cascadingDeletes() ) {
2373 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2375 if ($wgUseTrackbacks)
2376 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2378 # Delete outgoing links
2379 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2380 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2381 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2382 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2383 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2384 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2385 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2388 # If using cleanup triggers, we can skip some manual deletes
2389 if ( !$dbw->cleanupTriggers() ) {
2391 # Clean up recentchanges entries...
2392 $dbw->delete( 'recentchanges',
2393 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2399 Article
::onArticleDelete( $this->mTitle
);
2401 # Clear the cached article id so the interface doesn't act like we exist
2402 $this->mTitle
->resetArticleID( 0 );
2403 $this->mTitle
->mArticleID
= 0;
2405 # Log the deletion, if the page was suppressed, log it at Oversight instead
2406 $logtype = $suppress ?
'suppress' : 'delete';
2407 $log = new LogPage( $logtype );
2409 # Make sure logging got through
2410 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2416 * Roll back the most recent consecutive set of edits to a page
2417 * from the same user; fails if there are no eligible edits to
2418 * roll back to, e.g. user is the sole contributor. This function
2419 * performs permissions checks on $wgUser, then calls commitRollback()
2420 * to do the dirty work
2422 * @param string $fromP - Name of the user whose edits to rollback.
2423 * @param string $summary - Custom summary. Set to default summary if empty.
2424 * @param string $token - Rollback token.
2425 * @param bool $bot - If true, mark all reverted edits as bot.
2427 * @param array $resultDetails contains result-specific array of additional values
2428 * 'alreadyrolled' : 'current' (rev)
2429 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2431 * @return array of errors, each error formatted as
2432 * array(messagekey, param1, param2, ...).
2433 * On success, the array is empty. This array can also be passed to
2434 * OutputPage::showPermissionsErrorPage().
2436 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2438 $resultDetails = null;
2441 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2442 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2443 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2444 $errors[] = array( 'sessionfailure' );
2446 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2447 $errors[] = array( 'actionthrottledtext' );
2449 # If there were errors, bail out now
2453 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2457 * Backend implementation of doRollback(), please refer there for parameter
2458 * and return value documentation
2460 * NOTE: This function does NOT check ANY permissions, it just commits the
2461 * rollback to the DB Therefore, you should only call this function direct-
2462 * ly if you want to use custom permissions checks. If you don't, use
2463 * doRollback() instead.
2465 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2466 global $wgUseRCPatrol, $wgUser, $wgLang;
2467 $dbw = wfGetDB( DB_MASTER
);
2469 if( wfReadOnly() ) {
2470 return array( array( 'readonlytext' ) );
2473 # Get the last editor
2474 $current = Revision
::newFromTitle( $this->mTitle
);
2475 if( is_null( $current ) ) {
2476 # Something wrong... no page?
2477 return array(array('notanarticle'));
2480 $from = str_replace( '_', ' ', $fromP );
2481 if( $from != $current->getUserText() ) {
2482 $resultDetails = array( 'current' => $current );
2483 return array(array('alreadyrolled',
2484 htmlspecialchars($this->mTitle
->getPrefixedText()),
2485 htmlspecialchars($fromP),
2486 htmlspecialchars($current->getUserText())
2490 # Get the last edit not by this guy
2491 $user = intval( $current->getUser() );
2492 $user_text = $dbw->addQuotes( $current->getUserText() );
2493 $s = $dbw->selectRow( 'revision',
2494 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2495 array( 'rev_page' => $current->getPage(),
2496 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2498 array( 'USE INDEX' => 'page_timestamp',
2499 'ORDER BY' => 'rev_timestamp DESC' )
2501 if( $s === false ) {
2502 # No one else ever edited this page
2503 return array(array('cantrollback'));
2504 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2505 # Only admins can see this text
2506 return array(array('notvisiblerev'));
2510 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2511 # Mark all reverted edits as bot
2514 if ( $wgUseRCPatrol ) {
2515 # Mark all reverted edits as patrolled
2516 $set['rc_patrolled'] = 1;
2520 $dbw->update( 'recentchanges', $set,
2522 'rc_cur_id' => $current->getPage(),
2523 'rc_user_text' => $current->getUserText(),
2524 "rc_timestamp > '{$s->rev_timestamp}'",
2529 # Generate the edit summary if necessary
2530 $target = Revision
::newFromId( $s->rev_id
);
2531 if( empty( $summary ) ){
2532 $summary = wfMsgForContent( 'revertpage' );
2535 # Allow the custom summary to use the same args as the default message
2537 $target->getUserText(), $from, $s->rev_id
,
2538 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2539 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2541 $summary = wfMsgReplaceArgs( $summary, $args );
2544 $flags = EDIT_UPDATE
;
2546 if ($wgUser->isAllowed('minoredit'))
2547 $flags |
= EDIT_MINOR
;
2549 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2550 $flags |
= EDIT_FORCE_BOT
;
2551 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2553 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2555 $resultDetails = array(
2556 'summary' => $summary,
2557 'current' => $current,
2558 'target' => $target,
2564 * User interface for rollback operations
2566 function rollback() {
2567 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2570 $result = $this->doRollback(
2571 $wgRequest->getVal( 'from' ),
2572 $wgRequest->getText( 'summary' ),
2573 $wgRequest->getVal( 'token' ),
2574 $wgRequest->getBool( 'bot' ),
2578 if( in_array( array( 'blocked' ), $result ) ) {
2579 $wgOut->blockedPage();
2582 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2583 $wgOut->rateLimited();
2586 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2587 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2588 $errArray = $result[0];
2589 $errMsg = array_shift( $errArray );
2590 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2591 if( isset( $details['current'] ) ){
2592 $current = $details['current'];
2593 if( $current->getComment() != '' ) {
2594 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2599 # Display permissions errors before read-only message -- there's no
2600 # point in misleading the user into thinking the inability to rollback
2601 # is only temporary.
2602 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2603 # array_diff is completely broken for arrays of arrays, sigh. Re-
2604 # move any 'readonlytext' error manually.
2606 foreach( $result as $error ) {
2607 if( $error != array( 'readonlytext' ) ) {
2611 $wgOut->showPermissionsErrorPage( $out );
2614 if( $result == array( array('readonlytext') ) ) {
2615 $wgOut->readOnlyPage();
2619 $current = $details['current'];
2620 $target = $details['target'];
2621 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2622 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2623 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2624 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2625 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2626 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2627 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2628 $wgOut->returnToMain( false, $this->mTitle
);
2630 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2631 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), 'next', false, true );
2632 $de->showDiff( '', '' );
2638 * Do standard deferred updates after page view
2641 function viewUpdates() {
2642 global $wgDeferredUpdateList, $wgUser;
2644 if ( 0 != $this->getID() ) {
2645 # Don't update page view counters on views from bot users (bug 14044)
2646 global $wgDisableCounters;
2647 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2648 Article
::incViewCount( $this->getID() );
2649 $u = new SiteStatsUpdate( 1, 0, 0 );
2650 array_push( $wgDeferredUpdateList, $u );
2654 # Update newtalk / watchlist notification status
2655 $wgUser->clearNotification( $this->mTitle
);
2659 * Prepare text which is about to be saved.
2660 * Returns a stdclass with source, pst and output members
2662 function prepareTextForEdit( $text, $revid=null ) {
2663 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2665 return $this->mPreparedEdit
;
2668 $edit = (object)array();
2669 $edit->revid
= $revid;
2670 $edit->newText
= $text;
2671 $edit->pst
= $this->preSaveTransform( $text );
2672 $options = new ParserOptions
;
2673 $options->setTidy( true );
2674 $options->enableLimitReport();
2675 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2676 $edit->oldText
= $this->getContent();
2677 $this->mPreparedEdit
= $edit;
2682 * Do standard deferred updates after page edit.
2683 * Update links tables, site stats, search index and message cache.
2684 * Every 100th edit, prune the recent changes table.
2687 * @param $text New text of the article
2688 * @param $summary Edit summary
2689 * @param $minoredit Minor edit
2690 * @param $timestamp_of_pagechange Timestamp associated with the page change
2691 * @param $newid rev_id value of the new revision
2692 * @param $changed Whether or not the content actually changed
2694 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2695 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2697 wfProfileIn( __METHOD__
);
2700 # Be careful not to double-PST: $text is usually already PST-ed once
2701 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2702 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2703 $editInfo = $this->prepareTextForEdit( $text, $newid );
2705 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2706 $editInfo = $this->mPreparedEdit
;
2709 # Save it to the parser cache
2710 if ( $wgEnableParserCache ) {
2711 $parserCache = ParserCache
::singleton();
2712 $parserCache->save( $editInfo->output
, $this, $wgUser );
2715 # Update the links tables
2716 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2719 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2720 if ( 0 == mt_rand( 0, 99 ) ) {
2721 // Flush old entries from the `recentchanges` table; we do this on
2722 // random requests so as to avoid an increase in writes for no good reason
2724 $dbw = wfGetDB( DB_MASTER
);
2725 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2726 $recentchanges = $dbw->tableName( 'recentchanges' );
2727 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2728 $dbw->query( $sql );
2732 $id = $this->getID();
2733 $title = $this->mTitle
->getPrefixedDBkey();
2734 $shortTitle = $this->mTitle
->getDBkey();
2737 wfProfileOut( __METHOD__
);
2741 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2742 array_push( $wgDeferredUpdateList, $u );
2743 $u = new SearchUpdate( $id, $title, $text );
2744 array_push( $wgDeferredUpdateList, $u );
2746 # If this is another user's talk page, update newtalk
2747 # Don't do this if $changed = false otherwise some idiot can null-edit a
2748 # load of user talk pages and piss people off, nor if it's a minor edit
2749 # by a properly-flagged bot.
2750 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2751 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2752 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2753 $other = User
::newFromName( $shortTitle );
2754 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2755 // An anonymous user
2756 $other = new User();
2757 $other->setName( $shortTitle );
2760 $other->setNewtalk( true );
2765 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2766 $wgMessageCache->replace( $shortTitle, $text );
2769 wfProfileOut( __METHOD__
);
2773 * Perform article updates on a special page creation.
2775 * @param Revision $rev
2777 * @todo This is a shitty interface function. Kill it and replace the
2778 * other shitty functions like editUpdates and such so it's not needed
2781 function createUpdates( $rev ) {
2782 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2783 $this->mTotalAdjustment
= 1;
2784 $this->editUpdates( $rev->getText(), $rev->getComment(),
2785 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2789 * Generate the navigation links when browsing through an article revisions
2790 * It shows the information as:
2791 * Revision as of \<date\>; view current revision
2792 * \<- Previous version | Next Version -\>
2795 * @param string $oldid Revision ID of this article revision
2797 function setOldSubtitle( $oldid=0 ) {
2798 global $wgLang, $wgOut, $wgUser;
2800 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2804 $revision = Revision
::newFromId( $oldid );
2806 $current = ( $oldid == $this->mLatest
);
2807 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2808 $sk = $wgUser->getSkin();
2810 ?
wfMsg( 'currentrevisionlink' )
2811 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2814 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2815 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2817 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2818 : wfMsg( 'previousrevision' );
2820 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2822 $nextlink = $current
2823 ?
wfMsg( 'nextrevision' )
2824 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2825 $nextdiff = $current
2827 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2830 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2831 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2832 if( $revision->isCurrent() ) {
2833 // We don't handle top deleted edits too well
2834 $cdel = wfMsgHtml('rev-delundel');
2835 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2836 // If revision was hidden from sysops
2837 $cdel = wfMsgHtml('rev-delundel');
2839 $cdel = $sk->makeKnownLinkObj( $revdel,
2840 wfMsgHtml('rev-delundel'),
2841 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2842 '&oldid=' . urlencode( $oldid ) );
2843 // Bolden oversighted content
2844 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2845 $cdel = "<strong>$cdel</strong>";
2847 $cdel = "(<small>$cdel</small>) ";
2849 # Show user links if allowed to see them. Normally they
2850 # are hidden regardless, but since we can already see the text here...
2851 $userlinks = $sk->revUserTools( $revision, false );
2853 $m = wfMsg( 'revision-info-current' );
2854 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2855 ?
'revision-info-current'
2858 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2860 "\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";
2861 $wgOut->setSubtitle( $r );
2865 * This function is called right before saving the wikitext,
2866 * so we can do things like signatures and links-in-context.
2868 * @param string $text
2870 function preSaveTransform( $text ) {
2871 global $wgParser, $wgUser;
2872 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2875 /* Caching functions */
2878 * checkLastModified returns true if it has taken care of all
2879 * output to the client that is necessary for this request.
2880 * (that is, it has sent a cached version of the page)
2882 function tryFileCache() {
2883 static $called = false;
2885 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2889 if($this->isFileCacheable()) {
2890 $touched = $this->mTouched
;
2891 $cache = new HTMLFileCache( $this->mTitle
);
2892 if($cache->isFileCacheGood( $touched )) {
2893 wfDebug( "Article::tryFileCache(): about to load file\n" );
2894 $cache->loadFromFileCache();
2897 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2898 ob_start( array(&$cache, 'saveToFileCache' ) );
2901 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2906 * Check if the page can be cached
2909 function isFileCacheable() {
2910 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2911 $action = $wgRequest->getVal( 'action' );
2912 $oldid = $wgRequest->getVal( 'oldid' );
2913 $diff = $wgRequest->getVal( 'diff' );
2914 $redirect = $wgRequest->getVal( 'redirect' );
2915 $printable = $wgRequest->getVal( 'printable' );
2916 $page = $wgRequest->getVal( 'page' );
2918 //check for non-standard user language; this covers uselang,
2919 //and extensions for auto-detecting user language.
2920 $ulang = $wgLang->getCode();
2921 $clang = $wgContLang->getCode();
2923 $cacheable = $wgUseFileCache
2924 && (!$wgShowIPinHeader)
2925 && ($this->getID() != 0)
2926 && ($wgUser->isAnon())
2927 && (!$wgUser->getNewtalk())
2928 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2929 && (empty( $action ) ||
$action == 'view')
2932 && (!isset($redirect))
2933 && (!isset($printable))
2935 && (!$this->mRedirectedFrom
)
2936 && ($ulang === $clang);
2939 //extension may have reason to disable file caching on some pages.
2940 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2947 * Loads page_touched and returns a value indicating if it should be used
2950 function checkTouched() {
2951 if( !$this->mDataLoaded
) {
2952 $this->loadPageData();
2954 return !$this->mIsRedirect
;
2958 * Get the page_touched field
2960 function getTouched() {
2961 # Ensure that page data has been loaded
2962 if( !$this->mDataLoaded
) {
2963 $this->loadPageData();
2965 return $this->mTouched
;
2969 * Get the page_latest field
2971 function getLatest() {
2972 if ( !$this->mDataLoaded
) {
2973 $this->loadPageData();
2975 return $this->mLatest
;
2979 * Edit an article without doing all that other stuff
2980 * The article must already exist; link tables etc
2981 * are not updated, caches are not flushed.
2983 * @param string $text text submitted
2984 * @param string $comment comment submitted
2985 * @param bool $minor whereas it's a minor modification
2987 function quickEdit( $text, $comment = '', $minor = 0 ) {
2988 wfProfileIn( __METHOD__
);
2990 $dbw = wfGetDB( DB_MASTER
);
2992 $revision = new Revision( array(
2993 'page' => $this->getId(),
2995 'comment' => $comment,
2996 'minor_edit' => $minor ?
1 : 0,
2998 $revision->insertOn( $dbw );
2999 $this->updateRevisionOn( $dbw, $revision );
3002 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3004 wfProfileOut( __METHOD__
);
3008 * Used to increment the view counter
3011 * @param integer $id article id
3013 function incViewCount( $id ) {
3014 $id = intval( $id );
3015 global $wgHitcounterUpdateFreq, $wgDBtype;
3017 $dbw = wfGetDB( DB_MASTER
);
3018 $pageTable = $dbw->tableName( 'page' );
3019 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3020 $acchitsTable = $dbw->tableName( 'acchits' );
3022 if( $wgHitcounterUpdateFreq <= 1 ) {
3023 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3027 # Not important enough to warrant an error page in case of failure
3028 $oldignore = $dbw->ignoreErrors( true );
3030 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3032 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3033 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3034 # Most of the time (or on SQL errors), skip row count check
3035 $dbw->ignoreErrors( $oldignore );
3039 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3040 $row = $dbw->fetchObject( $res );
3041 $rown = intval( $row->n
);
3042 if( $rown >= $wgHitcounterUpdateFreq ){
3043 wfProfileIn( 'Article::incViewCount-collect' );
3044 $old_user_abort = ignore_user_abort( true );
3046 if ($wgDBtype == 'mysql')
3047 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3048 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3049 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3050 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3052 $dbw->query("DELETE FROM $hitcounterTable");
3053 if ($wgDBtype == 'mysql') {
3054 $dbw->query('UNLOCK TABLES');
3055 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3056 'WHERE page_id = hc_id');
3059 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3060 "FROM $acchitsTable WHERE page_id = hc_id");
3062 $dbw->query("DROP TABLE $acchitsTable");
3064 ignore_user_abort( $old_user_abort );
3065 wfProfileOut( 'Article::incViewCount-collect' );
3067 $dbw->ignoreErrors( $oldignore );
3071 * The onArticle*() functions are supposed to be a kind of hooks
3072 * which should be called whenever any of the specified actions
3075 * This is a good place to put code to clear caches, for instance.
3077 * This is called on page move and undelete, as well as edit
3079 * @param $title_obj a title object
3082 static function onArticleCreate($title) {
3083 # The talk page isn't in the regular link tables, so we need to update manually:
3084 if ( $title->isTalkPage() ) {
3085 $other = $title->getSubjectPage();
3087 $other = $title->getTalkPage();
3089 $other->invalidateCache();
3090 $other->purgeSquid();
3092 $title->touchLinks();
3093 $title->purgeSquid();
3094 $title->deleteTitleProtection();
3097 static function onArticleDelete( $title ) {
3098 global $wgUseFileCache, $wgMessageCache;
3100 // Update existence markers on article/talk tabs...
3101 if( $title->isTalkPage() ) {
3102 $other = $title->getSubjectPage();
3104 $other = $title->getTalkPage();
3106 $other->invalidateCache();
3107 $other->purgeSquid();
3109 $title->touchLinks();
3110 $title->purgeSquid();
3113 if ( $wgUseFileCache ) {
3114 $cm = new HTMLFileCache( $title );
3115 @unlink
( $cm->fileCacheName() );
3119 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3120 $wgMessageCache->replace( $title->getDBkey(), false );
3123 if( $title->getNamespace() == NS_IMAGE
) {
3124 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3125 $update->doUpdate();
3128 if( $title->getNamespace() == NS_USER_TALK
) {
3129 $user = User
::newFromName( $title->getText(), false );
3130 $user->setNewtalk( false );
3135 * Purge caches on page update etc
3137 static function onArticleEdit( $title ) {
3138 global $wgDeferredUpdateList, $wgUseFileCache;
3140 // Invalidate caches of articles which include this page
3141 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3143 // Invalidate the caches of all pages which redirect here
3144 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3146 # Purge squid for this page only
3147 $title->purgeSquid();
3150 if ( $wgUseFileCache ) {
3151 $cm = new HTMLFileCache( $title );
3152 @unlink
( $cm->fileCacheName() );
3159 * Overriden by ImagePage class, only present here to avoid a fatal error
3160 * Called for ?action=revert
3162 public function revert(){
3164 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3168 * Info about this page
3169 * Called for ?action=info when $wgAllowPageInfo is on.
3174 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3176 if ( !$wgAllowPageInfo ) {
3177 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3181 $page = $this->mTitle
->getSubjectPage();
3183 $wgOut->setPagetitle( $page->getPrefixedText() );
3184 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3185 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3187 if( !$this->mTitle
->exists() ) {
3188 $wgOut->addHtml( '<div class="noarticletext">' );
3189 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3190 // This doesn't quite make sense; the user is asking for
3191 // information about the _page_, not the message... -- RC
3192 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3194 $msg = $wgUser->isLoggedIn()
3196 : 'noarticletextanon';
3197 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3199 $wgOut->addHtml( '</div>' );
3201 $dbr = wfGetDB( DB_SLAVE
);
3203 'wl_title' => $page->getDBkey(),
3204 'wl_namespace' => $page->getNamespace() );
3205 $numwatchers = $dbr->selectField(
3210 $this->getSelectOptions() );
3212 $pageInfo = $this->pageCountInfo( $page );
3213 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3215 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3216 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3218 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3220 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3222 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3224 $wgOut->addHTML( '</ul>' );
3230 * Return the total number of edits and number of unique editors
3231 * on a given page. If page does not exist, returns false.
3233 * @param Title $title
3237 function pageCountInfo( $title ) {
3238 $id = $title->getArticleId();
3243 $dbr = wfGetDB( DB_SLAVE
);
3245 $rev_clause = array( 'rev_page' => $id );
3247 $edits = $dbr->selectField(
3252 $this->getSelectOptions() );
3254 $authors = $dbr->selectField(
3256 'COUNT(DISTINCT rev_user_text)',
3259 $this->getSelectOptions() );
3261 return array( 'edits' => $edits, 'authors' => $authors );
3265 * Return a list of templates used by this article.
3266 * Uses the templatelinks table
3268 * @return array Array of Title objects
3270 function getUsedTemplates() {
3272 $id = $this->mTitle
->getArticleID();
3277 $dbr = wfGetDB( DB_SLAVE
);
3278 $res = $dbr->select( array( 'templatelinks' ),
3279 array( 'tl_namespace', 'tl_title' ),
3280 array( 'tl_from' => $id ),
3281 'Article:getUsedTemplates' );
3282 if ( false !== $res ) {
3283 if ( $dbr->numRows( $res ) ) {
3284 while ( $row = $dbr->fetchObject( $res ) ) {
3285 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3289 $dbr->freeResult( $res );
3294 * Returns a list of hidden categories this page is a member of.
3295 * Uses the page_props and categorylinks tables.
3297 * @return array Array of Title objects
3299 function getHiddenCategories() {
3301 $id = $this->mTitle
->getArticleID();
3306 $dbr = wfGetDB( DB_SLAVE
);
3307 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3309 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3310 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3311 'Article:getHiddenCategories' );
3312 if ( false !== $res ) {
3313 if ( $dbr->numRows( $res ) ) {
3314 while ( $row = $dbr->fetchObject( $res ) ) {
3315 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3319 $dbr->freeResult( $res );
3324 * Return an applicable autosummary if one exists for the given edit.
3325 * @param string $oldtext The previous text of the page.
3326 * @param string $newtext The submitted text of the page.
3327 * @param bitmask $flags A bitmask of flags submitted for the edit.
3328 * @return string An appropriate autosummary, or an empty string.
3330 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3331 # Decide what kind of autosummary is needed.
3333 # Redirect autosummaries
3334 $rt = Title
::newFromRedirect( $newtext );
3335 if( is_object( $rt ) ) {
3336 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3339 # New page autosummaries
3340 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3341 # If they're making a new article, give its text, truncated, in the summary.
3343 $truncatedtext = $wgContLang->truncate(
3344 str_replace("\n", ' ', $newtext),
3345 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3347 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3350 # Blanking autosummaries
3351 if( $oldtext != '' && $newtext == '' ) {
3352 return wfMsgForContent('autosumm-blank');
3353 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3354 # Removing more than 90% of the article
3356 $truncatedtext = $wgContLang->truncate(
3358 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3361 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3364 # If we reach this point, there's no applicable autosummary for our case, so our
3365 # autosummary is empty.
3370 * Add the primary page-view wikitext to the output buffer
3371 * Saves the text into the parser cache if possible.
3372 * Updates templatelinks if it is out of date.
3374 * @param string $text
3375 * @param bool $cache
3377 public function outputWikiText( $text, $cache = true ) {
3378 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3380 $popts = $wgOut->parserOptions();
3381 $popts->setTidy(true);
3382 $popts->enableLimitReport();
3383 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3384 $popts, true, true, $this->getRevIdFetched() );
3385 $popts->setTidy(false);
3386 $popts->enableLimitReport( false );
3387 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3388 $parserCache = ParserCache
::singleton();
3389 $parserCache->save( $parserOutput, $this, $wgUser );
3392 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3393 // templatelinks table may have become out of sync,
3394 // especially if using variable-based transclusions.
3395 // For paranoia, check if things have changed and if
3396 // so apply updates to the database. This will ensure
3397 // that cascaded protections apply as soon as the changes
3400 # Get templates from templatelinks
3401 $id = $this->mTitle
->getArticleID();
3403 $tlTemplates = array();
3405 $dbr = wfGetDB( DB_SLAVE
);
3406 $res = $dbr->select( array( 'templatelinks' ),
3407 array( 'tl_namespace', 'tl_title' ),
3408 array( 'tl_from' => $id ),
3409 'Article:getUsedTemplates' );
3413 if ( false !== $res ) {
3414 if ( $dbr->numRows( $res ) ) {
3415 while ( $row = $dbr->fetchObject( $res ) ) {
3416 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3421 # Get templates from parser output.
3422 $poTemplates_allns = $parserOutput->getTemplates();
3424 $poTemplates = array ();
3425 foreach ( $poTemplates_allns as $ns_templates ) {
3426 $poTemplates = array_merge( $poTemplates, $ns_templates );
3430 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3432 if ( count( $templates_diff ) > 0 ) {
3433 # Whee, link updates time.
3434 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3436 $dbw = wfGetDb( DB_MASTER
);
3445 $wgOut->addParserOutput( $parserOutput );
3449 * Update all the appropriate counts in the category table, given that
3450 * we've added the categories $added and deleted the categories $deleted.
3452 * @param $added array The names of categories that were added
3453 * @param $deleted array The names of categories that were deleted
3456 public function updateCategoryCounts( $added, $deleted ) {
3457 $ns = $this->mTitle
->getNamespace();
3458 $dbw = wfGetDB( DB_MASTER
);
3460 # First make sure the rows exist. If one of the "deleted" ones didn't
3461 # exist, we might legitimately not create it, but it's simpler to just
3462 # create it and then give it a negative value, since the value is bogus
3465 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3466 $insertCats = array_merge( $added, $deleted );
3467 if( !$insertCats ) {
3468 # Okay, nothing to do
3471 $insertRows = array();
3472 foreach( $insertCats as $cat ) {
3473 $insertRows[] = array( 'cat_title' => $cat );
3475 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3477 $addFields = array( 'cat_pages = cat_pages + 1' );
3478 $removeFields = array( 'cat_pages = cat_pages - 1' );
3479 if( $ns == NS_CATEGORY
) {
3480 $addFields[] = 'cat_subcats = cat_subcats + 1';
3481 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3482 } elseif( $ns == NS_IMAGE
) {
3483 $addFields[] = 'cat_files = cat_files + 1';
3484 $removeFields[] = 'cat_files = cat_files - 1';
3491 array( 'cat_title' => $added ),
3499 array( 'cat_title' => $deleted ),