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 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 * @param $limit Integer: default 0.
639 * @param $offset Integer: default 0.
641 function getContributors($limit = 0, $offset = 0) {
642 # XXX: this is expensive; cache this info somewhere.
645 $dbr = wfGetDB( DB_SLAVE
);
646 $revTable = $dbr->tableName( 'revision' );
647 $userTable = $dbr->tableName( 'user' );
648 $user = $this->getUser();
649 $pageId = $this->getId();
651 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
652 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
653 WHERE rev_page = $pageId
654 AND rev_user != $user
655 GROUP BY rev_user, rev_user_text, user_real_name
656 ORDER BY timestamp DESC";
658 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
659 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
661 $sql .= ' '. $this->getSelectOptions();
663 $res = $dbr->query($sql, __METHOD__
);
665 while ( $line = $dbr->fetchObject( $res ) ) {
666 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
669 $dbr->freeResult($res);
674 * This is the default action of the script: just view the page of
678 global $wgUser, $wgOut, $wgRequest, $wgContLang;
679 global $wgEnableParserCache, $wgStylePath, $wgParser;
680 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
681 global $wgDefaultRobotPolicy;
682 $sk = $wgUser->getSkin();
684 wfProfileIn( __METHOD__
);
686 $parserCache = ParserCache
::singleton();
687 $ns = $this->mTitle
->getNamespace(); # shortcut
689 # Get variables from query string
690 $oldid = $this->getOldID();
692 # getOldID may want us to redirect somewhere else
693 if ( $this->mRedirectUrl
) {
694 $wgOut->redirect( $this->mRedirectUrl
);
695 wfProfileOut( __METHOD__
);
699 $diff = $wgRequest->getVal( 'diff' );
700 $rcid = $wgRequest->getVal( 'rcid' );
701 $rdfrom = $wgRequest->getVal( 'rdfrom' );
702 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
703 $purge = $wgRequest->getVal( 'action' ) == 'purge';
705 $wgOut->setArticleFlag( true );
707 # Discourage indexing of printable versions, but encourage following
708 if( $wgOut->isPrintable() ) {
709 $policy = 'noindex,follow';
710 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
711 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
712 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
713 # Honour customised robot policies for this namespace
714 $policy = $wgNamespaceRobotPolicies[$ns];
716 $policy = $wgDefaultRobotPolicy;
718 $wgOut->setRobotPolicy( $policy );
720 # If we got diff and oldid in the query, we want to see a
721 # diff page instead of the article.
723 if ( !is_null( $diff ) ) {
724 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
726 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
727 // DifferenceEngine directly fetched the revision:
728 $this->mRevIdFetched
= $de->mNewid
;
729 $de->showDiffPage( $diffOnly );
731 // Needed to get the page's current revision
732 $this->loadPageData();
733 if( $diff == 0 ||
$diff == $this->mLatest
) {
734 # Run view updates for current revision only
735 $this->viewUpdates();
737 wfProfileOut( __METHOD__
);
741 if ( empty( $oldid ) && $this->checkTouched() ) {
742 $wgOut->setETag($parserCache->getETag($this, $wgUser));
744 if( $wgOut->checkLastModified( $this->mTouched
) ){
745 wfProfileOut( __METHOD__
);
747 } else if ( $this->tryFileCache() ) {
748 # tell wgOut that output is taken care of
750 $this->viewUpdates();
751 wfProfileOut( __METHOD__
);
756 # Should the parser cache be used?
757 $pcache = $this->useParserCache( $oldid );
758 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
759 if ( $wgUser->getOption( 'stubthreshold' ) ) {
760 wfIncrStats( 'pcache_miss_stub' );
763 $wasRedirected = false;
764 if ( isset( $this->mRedirectedFrom
) ) {
765 // This is an internally redirected page view.
766 // We'll need a backlink to the source page for navigation.
767 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
768 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
769 $s = wfMsg( 'redirectedfrom', $redir );
770 $wgOut->setSubtitle( $s );
772 // Set the fragment if one was specified in the redirect
773 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
774 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
775 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
777 $wasRedirected = true;
779 } elseif ( !empty( $rdfrom ) ) {
780 // This is an externally redirected view, from some other wiki.
781 // If it was reported from a trusted site, supply a backlink.
782 global $wgRedirectSources;
783 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
784 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
785 $s = wfMsg( 'redirectedfrom', $redir );
786 $wgOut->setSubtitle( $s );
787 $wasRedirected = true;
792 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
794 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
795 // Ensure that UI elements requiring revision ID have
796 // the correct version information.
797 $wgOut->setRevisionId( $this->mLatest
);
801 # Fetch content and check for errors
802 if ( !$outputDone ) {
803 $text = $this->getContent();
804 if ( $text === false ) {
805 # Failed to load, replace text with error message
806 $t = $this->mTitle
->getPrefixedText();
808 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
809 $text = wfMsg( 'missing-article', $t, $d );
811 $text = wfMsg( 'noarticletext' );
815 # Another whitelist check in case oldid is altering the title
816 if ( !$this->mTitle
->userCanRead() ) {
817 $wgOut->loginToUse();
819 wfProfileOut( __METHOD__
);
823 # We're looking at an old revision
824 if ( !empty( $oldid ) ) {
825 $wgOut->setRobotPolicy( 'noindex,nofollow' );
826 if( is_null( $this->mRevision
) ) {
827 // FIXME: This would be a nice place to load the 'no such page' text.
829 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
830 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
831 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
832 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
833 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
834 wfProfileOut( __METHOD__
);
837 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
838 // and we are allowed to see...
844 $wgOut->setRevisionId( $this->getRevIdFetched() );
846 // Pages containing custom CSS or JavaScript get special treatment
847 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
848 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
849 // Give hooks a chance to customise the output
850 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
851 // Wrap the whole lot in a <pre> and don't parse
853 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
854 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
855 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
856 $wgOut->addHtml( "\n</pre>\n" );
858 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
859 # Don't append the subtitle if this was an old revision
860 $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() );
861 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
862 $wgOut->addParserOutputNoText( $parseout );
863 } else if ( $pcache ) {
864 # Display content and save to parser cache
865 $this->outputWikiText( $text );
867 # Display content, don't attempt to save to parser cache
868 # Don't show section-edit links on old revisions... this way lies madness.
869 if( !$this->isCurrent() ) {
870 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
872 # Display content and don't save to parser cache
873 # With timing hack -- TS 2006-07-26
875 $this->outputWikiText( $text, false );
880 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
881 $this->mTitle
->getPrefixedDBkey()));
884 if( !$this->isCurrent() ) {
885 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
889 /* title may have been set from the cache */
890 $t = $wgOut->getPageTitle();
892 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
895 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
896 if( $ns == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
897 $wgOut->addWikiMsg('anontalkpagetext');
900 # If we have been passed an &rcid= parameter, we want to give the user a
901 # chance to mark this new article as patrolled.
902 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
904 "<div class='patrollink'>" .
905 wfMsgHtml( 'markaspatrolledlink',
906 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
907 "action=markpatrolled&rcid=$rcid" )
914 if ($wgUseTrackbacks)
915 $this->addTrackbacks();
917 $this->viewUpdates();
918 wfProfileOut( __METHOD__
);
922 * Should the parser cache be used?
924 protected function useParserCache( $oldid ) {
925 global $wgUser, $wgEnableParserCache;
927 return $wgEnableParserCache
928 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
931 && !$this->mTitle
->isCssOrJsPage()
932 && !$this->mTitle
->isCssJsSubpage();
935 protected function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
936 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
939 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
940 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
942 if( $appendSubtitle ) {
943 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
945 $sk = $wgUser->getSkin();
947 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
949 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
951 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
952 '<span class="redirectText">'.$link.'</span>' );
956 function addTrackbacks() {
957 global $wgOut, $wgUser;
959 $dbr = wfGetDB(DB_SLAVE
);
961 /* FROM */ 'trackbacks',
962 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
963 /* WHERE */ array('tb_page' => $this->getID())
966 if (!$dbr->numrows($tbs))
970 while ($o = $dbr->fetchObject($tbs)) {
972 if ($wgUser->isAllowed( 'trackback' )) {
973 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
974 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
975 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
978 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
985 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
988 function deletetrackback() {
989 global $wgUser, $wgRequest, $wgOut, $wgTitle;
991 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
992 $wgOut->addWikiMsg( 'sessionfailure' );
996 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
998 if (count($permission_errors)>0)
1000 $wgOut->showPermissionsErrorPage( $permission_errors );
1004 $db = wfGetDB(DB_MASTER
);
1005 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1006 $wgTitle->invalidateCache();
1007 $wgOut->addWikiMsg('trackbackdeleteok');
1013 $wgOut->setArticleBodyOnly(true);
1018 * Handle action=purge
1021 global $wgUser, $wgRequest, $wgOut;
1023 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1024 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1028 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1029 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1030 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1031 $msg = str_replace( '$1',
1032 "<form method=\"post\" action=\"$action\">\n" .
1033 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1034 "</form>\n", $msg );
1036 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1037 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1038 $wgOut->addHTML( $msg );
1043 * Perform the actions of a page purging
1045 function doPurge() {
1047 // Invalidate the cache
1048 $this->mTitle
->invalidateCache();
1050 if ( $wgUseSquid ) {
1051 // Commit the transaction before the purge is sent
1052 $dbw = wfGetDB( DB_MASTER
);
1053 $dbw->immediateCommit();
1056 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1057 $update->doUpdate();
1059 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1060 global $wgMessageCache;
1061 if ( $this->getID() == 0 ) {
1064 $text = $this->getContent();
1066 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1072 * Insert a new empty page record for this article.
1073 * This *must* be followed up by creating a revision
1074 * and running $this->updateToLatest( $rev_id );
1075 * or else the record will be left in a funky state.
1076 * Best if all done inside a transaction.
1078 * @param Database $dbw
1079 * @return int The newly created page_id key
1082 function insertOn( $dbw ) {
1083 wfProfileIn( __METHOD__
);
1085 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1086 $dbw->insert( 'page', array(
1087 'page_id' => $page_id,
1088 'page_namespace' => $this->mTitle
->getNamespace(),
1089 'page_title' => $this->mTitle
->getDBkey(),
1090 'page_counter' => 0,
1091 'page_restrictions' => '',
1092 'page_is_redirect' => 0, # Will set this shortly...
1094 'page_random' => wfRandom(),
1095 'page_touched' => $dbw->timestamp(),
1096 'page_latest' => 0, # Fill this in shortly...
1097 'page_len' => 0, # Fill this in shortly...
1099 $newid = $dbw->insertId();
1101 $this->mTitle
->resetArticleId( $newid );
1103 wfProfileOut( __METHOD__
);
1108 * Update the page record to point to a newly saved revision.
1110 * @param Database $dbw
1111 * @param Revision $revision For ID number, and text used to set
1112 length and redirect status fields
1113 * @param int $lastRevision If given, will not overwrite the page field
1114 * when different from the currently set value.
1115 * Giving 0 indicates the new page flag should
1117 * @param bool $lastRevIsRedirect If given, will optimize adding and
1118 * removing rows in redirect table.
1119 * @return bool true on success, false on failure
1122 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1123 wfProfileIn( __METHOD__
);
1125 $text = $revision->getText();
1126 $rt = Title
::newFromRedirect( $text );
1128 $conditions = array( 'page_id' => $this->getId() );
1129 if( !is_null( $lastRevision ) ) {
1130 # An extra check against threads stepping on each other
1131 $conditions['page_latest'] = $lastRevision;
1134 $dbw->update( 'page',
1136 'page_latest' => $revision->getId(),
1137 'page_touched' => $dbw->timestamp(),
1138 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1139 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1140 'page_len' => strlen( $text ),
1145 $result = $dbw->affectedRows() != 0;
1148 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1151 wfProfileOut( __METHOD__
);
1156 * Add row to the redirect table if this is a redirect, remove otherwise.
1158 * @param Database $dbw
1159 * @param $redirectTitle a title object pointing to the redirect target,
1160 * or NULL if this is not a redirect
1161 * @param bool $lastRevIsRedirect If given, will optimize adding and
1162 * removing rows in redirect table.
1163 * @return bool true on success, false on failure
1166 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1168 // Always update redirects (target link might have changed)
1169 // Update/Insert if we don't know if the last revision was a redirect or not
1170 // Delete if changing from redirect to non-redirect
1171 $isRedirect = !is_null($redirectTitle);
1172 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1174 wfProfileIn( __METHOD__
);
1178 // This title is a redirect, Add/Update row in the redirect table
1179 $set = array( /* SET */
1180 'rd_namespace' => $redirectTitle->getNamespace(),
1181 'rd_title' => $redirectTitle->getDBkey(),
1182 'rd_from' => $this->getId(),
1185 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1187 // This is not a redirect, remove row from redirect table
1188 $where = array( 'rd_from' => $this->getId() );
1189 $dbw->delete( 'redirect', $where, __METHOD__
);
1192 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1193 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1194 wfProfileOut( __METHOD__
);
1195 return ( $dbw->affectedRows() != 0 );
1202 * If the given revision is newer than the currently set page_latest,
1203 * update the page record. Otherwise, do nothing.
1205 * @param Database $dbw
1206 * @param Revision $revision
1208 function updateIfNewerOn( &$dbw, $revision ) {
1209 wfProfileIn( __METHOD__
);
1211 $row = $dbw->selectRow(
1212 array( 'revision', 'page' ),
1213 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1215 'page_id' => $this->getId(),
1216 'page_latest=rev_id' ),
1219 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1220 wfProfileOut( __METHOD__
);
1223 $prev = $row->rev_id
;
1224 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1226 # No or missing previous revision; mark the page as new
1228 $lastRevIsRedirect = null;
1231 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1232 wfProfileOut( __METHOD__
);
1237 * @return string Complete article text, or null if error
1239 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1240 wfProfileIn( __METHOD__
);
1242 if( $section == '' ) {
1243 // Whole-page edit; let the text through unmolested.
1245 if( is_null( $edittime ) ) {
1246 $rev = Revision
::newFromTitle( $this->mTitle
);
1248 $dbw = wfGetDB( DB_MASTER
);
1249 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1251 if( is_null( $rev ) ) {
1252 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1253 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1256 $oldtext = $rev->getText();
1258 if( $section == 'new' ) {
1259 # Inserting a new section
1260 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1261 $text = strlen( trim( $oldtext ) ) > 0
1262 ?
"{$oldtext}\n\n{$subject}{$text}"
1263 : "{$subject}{$text}";
1265 # Replacing an existing section; roll out the big guns
1267 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1272 wfProfileOut( __METHOD__
);
1277 * @deprecated use Article::doEdit()
1279 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1280 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1281 ( $isminor ? EDIT_MINOR
: 0 ) |
1282 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1283 ( $bot ? EDIT_FORCE_BOT
: 0 );
1285 # If this is a comment, add the summary as headline
1286 if ( $comment && $summary != "" ) {
1287 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1290 $this->doEdit( $text, $summary, $flags );
1292 $dbw = wfGetDB( DB_MASTER
);
1294 if (!$this->mTitle
->userIsWatching()) {
1300 if ( $this->mTitle
->userIsWatching() ) {
1306 $this->doRedirect( $this->isRedirect( $text ) );
1310 * @deprecated use Article::doEdit()
1312 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1313 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1314 ( $minor ? EDIT_MINOR
: 0 ) |
1315 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1317 $good = $this->doEdit( $text, $summary, $flags );
1319 $dbw = wfGetDB( DB_MASTER
);
1321 if (!$this->mTitle
->userIsWatching()) {
1327 if ( $this->mTitle
->userIsWatching() ) {
1334 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1335 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1337 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1345 * Change an existing article or create a new article. Updates RC and all necessary caches,
1346 * optionally via the deferred update array.
1348 * $wgUser must be set before calling this function.
1350 * @param string $text New text
1351 * @param string $summary Edit summary
1352 * @param integer $flags bitfield:
1354 * Article is known or assumed to be non-existent, create a new one
1356 * Article is known or assumed to be pre-existing, update it
1358 * Mark this edit minor, if the user is allowed to do so
1360 * Do not log the change in recentchanges
1362 * Mark the edit a "bot" edit regardless of user rights
1363 * EDIT_DEFER_UPDATES
1364 * Defer some of the updates until the end of index.php
1366 * Fill in blank summaries with generated text where possible
1368 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1369 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1370 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1371 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1372 * to MediaWiki's performance-optimised locking strategy.
1373 * @param $baseRevId, the revision ID this edit was based off, if any
1375 * @return bool success
1377 function doEdit( $text, $summary, $flags = 0, $baseRevId = false ) {
1378 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1380 wfProfileIn( __METHOD__
);
1383 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1384 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1386 $flags |
= EDIT_UPDATE
;
1392 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1393 &$summary, $flags & EDIT_MINOR
,
1394 null, null, &$flags ) ) )
1396 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1397 wfProfileOut( __METHOD__
);
1401 # Silently ignore EDIT_MINOR if not allowed
1402 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1403 $bot = $flags & EDIT_FORCE_BOT
;
1405 $oldtext = $this->getContent();
1406 $oldsize = strlen( $oldtext );
1408 # Provide autosummaries if one is not provided and autosummaries are enabled.
1409 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1410 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1413 $editInfo = $this->prepareTextForEdit( $text );
1414 $text = $editInfo->pst
;
1415 $newsize = strlen( $text );
1417 $dbw = wfGetDB( DB_MASTER
);
1418 $now = wfTimestampNow();
1420 if ( $flags & EDIT_UPDATE
) {
1421 # Update article, but only if changed.
1423 # Make sure the revision is either completely inserted or not inserted at all
1424 if( !$wgDBtransactions ) {
1425 $userAbort = ignore_user_abort( true );
1431 $changed = ( strcmp( $text, $oldtext ) != 0 );
1434 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1435 - (int)$this->isCountable( $oldtext );
1436 $this->mTotalAdjustment
= 0;
1438 $lastRevision = $dbw->selectField(
1439 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1441 if ( !$lastRevision ) {
1442 # Article gone missing
1443 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1444 wfProfileOut( __METHOD__
);
1448 $revision = new Revision( array(
1449 'page' => $this->getId(),
1450 'comment' => $summary,
1451 'minor_edit' => $isminor,
1453 'parent_id' => $lastRevision
1457 $revisionId = $revision->insertOn( $dbw );
1460 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1463 /* Belated edit conflict! Run away!! */
1467 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1469 # Update recentchanges
1470 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1471 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1472 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1475 # Mark as patrolled if the user can do so
1476 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1477 RecentChange
::markPatrolled( $rcid );
1478 PatrolLog
::record( $rcid, true );
1481 $wgUser->incEditCount();
1486 // Keep the same revision ID, but do some updates on it
1487 $revisionId = $this->getRevIdFetched();
1488 // Update page_touched, this is usually implicit in the page update
1489 // Other cache updates are done in onArticleEdit()
1490 $this->mTitle
->invalidateCache();
1493 if( !$wgDBtransactions ) {
1494 ignore_user_abort( $userAbort );
1498 # Invalidate cache of this article and all pages using this article
1499 # as a template. Partly deferred.
1500 Article
::onArticleEdit( $this->mTitle
);
1502 # Update links tables, site stats, etc.
1503 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1506 # Create new article
1508 # Set statistics members
1509 # We work out if it's countable after PST to avoid counter drift
1510 # when articles are created with {{subst:}}
1511 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1512 $this->mTotalAdjustment
= 1;
1516 # Add the page record; stake our claim on this title!
1517 # This will fail with a database query exception if the article already exists
1518 $newid = $this->insertOn( $dbw );
1520 # Save the revision text...
1521 $revision = new Revision( array(
1523 'comment' => $summary,
1524 'minor_edit' => $isminor,
1527 $revisionId = $revision->insertOn( $dbw );
1529 $this->mTitle
->resetArticleID( $newid );
1531 # Update the page record with revision data
1532 $this->updateRevisionOn( $dbw, $revision, 0 );
1534 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1536 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1537 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1538 '', strlen( $text ), $revisionId );
1539 # Mark as patrolled if the user can
1540 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1541 RecentChange
::markPatrolled( $rcid );
1542 PatrolLog
::record( $rcid, true );
1545 $wgUser->incEditCount();
1548 # Update links, etc.
1549 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1552 Article
::onArticleCreate( $this->mTitle
);
1554 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1555 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1558 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1563 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1564 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1567 wfProfileOut( __METHOD__
);
1572 * @deprecated wrapper for doRedirect
1574 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1575 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1579 * Output a redirect back to the article.
1580 * This is typically used after an edit.
1582 * @param boolean $noRedir Add redirect=no
1583 * @param string $sectionAnchor section to redirect to, including "#"
1584 * @param string $extraQuery, extra query params
1586 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1589 $query = 'redirect=no';
1591 $query .= "&$query";
1593 $query = $extraQuery;
1595 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1599 * Mark this particular edit/page as patrolled
1601 function markpatrolled() {
1602 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1603 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1605 # Check patrol config options
1607 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1608 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1612 # If we haven't been given an rc_id value, we can't do anything
1613 $rcid = (int) $wgRequest->getVal('rcid');
1614 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1615 if ( is_null ( $rc ) )
1617 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1621 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1622 // Only new pages can be patrolled if the general patrolling is off....???
1623 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1625 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1630 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1632 if (count($permission_errors)>0)
1634 $wgOut->showPermissionsErrorPage( $permission_errors );
1638 # Handle the 'MarkPatrolled' hook
1639 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1643 #It would be nice to see where the user had actually come from, but for now just guess
1644 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1645 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1647 # If it's left up to us, check that the user is allowed to patrol this edit
1648 # If the user has the "autopatrol" right, then we'll assume there are no
1649 # other conditions stopping them doing so
1650 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1651 $rc = RecentChange
::newFromId( $rcid );
1652 # Graceful error handling, as we've done before here...
1653 # (If the recent change doesn't exist, then it doesn't matter whether
1654 # the user is allowed to patrol it or not; nothing is going to happen
1655 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1656 # The user made this edit, and can't patrol it
1657 # Tell them so, and then back off
1658 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1659 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1660 $wgOut->returnToMain( false, $return );
1665 # Check that the revision isn't patrolled already
1666 # Prevents duplicate log entries
1667 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1668 # Mark the edit as patrolled
1669 RecentChange
::markPatrolled( $rcid );
1670 PatrolLog
::record( $rcid );
1671 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1675 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1676 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1677 $wgOut->returnToMain( false, $return );
1681 * User-interface handler for the "watch" action
1686 global $wgUser, $wgOut;
1688 if ( $wgUser->isAnon() ) {
1689 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1692 if ( wfReadOnly() ) {
1693 $wgOut->readOnlyPage();
1697 if( $this->doWatch() ) {
1698 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1699 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1701 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1704 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1708 * Add this page to $wgUser's watchlist
1709 * @return bool true on successful watch operation
1711 function doWatch() {
1713 if( $wgUser->isAnon() ) {
1717 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1718 $wgUser->addWatch( $this->mTitle
);
1720 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1727 * User interface handler for the "unwatch" action.
1729 function unwatch() {
1731 global $wgUser, $wgOut;
1733 if ( $wgUser->isAnon() ) {
1734 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1737 if ( wfReadOnly() ) {
1738 $wgOut->readOnlyPage();
1742 if( $this->doUnwatch() ) {
1743 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1744 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1746 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1749 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1753 * Stop watching a page
1754 * @return bool true on successful unwatch
1756 function doUnwatch() {
1758 if( $wgUser->isAnon() ) {
1762 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1763 $wgUser->removeWatch( $this->mTitle
);
1765 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1772 * action=protect handler
1774 function protect() {
1775 $form = new ProtectionForm( $this );
1780 * action=unprotect handler (alias)
1782 function unprotect() {
1787 * Update the article's restriction field, and leave a log entry.
1789 * @param array $limit set of restriction keys
1790 * @param string $reason
1791 * @return bool true on success
1793 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1794 global $wgUser, $wgRestrictionTypes, $wgContLang;
1796 $id = $this->mTitle
->getArticleID();
1797 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1805 // Take this opportunity to purge out expired restrictions
1806 Title
::purgeExpiredRestrictions();
1808 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1809 # we expect a single selection, but the schema allows otherwise.
1811 foreach( $wgRestrictionTypes as $action )
1812 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1814 $current = Article
::flattenRestrictions( $current );
1815 $updated = Article
::flattenRestrictions( $limit );
1817 $changed = ( $current != $updated );
1818 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1819 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1820 $protect = ( $updated != '' );
1822 # If nothing's changed, do nothing
1824 global $wgGroupPermissions;
1825 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1827 $dbw = wfGetDB( DB_MASTER
);
1829 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1831 $expiry_description = '';
1832 if ( $encodedExpiry != 'infinity' ) {
1833 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1836 # Prepare a null revision to be added to the history
1837 $modified = $current != '' && $protect;
1839 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1841 $comment_type = 'unprotectedarticle';
1843 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1845 # Only restrictions with the 'protect' right can cascade...
1846 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1847 foreach( $limit as $action => $restriction ) {
1848 # FIXME: can $restriction be an array or what? (same as fixme above)
1849 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1855 $cascade_description = '';
1857 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1861 $comment .= ": $reason";
1863 $comment .= " [$updated]";
1864 if ( $expiry_description && $protect )
1865 $comment .= "$expiry_description";
1867 $comment .= "$cascade_description";
1869 # Update restrictions table
1870 foreach( $limit as $action => $restrictions ) {
1871 if ($restrictions != '' ) {
1872 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1873 array( 'pr_page' => $id, 'pr_type' => $action
1874 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1875 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1877 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1878 'pr_type' => $action ), __METHOD__
);
1882 # Insert a null revision
1883 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1884 $nullRevId = $nullRevision->insertOn( $dbw );
1886 # Update page record
1887 $dbw->update( 'page',
1889 'page_touched' => $dbw->timestamp(),
1890 'page_restrictions' => '',
1891 'page_latest' => $nullRevId
1892 ), array( /* WHERE */
1894 ), 'Article::protect'
1897 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, false) );
1898 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1900 # Update the protection log
1901 $log = new LogPage( 'protect' );
1903 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
,
1904 trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1906 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1910 } # End "changed" check
1916 * Take an array of page restrictions and flatten it to a string
1917 * suitable for insertion into the page_restrictions field.
1918 * @param array $limit
1922 function flattenRestrictions( $limit ) {
1923 if( !is_array( $limit ) ) {
1924 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1928 foreach( $limit as $action => $restrictions ) {
1929 if( $restrictions != '' ) {
1930 $bits[] = "$action=$restrictions";
1933 return implode( ':', $bits );
1937 * Auto-generates a deletion reason
1938 * @param bool &$hasHistory Whether the page has a history
1940 public function generateReason(&$hasHistory)
1943 $dbw = wfGetDB(DB_MASTER
);
1944 // Get the last revision
1945 $rev = Revision
::newFromTitle($this->mTitle
);
1948 // Get the article's contents
1949 $contents = $rev->getText();
1951 // If the page is blank, use the text from the previous revision,
1952 // which can only be blank if there's a move/import/protect dummy revision involved
1955 $prev = $rev->getPrevious();
1958 $contents = $prev->getText();
1963 // Find out if there was only one contributor
1964 // Only scan the last 20 revisions
1966 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1967 array('LIMIT' => $limit));
1969 // This page has no revisions, which is very weird
1971 if($res->numRows() > 1)
1974 $hasHistory = false;
1975 $row = $dbw->fetchObject($res);
1976 $onlyAuthor = $row->rev_user_text
;
1977 // Try to find a second contributor
1978 while( $row = $dbw->fetchObject($res) ) {
1979 if($row->rev_user_text
!= $onlyAuthor) {
1980 $onlyAuthor = false;
1984 $dbw->freeResult($res);
1986 // Generate the summary with a '$1' placeholder
1988 // The current revision is blank and the one before is also
1989 // blank. It's just not our lucky day
1990 $reason = wfMsgForContent('exbeforeblank', '$1');
1993 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1995 $reason = wfMsgForContent('excontent', '$1');
1998 // Replace newlines with spaces to prevent uglyness
1999 $contents = preg_replace("/[\n\r]/", ' ', $contents);
2000 // Calculate the maximum amount of chars to get
2001 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2002 $maxLength = 255 - (strlen($reason) - 2) - 3;
2003 $contents = $wgContLang->truncate($contents, $maxLength, '...');
2004 // Remove possible unfinished links
2005 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2006 // Now replace the '$1' placeholder
2007 $reason = str_replace( '$1', $contents, $reason );
2013 * UI entry point for page deletion
2016 global $wgUser, $wgOut, $wgRequest;
2018 $confirm = $wgRequest->wasPosted() &&
2019 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2021 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2022 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2024 $reason = $this->DeleteReasonList
;
2026 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2027 // Entry from drop down menu + additional comment
2028 $reason .= ': ' . $this->DeleteReason
;
2029 } elseif ( $reason == 'other' ) {
2030 $reason = $this->DeleteReason
;
2032 # Flag to hide all contents of the archived revisions
2033 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2035 # This code desperately needs to be totally rewritten
2037 # Read-only check...
2038 if ( wfReadOnly() ) {
2039 $wgOut->readOnlyPage();
2044 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2046 if (count($permission_errors)>0) {
2047 $wgOut->showPermissionsErrorPage( $permission_errors );
2051 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2053 # Better double-check that it hasn't been deleted yet!
2054 $dbw = wfGetDB( DB_MASTER
);
2055 $conds = $this->mTitle
->pageCond();
2056 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2057 if ( $latest === false ) {
2058 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2062 # Hack for big sites
2063 $bigHistory = $this->isBigDeletion();
2064 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2065 global $wgLang, $wgDeleteRevisionsLimit;
2066 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2067 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2072 $this->doDelete( $reason, $suppress );
2073 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2075 } elseif( $this->mTitle
->userIsWatching() ) {
2081 // Generate deletion reason
2082 $hasHistory = false;
2083 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2085 // If the page has a history, insert a warning
2086 if( $hasHistory && !$confirm ) {
2087 $skin=$wgUser->getSkin();
2088 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2090 global $wgLang, $wgDeleteRevisionsLimit;
2091 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2092 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2096 return $this->confirmDelete( $reason );
2100 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2102 function isBigDeletion() {
2103 global $wgDeleteRevisionsLimit;
2104 if( $wgDeleteRevisionsLimit ) {
2105 $revCount = $this->estimateRevisionCount();
2106 return $revCount > $wgDeleteRevisionsLimit;
2112 * @return int approximate revision count
2114 function estimateRevisionCount() {
2116 // For an exact count...
2117 //return $dbr->selectField( 'revision', 'COUNT(*)',
2118 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2119 return $dbr->estimateRowCount( 'revision', '*',
2120 array( 'rev_page' => $this->getId() ), __METHOD__
);
2124 * Get the last N authors
2125 * @param int $num Number of revisions to get
2126 * @param string $revLatest The latest rev_id, selected from the master (optional)
2127 * @return array Array of authors, duplicates not removed
2129 function getLastNAuthors( $num, $revLatest = 0 ) {
2130 wfProfileIn( __METHOD__
);
2132 // First try the slave
2133 // If that doesn't have the latest revision, try the master
2135 $db = wfGetDB( DB_SLAVE
);
2137 $res = $db->select( array( 'page', 'revision' ),
2138 array( 'rev_id', 'rev_user_text' ),
2140 'page_namespace' => $this->mTitle
->getNamespace(),
2141 'page_title' => $this->mTitle
->getDBkey(),
2142 'rev_page = page_id'
2143 ), __METHOD__
, $this->getSelectOptions( array(
2144 'ORDER BY' => 'rev_timestamp DESC',
2149 wfProfileOut( __METHOD__
);
2152 $row = $db->fetchObject( $res );
2153 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2154 $db = wfGetDB( DB_MASTER
);
2159 } while ( $continue );
2161 $authors = array( $row->rev_user_text
);
2162 while ( $row = $db->fetchObject( $res ) ) {
2163 $authors[] = $row->rev_user_text
;
2165 wfProfileOut( __METHOD__
);
2170 * Output deletion confirmation dialog
2171 * @param $reason string Prefilled reason
2173 function confirmDelete( $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' ), '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 ),