7 * Class representing a MediaWiki article and history.
9 * See design.txt for an overview.
10 * Note: edit user interface and cache support functions have been
11 * moved to separate EditPage and HTMLFileCache classes.
20 var $mContentLoaded; //!<
23 var $mGoodAdjustment; //!<
27 var $mRedirectedFrom; //!<
28 var $mRedirectUrl; //!<
29 var $mRevIdFetched; //!<
33 var $mTotalAdjustment; //!<
37 var $mRedirectTarget; //!<
42 * Constructor and clear the article
43 * @param $title Reference to a Title object.
44 * @param $oldId Integer revision ID, null to fetch from request, zero for current
46 function __construct( Title
$title, $oldId = null ) {
47 $this->mTitle
=& $title;
48 $this->mOldId
= $oldId;
53 * Tell the page view functions that this view was redirected
54 * from another page on the wiki.
55 * @param $from Title object.
57 function setRedirectedFrom( $from ) {
58 $this->mRedirectedFrom
= $from;
62 * If this page is a redirect, get its target
64 * The target will be fetched from the redirect table if possible.
65 * If this page doesn't have an entry there, call insertRedirect()
66 * @return mixed Title object, or null if this page is not a redirect
68 public function getRedirectTarget() {
69 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
71 if(!is_null($this->mRedirectTarget
))
72 return $this->mRedirectTarget
;
74 # Query the redirect table
75 $dbr = wfGetDB(DB_SLAVE
);
76 $res = $dbr->select('redirect',
77 array('rd_namespace', 'rd_title'),
78 array('rd_from' => $this->getID()),
81 $row = $dbr->fetchObject($res);
83 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
85 # This page doesn't have an entry in the redirect table
86 return $this->mRedirectTarget
= $this->insertRedirect();
90 * Insert an entry for this page into the redirect table.
92 * Don't call this function directly unless you know what you're doing.
93 * @return Title object
95 public function insertRedirect() {
96 $retval = Title
::newFromRedirect($this->getContent());
99 $dbw = wfGetDB(DB_MASTER
);
100 $dbw->replace('redirect', array('rd_from'), array(
101 'rd_from' => $this->getID(),
102 'rd_namespace' => $retval->getNamespace(),
103 'rd_title' => $retval->getDBKey()
109 * Get the Title object this page redirects to
111 * @return mixed false, Title of in-wiki target, or string with URL
113 function followRedirect() {
114 $text = $this->getContent();
115 $rt = Title
::newFromRedirect( $text );
117 # process if title object is valid and not special:userlogout
119 if( $rt->getInterwiki() != '' ) {
120 if( $rt->isLocal() ) {
121 // Offsite wikis need an HTTP redirect.
123 // This can be hard to reverse and may produce loops,
124 // so they may be disabled in the site configuration.
126 $source = $this->mTitle
->getFullURL( 'redirect=no' );
127 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
130 if( $rt->getNamespace() == NS_SPECIAL
) {
131 // Gotta handle redirects to special pages differently:
132 // Fill the HTTP response "Location" header and ignore
133 // the rest of the page we're on.
135 // This can be hard to reverse, so they may be disabled.
137 if( $rt->isSpecial( 'Userlogout' ) ) {
140 return $rt->getFullURL();
147 // No or invalid redirect
152 * get the title object of the article
154 function getTitle() {
155 return $this->mTitle
;
163 $this->mDataLoaded
= false;
164 $this->mContentLoaded
= false;
166 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
167 $this->mRedirectedFrom
= null; # Title object if set
168 $this->mRedirectTarget
= null; # Title object if set
170 $this->mTimestamp
= $this->mComment
= '';
171 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
172 $this->mTouched
= '19700101000000';
173 $this->mForUpdate
= false;
174 $this->mIsRedirect
= false;
175 $this->mRevIdFetched
= 0;
176 $this->mRedirectUrl
= false;
177 $this->mLatest
= false;
178 $this->mPreparedEdit
= false;
182 * Note that getContent/loadContent do not follow redirects anymore.
183 * If you need to fetch redirectable content easily, try
184 * the shortcut in Article::followContent()
186 * @todo There are still side-effects in this!
187 * In general, you should use the Revision class, not Article,
188 * to fetch text for purposes other than page views.
190 * @return Return the text of this revision
192 function getContent() {
193 global $wgUser, $wgOut, $wgMessageCache;
195 wfProfileIn( __METHOD__
);
197 if ( 0 == $this->getID() ) {
198 wfProfileOut( __METHOD__
);
199 $wgOut->setRobotpolicy( 'noindex,nofollow' );
201 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
202 $wgMessageCache->loadAllMessages();
203 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
205 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
208 return "<div class='noarticletext'>\n$ret\n</div>";
210 $this->loadContent();
211 wfProfileOut( __METHOD__
);
212 return $this->mContent
;
217 * This function returns the text of a section, specified by a number ($section).
218 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
219 * the first section before any such heading (section 0).
221 * If a section contains subsections, these are also returned.
223 * @param $text String: text to look in
224 * @param $section Integer: section number
225 * @return string text of the requested section
228 function getSection($text,$section) {
230 return $wgParser->getSection( $text, $section );
234 * @return int The oldid of the article that is to be shown, 0 for the
237 function getOldID() {
238 if ( is_null( $this->mOldId
) ) {
239 $this->mOldId
= $this->getOldIDFromRequest();
241 return $this->mOldId
;
245 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
247 * @return int The old id for the request
249 function getOldIDFromRequest() {
251 $this->mRedirectUrl
= false;
252 $oldid = $wgRequest->getVal( 'oldid' );
253 if ( isset( $oldid ) ) {
254 $oldid = intval( $oldid );
255 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
256 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
260 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
262 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
263 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
281 * Load the revision (including text) into this object
283 function loadContent() {
284 if ( $this->mContentLoaded
) return;
287 $oldid = $this->getOldID();
289 # Pre-fill content with error message so that if something
290 # fails we'll have something telling us what we intended.
291 $this->mOldId
= $oldid;
292 $this->fetchContent( $oldid );
297 * Fetch a page record with the given conditions
298 * @param Database $dbr
299 * @param array $conditions
302 function pageData( $dbr, $conditions ) {
316 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
317 $row = $dbr->selectRow(
323 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
328 * @param Database $dbr
329 * @param Title $title
331 function pageDataFromTitle( $dbr, $title ) {
332 return $this->pageData( $dbr, array(
333 'page_namespace' => $title->getNamespace(),
334 'page_title' => $title->getDBkey() ) );
338 * @param Database $dbr
341 function pageDataFromId( $dbr, $id ) {
342 return $this->pageData( $dbr, array( 'page_id' => $id ) );
346 * Set the general counter, title etc data loaded from
349 * @param object $data
352 function loadPageData( $data = 'fromdb' ) {
353 if ( $data === 'fromdb' ) {
354 $dbr = $this->getDB();
355 $data = $this->pageDataFromId( $dbr, $this->getId() );
358 $lc = LinkCache
::singleton();
360 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
362 $this->mTitle
->mArticleID
= $data->page_id
;
364 # Old-fashioned restrictions.
365 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
367 $this->mCounter
= $data->page_counter
;
368 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
369 $this->mIsRedirect
= $data->page_is_redirect
;
370 $this->mLatest
= $data->page_latest
;
372 if ( is_object( $this->mTitle
) ) {
373 $lc->addBadLinkObj( $this->mTitle
);
375 $this->mTitle
->mArticleID
= 0;
378 $this->mDataLoaded
= true;
382 * Get text of an article from database
383 * Does *NOT* follow redirects.
384 * @param int $oldid 0 for whatever the latest revision is
387 function fetchContent( $oldid = 0 ) {
388 if ( $this->mContentLoaded
) {
389 return $this->mContent
;
392 $dbr = $this->getDB();
394 # Pre-fill content with error message so that if something
395 # fails we'll have something telling us what we intended.
396 $t = $this->mTitle
->getPrefixedText();
398 $t .= ' ' . wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
400 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
403 $revision = Revision
::newFromId( $oldid );
404 if( is_null( $revision ) ) {
405 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
408 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
410 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
413 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
414 $this->loadPageData( $data );
416 if( !$this->mDataLoaded
) {
417 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
419 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
422 $this->loadPageData( $data );
424 $revision = Revision
::newFromId( $this->mLatest
);
425 if( is_null( $revision ) ) {
426 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
431 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
432 // We should instead work with the Revision object when we need it...
433 $this->mContent
= $revision->revText(); // Loads if user is allowed
435 $this->mUser
= $revision->getUser();
436 $this->mUserText
= $revision->getUserText();
437 $this->mComment
= $revision->getComment();
438 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
440 $this->mRevIdFetched
= $revision->getID();
441 $this->mContentLoaded
= true;
442 $this->mRevision
=& $revision;
444 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
446 return $this->mContent
;
450 * Read/write accessor to select FOR UPDATE
452 * @param $x Mixed: FIXME
454 function forUpdate( $x = NULL ) {
455 return wfSetVar( $this->mForUpdate
, $x );
459 * Get the database which should be used for reads
464 return wfGetDB( DB_MASTER
);
468 * Get options for all SELECT statements
470 * @param $options Array: an optional options array which'll be appended to
472 * @return Array: options
474 function getSelectOptions( $options = '' ) {
475 if ( $this->mForUpdate
) {
476 if ( is_array( $options ) ) {
477 $options[] = 'FOR UPDATE';
479 $options = 'FOR UPDATE';
486 * @return int Page ID
489 if( $this->mTitle
) {
490 return $this->mTitle
->getArticleID();
497 * @return bool Whether or not the page exists in the database
500 return $this->getId() != 0;
504 * @return int The view count for the page
506 function getCount() {
507 if ( -1 == $this->mCounter
) {
508 $id = $this->getID();
512 $dbr = wfGetDB( DB_SLAVE
);
513 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
514 'Article::getCount', $this->getSelectOptions() );
517 return $this->mCounter
;
521 * Determine whether a page would be suitable for being counted as an
522 * article in the site_stats table based on the title & its content
524 * @param $text String: text to analyze
527 function isCountable( $text ) {
528 global $wgUseCommaCount;
530 $token = $wgUseCommaCount ?
',' : '[[';
532 $this->mTitle
->isContentPage()
533 && !$this->isRedirect( $text )
534 && in_string( $token, $text );
538 * Tests if the article text represents a redirect
540 * @param $text String: FIXME
543 function isRedirect( $text = false ) {
544 if ( $text === false ) {
545 if ( $this->mDataLoaded
)
546 return $this->mIsRedirect
;
548 // Apparently loadPageData was never called
549 $this->loadContent();
550 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
552 $titleObj = Title
::newFromRedirect( $text );
554 return $titleObj !== NULL;
558 * Returns true if the currently-referenced revision is the current edit
559 * to this page (and it exists).
562 function isCurrent() {
563 # If no oldid, this is the current version.
564 if ($this->getOldID() == 0)
567 return $this->exists() &&
568 isset( $this->mRevision
) &&
569 $this->mRevision
->isCurrent();
573 * Loads everything except the text
574 * This isn't necessary for all uses, so it's only done if needed.
577 function loadLastEdit() {
578 if ( -1 != $this->mUser
)
581 # New or non-existent articles have no user information
582 $id = $this->getID();
583 if ( 0 == $id ) return;
585 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
586 if( !is_null( $this->mLastRevision
) ) {
587 $this->mUser
= $this->mLastRevision
->getUser();
588 $this->mUserText
= $this->mLastRevision
->getUserText();
589 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
590 $this->mComment
= $this->mLastRevision
->getComment();
591 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
592 $this->mRevIdFetched
= $this->mLastRevision
->getID();
596 function getTimestamp() {
597 // Check if the field has been filled by ParserCache::get()
598 if ( !$this->mTimestamp
) {
599 $this->loadLastEdit();
601 return wfTimestamp(TS_MW
, $this->mTimestamp
);
605 $this->loadLastEdit();
609 function getUserText() {
610 $this->loadLastEdit();
611 return $this->mUserText
;
614 function getComment() {
615 $this->loadLastEdit();
616 return $this->mComment
;
619 function getMinorEdit() {
620 $this->loadLastEdit();
621 return $this->mMinorEdit
;
624 function getRevIdFetched() {
625 $this->loadLastEdit();
626 return $this->mRevIdFetched
;
630 * @todo Document, fixme $offset never used.
631 * @param $limit Integer: default 0.
632 * @param $offset Integer: default 0.
634 function getContributors($limit = 0, $offset = 0) {
635 # XXX: this is expensive; cache this info somewhere.
638 $dbr = wfGetDB( DB_SLAVE
);
639 $revTable = $dbr->tableName( 'revision' );
640 $userTable = $dbr->tableName( 'user' );
641 $user = $this->getUser();
642 $pageId = $this->getId();
644 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
645 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
646 WHERE rev_page = $pageId
647 AND rev_user != $user
648 GROUP BY rev_user, rev_user_text, user_real_name
649 ORDER BY timestamp DESC";
651 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
652 $sql .= ' '. $this->getSelectOptions();
654 $res = $dbr->query($sql, __METHOD__
);
656 while ( $line = $dbr->fetchObject( $res ) ) {
657 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
660 $dbr->freeResult($res);
665 * This is the default action of the script: just view the page of
669 global $wgUser, $wgOut, $wgRequest, $wgContLang;
670 global $wgEnableParserCache, $wgStylePath, $wgParser;
671 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
672 global $wgDefaultRobotPolicy;
673 $sk = $wgUser->getSkin();
675 wfProfileIn( __METHOD__
);
677 $parserCache = ParserCache
::singleton();
678 $ns = $this->mTitle
->getNamespace(); # shortcut
680 # Get variables from query string
681 $oldid = $this->getOldID();
683 # getOldID may want us to redirect somewhere else
684 if ( $this->mRedirectUrl
) {
685 $wgOut->redirect( $this->mRedirectUrl
);
686 wfProfileOut( __METHOD__
);
690 $diff = $wgRequest->getVal( 'diff' );
691 $rcid = $wgRequest->getVal( 'rcid' );
692 $rdfrom = $wgRequest->getVal( 'rdfrom' );
693 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
694 $purge = $wgRequest->getVal( 'action' ) == 'purge';
696 $wgOut->setArticleFlag( true );
698 # Discourage indexing of printable versions, but encourage following
699 if( $wgOut->isPrintable() ) {
700 $policy = 'noindex,follow';
701 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
702 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
703 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
704 # Honour customised robot policies for this namespace
705 $policy = $wgNamespaceRobotPolicies[$ns];
707 $policy = $wgDefaultRobotPolicy;
709 $wgOut->setRobotPolicy( $policy );
711 # If we got diff and oldid in the query, we want to see a
712 # diff page instead of the article.
714 if ( !is_null( $diff ) ) {
715 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
717 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
718 // DifferenceEngine directly fetched the revision:
719 $this->mRevIdFetched
= $de->mNewid
;
720 $de->showDiffPage( $diffOnly );
722 // Needed to get the page's current revision
723 $this->loadPageData();
724 if( $diff == 0 ||
$diff == $this->mLatest
) {
725 # Run view updates for current revision only
726 $this->viewUpdates();
728 wfProfileOut( __METHOD__
);
732 if ( empty( $oldid ) && $this->checkTouched() ) {
733 $wgOut->setETag($parserCache->getETag($this, $wgUser));
735 if( $wgOut->checkLastModified( $this->mTouched
) ){
736 wfProfileOut( __METHOD__
);
738 } else if ( $this->tryFileCache() ) {
739 # tell wgOut that output is taken care of
741 $this->viewUpdates();
742 wfProfileOut( __METHOD__
);
747 # Should the parser cache be used?
748 $pcache = $wgEnableParserCache
749 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
752 && !$this->mTitle
->isCssOrJsPage()
753 && !$this->mTitle
->isCssJsSubpage();
754 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
755 if ( $wgUser->getOption( 'stubthreshold' ) ) {
756 wfIncrStats( 'pcache_miss_stub' );
759 $wasRedirected = false;
760 if ( isset( $this->mRedirectedFrom
) ) {
761 // This is an internally redirected page view.
762 // We'll need a backlink to the source page for navigation.
763 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
764 $sk = $wgUser->getSkin();
765 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
766 $s = wfMsg( 'redirectedfrom', $redir );
767 $wgOut->setSubtitle( $s );
769 // Set the fragment if one was specified in the redirect
770 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
771 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
772 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
774 $wasRedirected = true;
776 } elseif ( !empty( $rdfrom ) ) {
777 // This is an externally redirected view, from some other wiki.
778 // If it was reported from a trusted site, supply a backlink.
779 global $wgRedirectSources;
780 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
781 $sk = $wgUser->getSkin();
782 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
783 $s = wfMsg( 'redirectedfrom', $redir );
784 $wgOut->setSubtitle( $s );
785 $wasRedirected = true;
790 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
792 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
793 // Ensure that UI elements requiring revision ID have
794 // the correct version information.
795 $wgOut->setRevisionId( $this->mLatest
);
799 if ( !$outputDone ) {
800 $text = $this->getContent();
801 if ( $text === false ) {
802 # Failed to load, replace text with error message
803 $t = $this->mTitle
->getPrefixedText();
805 $t .= ' ' . wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
806 $text = wfMsg( 'missingarticle', $t );
808 $text = wfMsg( 'noarticletext' );
812 # Another whitelist check in case oldid is altering the title
813 if ( !$this->mTitle
->userCanRead() ) {
814 $wgOut->loginToUse();
816 wfProfileOut( __METHOD__
);
820 # We're looking at an old revision
822 if ( !empty( $oldid ) ) {
823 $wgOut->setRobotpolicy( 'noindex,nofollow' );
824 if( is_null( $this->mRevision
) ) {
825 // FIXME: This would be a nice place to load the 'no such page' text.
827 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
828 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
829 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
830 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
831 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
832 wfProfileOut( __METHOD__
);
835 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
836 // 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' ) );
850 // Give hooks a chance to customise the output
851 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
852 // Wrap the whole lot in a <pre> and don't parse
854 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
855 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
856 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
857 $wgOut->addHtml( "\n</pre>\n" );
862 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
863 # Don't overwrite the subtitle if this was an old revision
864 $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() );
865 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
866 $wgOut->addParserOutputNoText( $parseout );
867 } else if ( $pcache ) {
868 # Display content and save to parser cache
869 $this->outputWikiText( $text );
871 # Display content, don't attempt to save to parser cache
872 # Don't show section-edit links on old revisions... this way lies madness.
873 if( !$this->isCurrent() ) {
874 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
876 # Display content and don't save to parser cache
877 # With timing hack -- TS 2006-07-26
879 $this->outputWikiText( $text, false );
884 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
885 $this->mTitle
->getPrefixedDBkey()));
888 if( !$this->isCurrent() ) {
889 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
894 /* title may have been set from the cache */
895 $t = $wgOut->getPageTitle();
897 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
900 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
901 if( $ns == NS_USER_TALK
&&
902 IP
::isValid( $this->mTitle
->getText() ) ) {
903 $wgOut->addWikiMsg('anontalkpagetext');
906 # If we have been passed an &rcid= parameter, we want to give the user a
907 # chance to mark this new article as patrolled.
908 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
910 "<div class='patrollink'>" .
911 wfMsgHtml( 'markaspatrolledlink',
912 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
913 "action=markpatrolled&rcid=$rcid" )
920 if ($wgUseTrackbacks)
921 $this->addTrackbacks();
923 $this->viewUpdates();
924 wfProfileOut( __METHOD__
);
927 protected function viewRedirect( $target, $overwriteSubtitle = true, $forceKnown = false ) {
928 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
931 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
932 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
934 if( $overwriteSubtitle ) {
935 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
937 $sk = $wgUser->getSkin();
939 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
941 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
943 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
944 '<span class="redirectText">'.$link.'</span>' );
948 function addTrackbacks() {
949 global $wgOut, $wgUser;
951 $dbr = wfGetDB(DB_SLAVE
);
953 /* FROM */ 'trackbacks',
954 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
955 /* WHERE */ array('tb_page' => $this->getID())
958 if (!$dbr->numrows($tbs))
962 while ($o = $dbr->fetchObject($tbs)) {
964 if ($wgUser->isAllowed( 'trackback' )) {
965 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
966 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
967 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
970 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
977 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
980 function deletetrackback() {
981 global $wgUser, $wgRequest, $wgOut, $wgTitle;
983 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
984 $wgOut->addWikiMsg( 'sessionfailure' );
988 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
990 if (count($permission_errors)>0)
992 $wgOut->showPermissionsErrorPage( $permission_errors );
996 $db = wfGetDB(DB_MASTER
);
997 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
998 $wgTitle->invalidateCache();
999 $wgOut->addWikiMsg('trackbackdeleteok');
1005 $wgOut->setArticleBodyOnly(true);
1010 * Handle action=purge
1013 global $wgUser, $wgRequest, $wgOut;
1015 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1016 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1020 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1021 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1022 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1023 $msg = str_replace( '$1',
1024 "<form method=\"post\" action=\"$action\">\n" .
1025 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1026 "</form>\n", $msg );
1028 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1029 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1030 $wgOut->addHTML( $msg );
1035 * Perform the actions of a page purging
1037 function doPurge() {
1039 // Invalidate the cache
1040 $this->mTitle
->invalidateCache();
1042 if ( $wgUseSquid ) {
1043 // Commit the transaction before the purge is sent
1044 $dbw = wfGetDB( DB_MASTER
);
1045 $dbw->immediateCommit();
1048 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1049 $update->doUpdate();
1051 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1052 global $wgMessageCache;
1053 if ( $this->getID() == 0 ) {
1056 $text = $this->getContent();
1058 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1064 * Insert a new empty page record for this article.
1065 * This *must* be followed up by creating a revision
1066 * and running $this->updateToLatest( $rev_id );
1067 * or else the record will be left in a funky state.
1068 * Best if all done inside a transaction.
1070 * @param Database $dbw
1071 * @return int The newly created page_id key
1074 function insertOn( $dbw ) {
1075 wfProfileIn( __METHOD__
);
1077 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1078 $dbw->insert( 'page', array(
1079 'page_id' => $page_id,
1080 'page_namespace' => $this->mTitle
->getNamespace(),
1081 'page_title' => $this->mTitle
->getDBkey(),
1082 'page_counter' => 0,
1083 'page_restrictions' => '',
1084 'page_is_redirect' => 0, # Will set this shortly...
1086 'page_random' => wfRandom(),
1087 'page_touched' => $dbw->timestamp(),
1088 'page_latest' => 0, # Fill this in shortly...
1089 'page_len' => 0, # Fill this in shortly...
1091 $newid = $dbw->insertId();
1093 $this->mTitle
->resetArticleId( $newid );
1095 wfProfileOut( __METHOD__
);
1100 * Update the page record to point to a newly saved revision.
1102 * @param Database $dbw
1103 * @param Revision $revision For ID number, and text used to set
1104 length and redirect status fields
1105 * @param int $lastRevision If given, will not overwrite the page field
1106 * when different from the currently set value.
1107 * Giving 0 indicates the new page flag should
1109 * @param bool $lastRevIsRedirect If given, will optimize adding and
1110 * removing rows in redirect table.
1111 * @return bool true on success, false on failure
1114 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1115 wfProfileIn( __METHOD__
);
1117 $text = $revision->getText();
1118 $rt = Title
::newFromRedirect( $text );
1120 $conditions = array( 'page_id' => $this->getId() );
1121 if( !is_null( $lastRevision ) ) {
1122 # An extra check against threads stepping on each other
1123 $conditions['page_latest'] = $lastRevision;
1126 $dbw->update( 'page',
1128 'page_latest' => $revision->getId(),
1129 'page_touched' => $dbw->timestamp(),
1130 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1131 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1132 'page_len' => strlen( $text ),
1137 $result = $dbw->affectedRows() != 0;
1140 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1143 wfProfileOut( __METHOD__
);
1148 * Add row to the redirect table if this is a redirect, remove otherwise.
1150 * @param Database $dbw
1151 * @param $redirectTitle a title object pointing to the redirect target,
1152 * or NULL if this is not a redirect
1153 * @param bool $lastRevIsRedirect If given, will optimize adding and
1154 * removing rows in redirect table.
1155 * @return bool true on success, false on failure
1158 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1160 // Always update redirects (target link might have changed)
1161 // Update/Insert if we don't know if the last revision was a redirect or not
1162 // Delete if changing from redirect to non-redirect
1163 $isRedirect = !is_null($redirectTitle);
1164 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1166 wfProfileIn( __METHOD__
);
1170 // This title is a redirect, Add/Update row in the redirect table
1171 $set = array( /* SET */
1172 'rd_namespace' => $redirectTitle->getNamespace(),
1173 'rd_title' => $redirectTitle->getDBkey(),
1174 'rd_from' => $this->getId(),
1177 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1179 // This is not a redirect, remove row from redirect table
1180 $where = array( 'rd_from' => $this->getId() );
1181 $dbw->delete( 'redirect', $where, __METHOD__
);
1184 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1185 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1186 wfProfileOut( __METHOD__
);
1187 return ( $dbw->affectedRows() != 0 );
1194 * If the given revision is newer than the currently set page_latest,
1195 * update the page record. Otherwise, do nothing.
1197 * @param Database $dbw
1198 * @param Revision $revision
1200 function updateIfNewerOn( &$dbw, $revision ) {
1201 wfProfileIn( __METHOD__
);
1203 $row = $dbw->selectRow(
1204 array( 'revision', 'page' ),
1205 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1207 'page_id' => $this->getId(),
1208 'page_latest=rev_id' ),
1211 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1212 wfProfileOut( __METHOD__
);
1215 $prev = $row->rev_id
;
1216 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1218 # No or missing previous revision; mark the page as new
1220 $lastRevIsRedirect = null;
1223 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1224 wfProfileOut( __METHOD__
);
1229 * @return string Complete article text, or null if error
1231 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1232 wfProfileIn( __METHOD__
);
1234 if( $section == '' ) {
1235 // Whole-page edit; let the text through unmolested.
1237 if( is_null( $edittime ) ) {
1238 $rev = Revision
::newFromTitle( $this->mTitle
);
1240 $dbw = wfGetDB( DB_MASTER
);
1241 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1243 if( is_null( $rev ) ) {
1244 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1245 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1248 $oldtext = $rev->getText();
1250 if( $section == 'new' ) {
1251 # Inserting a new section
1252 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1253 $text = strlen( trim( $oldtext ) ) > 0
1254 ?
"{$oldtext}\n\n{$subject}{$text}"
1255 : "{$subject}{$text}";
1257 # Replacing an existing section; roll out the big guns
1259 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1264 wfProfileOut( __METHOD__
);
1269 * @deprecated use Article::doEdit()
1271 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1272 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1273 ( $isminor ? EDIT_MINOR
: 0 ) |
1274 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1275 ( $bot ? EDIT_FORCE_BOT
: 0 );
1277 # If this is a comment, add the summary as headline
1278 if ( $comment && $summary != "" ) {
1279 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1282 $this->doEdit( $text, $summary, $flags );
1284 $dbw = wfGetDB( DB_MASTER
);
1286 if (!$this->mTitle
->userIsWatching()) {
1292 if ( $this->mTitle
->userIsWatching() ) {
1298 $this->doRedirect( $this->isRedirect( $text ) );
1302 * @deprecated use Article::doEdit()
1304 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1305 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1306 ( $minor ? EDIT_MINOR
: 0 ) |
1307 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1309 $good = $this->doEdit( $text, $summary, $flags );
1311 $dbw = wfGetDB( DB_MASTER
);
1313 if (!$this->mTitle
->userIsWatching()) {
1319 if ( $this->mTitle
->userIsWatching() ) {
1326 $extraq = ''; // Give extensions a chance to modify URL query on update
1327 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1329 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1337 * Change an existing article or create a new article. Updates RC and all necessary caches,
1338 * optionally via the deferred update array.
1340 * $wgUser must be set before calling this function.
1342 * @param string $text New text
1343 * @param string $summary Edit summary
1344 * @param integer $flags bitfield:
1346 * Article is known or assumed to be non-existent, create a new one
1348 * Article is known or assumed to be pre-existing, update it
1350 * Mark this edit minor, if the user is allowed to do so
1352 * Do not log the change in recentchanges
1354 * Mark the edit a "bot" edit regardless of user rights
1355 * EDIT_DEFER_UPDATES
1356 * Defer some of the updates until the end of index.php
1358 * Fill in blank summaries with generated text where possible
1360 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1361 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1362 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1363 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1364 * to MediaWiki's performance-optimised locking strategy.
1366 * @return bool success
1368 function doEdit( $text, $summary, $flags = 0 ) {
1369 global $wgUser, $wgDBtransactions;
1371 wfProfileIn( __METHOD__
);
1374 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1375 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1377 $flags |
= EDIT_UPDATE
;
1383 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1384 &$summary, $flags & EDIT_MINOR
,
1385 null, null, &$flags ) ) )
1387 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1388 wfProfileOut( __METHOD__
);
1392 # Silently ignore EDIT_MINOR if not allowed
1393 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1394 $bot = $flags & EDIT_FORCE_BOT
;
1396 $oldtext = $this->getContent();
1397 $oldsize = strlen( $oldtext );
1399 # Provide autosummaries if one is not provided.
1400 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1401 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1403 $editInfo = $this->prepareTextForEdit( $text );
1404 $text = $editInfo->pst
;
1405 $newsize = strlen( $text );
1407 $dbw = wfGetDB( DB_MASTER
);
1408 $now = wfTimestampNow();
1410 if ( $flags & EDIT_UPDATE
) {
1411 # Update article, but only if changed.
1413 # Make sure the revision is either completely inserted or not inserted at all
1414 if( !$wgDBtransactions ) {
1415 $userAbort = ignore_user_abort( true );
1421 $changed = ( strcmp( $text, $oldtext ) != 0 );
1424 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1425 - (int)$this->isCountable( $oldtext );
1426 $this->mTotalAdjustment
= 0;
1428 $lastRevision = $dbw->selectField(
1429 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1431 if ( !$lastRevision ) {
1432 # Article gone missing
1433 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1434 wfProfileOut( __METHOD__
);
1438 $revision = new Revision( array(
1439 'page' => $this->getId(),
1440 'comment' => $summary,
1441 'minor_edit' => $isminor,
1443 'parent_id' => $lastRevision
1447 $revisionId = $revision->insertOn( $dbw );
1450 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1453 /* Belated edit conflict! Run away!! */
1457 # Update recentchanges
1458 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1459 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1460 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1463 # Mark as patrolled if the user can do so
1464 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1465 RecentChange
::markPatrolled( $rcid );
1466 PatrolLog
::record( $rcid, true );
1469 $wgUser->incEditCount();
1474 // Keep the same revision ID, but do some updates on it
1475 $revisionId = $this->getRevIdFetched();
1476 // Update page_touched, this is usually implicit in the page update
1477 // Other cache updates are done in onArticleEdit()
1478 $this->mTitle
->invalidateCache();
1481 if( !$wgDBtransactions ) {
1482 ignore_user_abort( $userAbort );
1486 # Invalidate cache of this article and all pages using this article
1487 # as a template. Partly deferred.
1488 Article
::onArticleEdit( $this->mTitle
);
1490 # Update links tables, site stats, etc.
1491 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1494 # Create new article
1496 # Set statistics members
1497 # We work out if it's countable after PST to avoid counter drift
1498 # when articles are created with {{subst:}}
1499 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1500 $this->mTotalAdjustment
= 1;
1504 # Add the page record; stake our claim on this title!
1505 # This will fail with a database query exception if the article already exists
1506 $newid = $this->insertOn( $dbw );
1508 # Save the revision text...
1509 $revision = new Revision( array(
1511 'comment' => $summary,
1512 'minor_edit' => $isminor,
1515 $revisionId = $revision->insertOn( $dbw );
1517 $this->mTitle
->resetArticleID( $newid );
1519 # Update the page record with revision data
1520 $this->updateRevisionOn( $dbw, $revision, 0 );
1522 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1523 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1524 '', strlen( $text ), $revisionId );
1525 # Mark as patrolled if the user can
1526 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1527 RecentChange
::markPatrolled( $rcid );
1528 PatrolLog
::record( $rcid, true );
1531 $wgUser->incEditCount();
1534 # Update links, etc.
1535 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1538 Article
::onArticleCreate( $this->mTitle
);
1540 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1541 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1544 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1549 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1550 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1553 wfProfileOut( __METHOD__
);
1558 * @deprecated wrapper for doRedirect
1560 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1561 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1565 * Output a redirect back to the article.
1566 * This is typically used after an edit.
1568 * @param boolean $noRedir Add redirect=no
1569 * @param string $sectionAnchor section to redirect to, including "#"
1570 * @param string $extraq, extra query params
1572 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1575 $query = 'redirect=no';
1577 $query .= "&$query";
1581 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1585 * Mark this particular edit/page as patrolled
1587 function markpatrolled() {
1588 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1589 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1591 # Check patrol config options
1593 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1594 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1598 # If we haven't been given an rc_id value, we can't do anything
1599 $rcid = (int) $wgRequest->getVal('rcid');
1600 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1601 if ( is_null ( $rc ) )
1603 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1607 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1608 // Only new pages can be patrolled if the general patrolling is off....???
1609 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1611 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1616 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1618 if (count($permission_errors)>0)
1620 $wgOut->showPermissionsErrorPage( $permission_errors );
1624 # Handle the 'MarkPatrolled' hook
1625 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1629 #It would be nice to see where the user had actually come from, but for now just guess
1630 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1631 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1633 # If it's left up to us, check that the user is allowed to patrol this edit
1634 # If the user has the "autopatrol" right, then we'll assume there are no
1635 # other conditions stopping them doing so
1636 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1637 $rc = RecentChange
::newFromId( $rcid );
1638 # Graceful error handling, as we've done before here...
1639 # (If the recent change doesn't exist, then it doesn't matter whether
1640 # the user is allowed to patrol it or not; nothing is going to happen
1641 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1642 # The user made this edit, and can't patrol it
1643 # Tell them so, and then back off
1644 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1645 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1646 $wgOut->returnToMain( false, $return );
1651 # Check that the revision isn't patrolled already
1652 # Prevents duplicate log entries
1653 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1654 # Mark the edit as patrolled
1655 RecentChange
::markPatrolled( $rcid );
1656 PatrolLog
::record( $rcid );
1657 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1661 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1662 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1663 $wgOut->returnToMain( false, $return );
1667 * User-interface handler for the "watch" action
1672 global $wgUser, $wgOut;
1674 if ( $wgUser->isAnon() ) {
1675 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1678 if ( wfReadOnly() ) {
1679 $wgOut->readOnlyPage();
1683 if( $this->doWatch() ) {
1684 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1685 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1687 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1690 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1694 * Add this page to $wgUser's watchlist
1695 * @return bool true on successful watch operation
1697 function doWatch() {
1699 if( $wgUser->isAnon() ) {
1703 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1704 $wgUser->addWatch( $this->mTitle
);
1706 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1713 * User interface handler for the "unwatch" action.
1715 function unwatch() {
1717 global $wgUser, $wgOut;
1719 if ( $wgUser->isAnon() ) {
1720 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1723 if ( wfReadOnly() ) {
1724 $wgOut->readOnlyPage();
1728 if( $this->doUnwatch() ) {
1729 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1730 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1732 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1735 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1739 * Stop watching a page
1740 * @return bool true on successful unwatch
1742 function doUnwatch() {
1744 if( $wgUser->isAnon() ) {
1748 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1749 $wgUser->removeWatch( $this->mTitle
);
1751 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1758 * action=protect handler
1760 function protect() {
1761 $form = new ProtectionForm( $this );
1766 * action=unprotect handler (alias)
1768 function unprotect() {
1773 * Update the article's restriction field, and leave a log entry.
1775 * @param array $limit set of restriction keys
1776 * @param string $reason
1777 * @return bool true on success
1779 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1780 global $wgUser, $wgRestrictionTypes, $wgContLang;
1782 $id = $this->mTitle
->getArticleID();
1783 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1791 // Take this opportunity to purge out expired restrictions
1792 Title
::purgeExpiredRestrictions();
1794 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1795 # we expect a single selection, but the schema allows otherwise.
1797 foreach( $wgRestrictionTypes as $action )
1798 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1800 $current = Article
::flattenRestrictions( $current );
1801 $updated = Article
::flattenRestrictions( $limit );
1803 $changed = ( $current != $updated );
1804 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1805 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1806 $protect = ( $updated != '' );
1808 # If nothing's changed, do nothing
1810 global $wgGroupPermissions;
1811 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1813 $dbw = wfGetDB( DB_MASTER
);
1815 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1817 $expiry_description = '';
1818 if ( $encodedExpiry != 'infinity' ) {
1819 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1822 # Prepare a null revision to be added to the history
1823 $modified = $current != '' && $protect;
1825 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1827 $comment_type = 'unprotectedarticle';
1829 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1831 foreach( $limit as $action => $restrictions ) {
1832 # Check if the group level required to edit also can protect pages
1833 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1834 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1835 $wgGroupPermissions[$restrictions]['protect'] );
1838 $cascade_description = '';
1840 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1844 $comment .= ": $reason";
1846 $comment .= " [$updated]";
1847 if ( $expiry_description && $protect )
1848 $comment .= "$expiry_description";
1850 $comment .= "$cascade_description";
1852 # Update restrictions table
1853 foreach( $limit as $action => $restrictions ) {
1854 if ($restrictions != '' ) {
1855 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1856 array( 'pr_page' => $id, 'pr_type' => $action
1857 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1858 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1860 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1861 'pr_type' => $action ), __METHOD__
);
1865 # Insert a null revision
1866 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1867 $nullRevId = $nullRevision->insertOn( $dbw );
1869 # Update page record
1870 $dbw->update( 'page',
1872 'page_touched' => $dbw->timestamp(),
1873 'page_restrictions' => '',
1874 'page_latest' => $nullRevId
1875 ), array( /* WHERE */
1877 ), 'Article::protect'
1879 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1881 # Update the protection log
1882 $log = new LogPage( 'protect' );
1884 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1886 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1890 } # End "changed" check
1896 * Take an array of page restrictions and flatten it to a string
1897 * suitable for insertion into the page_restrictions field.
1898 * @param array $limit
1902 function flattenRestrictions( $limit ) {
1903 if( !is_array( $limit ) ) {
1904 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1908 foreach( $limit as $action => $restrictions ) {
1909 if( $restrictions != '' ) {
1910 $bits[] = "$action=$restrictions";
1913 return implode( ':', $bits );
1917 * Auto-generates a deletion reason
1918 * @param bool &$hasHistory Whether the page has a history
1920 public function generateReason(&$hasHistory)
1923 $dbw = wfGetDB(DB_MASTER
);
1924 // Get the last revision
1925 $rev = Revision
::newFromTitle($this->mTitle
);
1928 // Get the article's contents
1929 $contents = $rev->getText();
1931 // If the page is blank, use the text from the previous revision,
1932 // which can only be blank if there's a move/import/protect dummy revision involved
1935 $prev = $rev->getPrevious();
1938 $contents = $prev->getText();
1943 // Find out if there was only one contributor
1944 // Only scan the last 20 revisions
1946 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1947 array('LIMIT' => $limit));
1949 // This page has no revisions, which is very weird
1951 if($res->numRows() > 1)
1954 $hasHistory = false;
1955 $row = $dbw->fetchObject($res);
1956 $onlyAuthor = $row->rev_user_text
;
1957 // Try to find a second contributor
1958 while( $row = $dbw->fetchObject($res) ) {
1959 if($row->rev_user_text
!= $onlyAuthor) {
1960 $onlyAuthor = false;
1964 $dbw->freeResult($res);
1966 // Generate the summary with a '$1' placeholder
1968 // The current revision is blank and the one before is also
1969 // blank. It's just not our lucky day
1970 $reason = wfMsgForContent('exbeforeblank', '$1');
1973 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1975 $reason = wfMsgForContent('excontent', '$1');
1978 // Replace newlines with spaces to prevent uglyness
1979 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1980 // Calculate the maximum amount of chars to get
1981 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1982 $maxLength = 255 - (strlen($reason) - 2) - 3;
1983 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1984 // Remove possible unfinished links
1985 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1986 // Now replace the '$1' placeholder
1987 $reason = str_replace( '$1', $contents, $reason );
1993 * UI entry point for page deletion
1996 global $wgUser, $wgOut, $wgRequest;
1998 $confirm = $wgRequest->wasPosted() &&
1999 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2001 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2002 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2004 $reason = $this->DeleteReasonList
;
2006 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2007 // Entry from drop down menu + additional comment
2008 $reason .= ': ' . $this->DeleteReason
;
2009 } elseif ( $reason == 'other' ) {
2010 $reason = $this->DeleteReason
;
2012 # Flag to hide all contents of the archived revisions
2013 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('hiderevision');
2015 # This code desperately needs to be totally rewritten
2017 # Read-only check...
2018 if ( wfReadOnly() ) {
2019 $wgOut->readOnlyPage();
2024 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2026 if (count($permission_errors)>0) {
2027 $wgOut->showPermissionsErrorPage( $permission_errors );
2031 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2033 # Better double-check that it hasn't been deleted yet!
2034 $dbw = wfGetDB( DB_MASTER
);
2035 $conds = $this->mTitle
->pageCond();
2036 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2037 if ( $latest === false ) {
2038 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2042 # Hack for big sites
2043 $bigHistory = $this->isBigDeletion();
2044 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2045 global $wgLang, $wgDeleteRevisionsLimit;
2046 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2047 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2052 $this->doDelete( $reason, $suppress );
2053 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2055 } elseif( $this->mTitle
->userIsWatching() ) {
2061 // Generate deletion reason
2062 $hasHistory = false;
2063 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2065 // If the page has a history, insert a warning
2066 if( $hasHistory && !$confirm ) {
2067 $skin=$wgUser->getSkin();
2068 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2070 global $wgLang, $wgDeleteRevisionsLimit;
2071 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2072 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2076 return $this->confirmDelete( '', $reason );
2080 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2082 function isBigDeletion() {
2083 global $wgDeleteRevisionsLimit;
2084 if( $wgDeleteRevisionsLimit ) {
2085 $revCount = $this->estimateRevisionCount();
2086 return $revCount > $wgDeleteRevisionsLimit;
2092 * @return int approximate revision count
2094 function estimateRevisionCount() {
2096 // For an exact count...
2097 //return $dbr->selectField( 'revision', 'COUNT(*)',
2098 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2099 return $dbr->estimateRowCount( 'revision', '*',
2100 array( 'rev_page' => $this->getId() ), __METHOD__
);
2104 * Get the last N authors
2105 * @param int $num Number of revisions to get
2106 * @param string $revLatest The latest rev_id, selected from the master (optional)
2107 * @return array Array of authors, duplicates not removed
2109 function getLastNAuthors( $num, $revLatest = 0 ) {
2110 wfProfileIn( __METHOD__
);
2112 // First try the slave
2113 // If that doesn't have the latest revision, try the master
2115 $db = wfGetDB( DB_SLAVE
);
2117 $res = $db->select( array( 'page', 'revision' ),
2118 array( 'rev_id', 'rev_user_text' ),
2120 'page_namespace' => $this->mTitle
->getNamespace(),
2121 'page_title' => $this->mTitle
->getDBkey(),
2122 'rev_page = page_id'
2123 ), __METHOD__
, $this->getSelectOptions( array(
2124 'ORDER BY' => 'rev_timestamp DESC',
2129 wfProfileOut( __METHOD__
);
2132 $row = $db->fetchObject( $res );
2133 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2134 $db = wfGetDB( DB_MASTER
);
2139 } while ( $continue );
2141 $authors = array( $row->rev_user_text
);
2142 while ( $row = $db->fetchObject( $res ) ) {
2143 $authors[] = $row->rev_user_text
;
2145 wfProfileOut( __METHOD__
);
2150 * Output deletion confirmation dialog
2151 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2152 * @param $reason string Prefilled reason
2154 function confirmDelete( $par, $reason ) {
2155 global $wgOut, $wgUser, $wgContLang;
2156 $align = $wgContLang->isRtl() ?
'left' : 'right';
2158 wfDebug( "Article::confirmDelete\n" );
2160 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2161 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2162 $wgOut->addWikiMsg( 'confirmdeletetext' );
2164 if( $wgUser->isAllowed( 'hiderevision' ) ) {
2165 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2166 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2167 $suppress .= "</td></tr>";
2172 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2173 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2174 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2175 Xml
::openElement( 'table' ) .
2176 "<tr id=\"wpDeleteReasonListRow\">
2177 <td align='$align'>" .
2178 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2181 Xml
::listDropDown( 'wpDeleteReasonList',
2182 wfMsgForContent( 'deletereason-dropdown' ),
2183 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2186 <tr id=\"wpDeleteReasonRow\">
2187 <td align='$align'>" .
2188 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2191 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2197 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2204 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2207 Xml
::closeElement( 'table' ) .
2208 Xml
::closeElement( 'fieldset' ) .
2209 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2210 Xml
::closeElement( 'form' );
2212 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2213 $skin = $wgUser->getSkin();
2214 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2215 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2218 $wgOut->addHTML( $form );
2219 $this->showLogExtract( $wgOut );
2224 * Show relevant lines from the deletion log
2226 function showLogExtract( $out ) {
2227 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2228 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2233 * Perform a deletion and output success or failure messages
2235 function doDelete( $reason, $suppress = false ) {
2236 global $wgOut, $wgUser;
2237 wfDebug( __METHOD__
."\n" );
2239 $id = $this->getId();
2241 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2242 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2243 $deleted = $this->mTitle
->getPrefixedText();
2245 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2246 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2248 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2250 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2251 $wgOut->returnToMain( false );
2252 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2254 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2260 * Back-end article deletion
2261 * Deletes the article with database consistency, writes logs, purges caches
2264 function doDeleteArticle( $reason, $suppress = false ) {
2265 global $wgUseSquid, $wgDeferredUpdateList;
2266 global $wgUseTrackbacks;
2268 wfDebug( __METHOD__
."\n" );
2270 $dbw = wfGetDB( DB_MASTER
);
2271 $ns = $this->mTitle
->getNamespace();
2272 $t = $this->mTitle
->getDBkey();
2273 $id = $this->mTitle
->getArticleID();
2275 if ( $t == '' ||
$id == 0 ) {
2279 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2280 array_push( $wgDeferredUpdateList, $u );
2282 // Bitfields to further suppress the content
2285 // This should be 15...
2286 $bitfield |
= Revision
::DELETED_TEXT
;
2287 $bitfield |
= Revision
::DELETED_COMMENT
;
2288 $bitfield |
= Revision
::DELETED_USER
;
2289 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2291 $bitfield = 'rev_deleted';
2295 // For now, shunt the revision data into the archive table.
2296 // Text is *not* removed from the text table; bulk storage
2297 // is left intact to avoid breaking block-compression or
2298 // immutable storage schemes.
2300 // For backwards compatibility, note that some older archive
2301 // table entries will have ar_text and ar_flags fields still.
2303 // In the future, we may keep revisions and mark them with
2304 // the rev_deleted field, which is reserved for this purpose.
2305 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2307 'ar_namespace' => 'page_namespace',
2308 'ar_title' => 'page_title',
2309 'ar_comment' => 'rev_comment',
2310 'ar_user' => 'rev_user',
2311 'ar_user_text' => 'rev_user_text',
2312 'ar_timestamp' => 'rev_timestamp',
2313 'ar_minor_edit' => 'rev_minor_edit',
2314 'ar_rev_id' => 'rev_id',
2315 'ar_text_id' => 'rev_text_id',
2316 'ar_text' => '\'\'', // Be explicit to appease
2317 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2318 'ar_len' => 'rev_len',
2319 'ar_page_id' => 'page_id',
2320 'ar_deleted' => $bitfield
2323 'page_id = rev_page'
2327 # Delete restrictions for it
2328 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2330 # Fix category table counts
2332 $res = $dbw->select( 'categorylinks', 'cl_to',
2333 array( 'cl_from' => $id ), __METHOD__
);
2334 foreach( $res as $row ) {
2335 $cats []= $row->cl_to
;
2337 $this->updateCategoryCounts( array(), $cats );
2339 # Now that it's safely backed up, delete it
2340 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2341 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2347 # If using cascading deletes, we can skip some explicit deletes
2348 if ( !$dbw->cascadingDeletes() ) {
2349 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2351 if ($wgUseTrackbacks)
2352 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2354 # Delete outgoing links
2355 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2356 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2357 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2358 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2359 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2360 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2361 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2364 # If using cleanup triggers, we can skip some manual deletes
2365 if ( !$dbw->cleanupTriggers() ) {
2367 # Clean up recentchanges entries...
2368 $dbw->delete( 'recentchanges',
2369 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2375 Article
::onArticleDelete( $this->mTitle
);
2377 # Clear the cached article id so the interface doesn't act like we exist
2378 $this->mTitle
->resetArticleID( 0 );
2379 $this->mTitle
->mArticleID
= 0;
2381 # Log the deletion, if the page was suppressed, log it at Oversight instead
2382 $logtype = $suppress ?
'suppress' : 'delete';
2383 $log = new LogPage( $logtype );
2385 # Make sure logging got through
2386 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2392 * Roll back the most recent consecutive set of edits to a page
2393 * from the same user; fails if there are no eligible edits to
2394 * roll back to, e.g. user is the sole contributor. This function
2395 * performs permissions checks on $wgUser, then calls commitRollback()
2396 * to do the dirty work
2398 * @param string $fromP - Name of the user whose edits to rollback.
2399 * @param string $summary - Custom summary. Set to default summary if empty.
2400 * @param string $token - Rollback token.
2401 * @param bool $bot - If true, mark all reverted edits as bot.
2403 * @param array $resultDetails contains result-specific array of additional values
2404 * 'alreadyrolled' : 'current' (rev)
2405 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2407 * @return array of errors, each error formatted as
2408 * array(messagekey, param1, param2, ...).
2409 * On success, the array is empty. This array can also be passed to
2410 * OutputPage::showPermissionsErrorPage().
2412 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2414 $resultDetails = null;
2417 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2418 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2419 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2420 $errors[] = array( 'sessionfailure' );
2422 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2423 $errors[] = array( 'actionthrottledtext' );
2425 # If there were errors, bail out now
2429 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2433 * Backend implementation of doRollback(), please refer there for parameter
2434 * and return value documentation
2436 * NOTE: This function does NOT check ANY permissions, it just commits the
2437 * rollback to the DB Therefore, you should only call this function direct-
2438 * ly if you want to use custom permissions checks. If you don't, use
2439 * doRollback() instead.
2441 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2442 global $wgUseRCPatrol, $wgUser, $wgLang;
2443 $dbw = wfGetDB( DB_MASTER
);
2445 if( wfReadOnly() ) {
2446 return array( array( 'readonlytext' ) );
2449 # Get the last editor
2450 $current = Revision
::newFromTitle( $this->mTitle
);
2451 if( is_null( $current ) ) {
2452 # Something wrong... no page?
2453 return array(array('notanarticle'));
2456 $from = str_replace( '_', ' ', $fromP );
2457 if( $from != $current->getUserText() ) {
2458 $resultDetails = array( 'current' => $current );
2459 return array(array('alreadyrolled',
2460 htmlspecialchars($this->mTitle
->getPrefixedText()),
2461 htmlspecialchars($fromP),
2462 htmlspecialchars($current->getUserText())
2466 # Get the last edit not by this guy
2467 $user = intval( $current->getUser() );
2468 $user_text = $dbw->addQuotes( $current->getUserText() );
2469 $s = $dbw->selectRow( 'revision',
2470 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2471 array( 'rev_page' => $current->getPage(),
2472 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2474 array( 'USE INDEX' => 'page_timestamp',
2475 'ORDER BY' => 'rev_timestamp DESC' )
2477 if( $s === false ) {
2478 # No one else ever edited this page
2479 return array(array('cantrollback'));
2480 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2481 # Only admins can see this text
2482 return array(array('notvisiblerev'));
2486 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2487 # Mark all reverted edits as bot
2490 if ( $wgUseRCPatrol ) {
2491 # Mark all reverted edits as patrolled
2492 $set['rc_patrolled'] = 1;
2496 $dbw->update( 'recentchanges', $set,
2498 'rc_cur_id' => $current->getPage(),
2499 'rc_user_text' => $current->getUserText(),
2500 "rc_timestamp > '{$s->rev_timestamp}'",
2505 # Generate the edit summary if necessary
2506 $target = Revision
::newFromId( $s->rev_id
);
2507 if( empty( $summary ) ){
2508 $summary = wfMsgForContent( 'revertpage' );
2511 # Allow the custom summary to use the same args as the default message
2513 $target->getUserText(), $from, $s->rev_id
,
2514 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2515 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2517 $summary = wfMsgReplaceArgs( $summary, $args );
2520 $flags = EDIT_UPDATE
;
2522 if ($wgUser->isAllowed('minoredit'))
2523 $flags |
= EDIT_MINOR
;
2525 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2526 $flags |
= EDIT_FORCE_BOT
;
2527 $this->doEdit( $target->getText(), $summary, $flags );
2529 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2531 $resultDetails = array(
2532 'summary' => $summary,
2533 'current' => $current,
2534 'target' => $target,
2540 * User interface for rollback operations
2542 function rollback() {
2543 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2546 $result = $this->doRollback(
2547 $wgRequest->getVal( 'from' ),
2548 $wgRequest->getText( 'summary' ),
2549 $wgRequest->getVal( 'token' ),
2550 $wgRequest->getBool( 'bot' ),
2554 if( in_array( array( 'blocked' ), $result ) ) {
2555 $wgOut->blockedPage();
2558 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2559 $wgOut->rateLimited();
2562 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2563 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2564 $errArray = $result[0];
2565 $errMsg = array_shift( $errArray );
2566 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2567 if( isset( $details['current'] ) ){
2568 $current = $details['current'];
2569 if( $current->getComment() != '' ) {
2570 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2575 # Display permissions errors before read-only message -- there's no
2576 # point in misleading the user into thinking the inability to rollback
2577 # is only temporary.
2578 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2579 # array_diff is completely broken for arrays of arrays, sigh. Re-
2580 # move any 'readonlytext' error manually.
2582 foreach( $result as $error ) {
2583 if( $error != array( 'readonlytext' ) ) {
2587 $wgOut->showPermissionsErrorPage( $out );
2590 if( $result == array( array('readonlytext') ) ) {
2591 $wgOut->readOnlyPage();
2595 $current = $details['current'];
2596 $target = $details['target'];
2597 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2598 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2599 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2600 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2601 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2602 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2603 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2604 $wgOut->returnToMain( false, $this->mTitle
);
2609 * Do standard deferred updates after page view
2612 function viewUpdates() {
2613 global $wgDeferredUpdateList, $wgUser;
2615 if ( 0 != $this->getID() ) {
2616 # Don't update page view counters on views from bot users (bug 14044)
2617 global $wgDisableCounters;
2618 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2619 Article
::incViewCount( $this->getID() );
2620 $u = new SiteStatsUpdate( 1, 0, 0 );
2621 array_push( $wgDeferredUpdateList, $u );
2625 # Update newtalk / watchlist notification status
2626 $wgUser->clearNotification( $this->mTitle
);
2630 * Prepare text which is about to be saved.
2631 * Returns a stdclass with source, pst and output members
2633 function prepareTextForEdit( $text, $revid=null ) {
2634 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2636 return $this->mPreparedEdit
;
2639 $edit = (object)array();
2640 $edit->revid
= $revid;
2641 $edit->newText
= $text;
2642 $edit->pst
= $this->preSaveTransform( $text );
2643 $options = new ParserOptions
;
2644 $options->setTidy( true );
2645 $options->enableLimitReport();
2646 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2647 $edit->oldText
= $this->getContent();
2648 $this->mPreparedEdit
= $edit;
2653 * Do standard deferred updates after page edit.
2654 * Update links tables, site stats, search index and message cache.
2655 * Every 100th edit, prune the recent changes table.
2658 * @param $text New text of the article
2659 * @param $summary Edit summary
2660 * @param $minoredit Minor edit
2661 * @param $timestamp_of_pagechange Timestamp associated with the page change
2662 * @param $newid rev_id value of the new revision
2663 * @param $changed Whether or not the content actually changed
2665 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2666 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2668 wfProfileIn( __METHOD__
);
2671 # Be careful not to double-PST: $text is usually already PST-ed once
2672 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2673 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2674 $editInfo = $this->prepareTextForEdit( $text, $newid );
2676 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2677 $editInfo = $this->mPreparedEdit
;
2680 # Save it to the parser cache
2681 if ( $wgEnableParserCache ) {
2682 $parserCache = ParserCache
::singleton();
2683 $parserCache->save( $editInfo->output
, $this, $wgUser );
2686 # Update the links tables
2687 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2690 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2691 if ( 0 == mt_rand( 0, 99 ) ) {
2692 // Flush old entries from the `recentchanges` table; we do this on
2693 // random requests so as to avoid an increase in writes for no good reason
2695 $dbw = wfGetDB( DB_MASTER
);
2696 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2697 $recentchanges = $dbw->tableName( 'recentchanges' );
2698 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2699 $dbw->query( $sql );
2703 $id = $this->getID();
2704 $title = $this->mTitle
->getPrefixedDBkey();
2705 $shortTitle = $this->mTitle
->getDBkey();
2708 wfProfileOut( __METHOD__
);
2712 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2713 array_push( $wgDeferredUpdateList, $u );
2714 $u = new SearchUpdate( $id, $title, $text );
2715 array_push( $wgDeferredUpdateList, $u );
2717 # If this is another user's talk page, update newtalk
2718 # Don't do this if $changed = false otherwise some idiot can null-edit a
2719 # load of user talk pages and piss people off, nor if it's a minor edit
2720 # by a properly-flagged bot.
2721 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2722 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2723 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2724 $other = User
::newFromName( $shortTitle );
2725 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2726 // An anonymous user
2727 $other = new User();
2728 $other->setName( $shortTitle );
2731 $other->setNewtalk( true );
2736 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2737 $wgMessageCache->replace( $shortTitle, $text );
2740 wfProfileOut( __METHOD__
);
2744 * Perform article updates on a special page creation.
2746 * @param Revision $rev
2748 * @todo This is a shitty interface function. Kill it and replace the
2749 * other shitty functions like editUpdates and such so it's not needed
2752 function createUpdates( $rev ) {
2753 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2754 $this->mTotalAdjustment
= 1;
2755 $this->editUpdates( $rev->getText(), $rev->getComment(),
2756 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2760 * Generate the navigation links when browsing through an article revisions
2761 * It shows the information as:
2762 * Revision as of \<date\>; view current revision
2763 * \<- Previous version | Next Version -\>
2766 * @param string $oldid Revision ID of this article revision
2768 function setOldSubtitle( $oldid=0 ) {
2769 global $wgLang, $wgOut, $wgUser;
2771 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2775 $revision = Revision
::newFromId( $oldid );
2777 $current = ( $oldid == $this->mLatest
);
2778 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2779 $sk = $wgUser->getSkin();
2781 ?
wfMsg( 'currentrevisionlink' )
2782 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2785 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2786 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2788 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2789 : wfMsg( 'previousrevision' );
2791 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2793 $nextlink = $current
2794 ?
wfMsg( 'nextrevision' )
2795 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2796 $nextdiff = $current
2798 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2801 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2802 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2803 if( $revision->isCurrent() ) {
2804 // We don't handle top deleted edits too well
2805 $cdel = wfMsgHtml('rev-delundel');
2806 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2807 // If revision was hidden from sysops
2808 $cdel = wfMsgHtml('rev-delundel');
2810 $cdel = $sk->makeKnownLinkObj( $revdel,
2811 wfMsgHtml('rev-delundel'),
2812 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2813 '&oldid=' . urlencode( $oldid ) );
2814 // Bolden oversighted content
2815 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2816 $cdel = "<strong>$cdel</strong>";
2818 $cdel = "(<small>$cdel</small>) ";
2820 # Show user links if allowed to see them. Normally they
2821 # are hidden regardless, but since we can already see the text here...
2822 $userlinks = $sk->revUserTools( $revision, false );
2824 $m = wfMsg( 'revision-info-current' );
2825 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2826 ?
'revision-info-current'
2829 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2831 "\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";
2832 $wgOut->setSubtitle( $r );
2836 * This function is called right before saving the wikitext,
2837 * so we can do things like signatures and links-in-context.
2839 * @param string $text
2841 function preSaveTransform( $text ) {
2842 global $wgParser, $wgUser;
2843 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2846 /* Caching functions */
2849 * checkLastModified returns true if it has taken care of all
2850 * output to the client that is necessary for this request.
2851 * (that is, it has sent a cached version of the page)
2853 function tryFileCache() {
2854 static $called = false;
2856 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2860 if($this->isFileCacheable()) {
2861 $touched = $this->mTouched
;
2862 $cache = new HTMLFileCache( $this->mTitle
);
2863 if($cache->isFileCacheGood( $touched )) {
2864 wfDebug( "Article::tryFileCache(): about to load file\n" );
2865 $cache->loadFromFileCache();
2868 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2869 ob_start( array(&$cache, 'saveToFileCache' ) );
2872 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2877 * Check if the page can be cached
2880 function isFileCacheable() {
2881 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2882 $action = $wgRequest->getVal( 'action' );
2883 $oldid = $wgRequest->getVal( 'oldid' );
2884 $diff = $wgRequest->getVal( 'diff' );
2885 $redirect = $wgRequest->getVal( 'redirect' );
2886 $printable = $wgRequest->getVal( 'printable' );
2887 $page = $wgRequest->getVal( 'page' );
2889 //check for non-standard user language; this covers uselang,
2890 //and extensions for auto-detecting user language.
2891 $ulang = $wgLang->getCode();
2892 $clang = $wgContLang->getCode();
2894 $cacheable = $wgUseFileCache
2895 && (!$wgShowIPinHeader)
2896 && ($this->getID() != 0)
2897 && ($wgUser->isAnon())
2898 && (!$wgUser->getNewtalk())
2899 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2900 && (empty( $action ) ||
$action == 'view')
2903 && (!isset($redirect))
2904 && (!isset($printable))
2906 && (!$this->mRedirectedFrom
)
2907 && ($ulang === $clang);
2910 //extension may have reason to disable file caching on some pages.
2911 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2918 * Loads page_touched and returns a value indicating if it should be used
2921 function checkTouched() {
2922 if( !$this->mDataLoaded
) {
2923 $this->loadPageData();
2925 return !$this->mIsRedirect
;
2929 * Get the page_touched field
2931 function getTouched() {
2932 # Ensure that page data has been loaded
2933 if( !$this->mDataLoaded
) {
2934 $this->loadPageData();
2936 return $this->mTouched
;
2940 * Get the page_latest field
2942 function getLatest() {
2943 if ( !$this->mDataLoaded
) {
2944 $this->loadPageData();
2946 return $this->mLatest
;
2950 * Edit an article without doing all that other stuff
2951 * The article must already exist; link tables etc
2952 * are not updated, caches are not flushed.
2954 * @param string $text text submitted
2955 * @param string $comment comment submitted
2956 * @param bool $minor whereas it's a minor modification
2958 function quickEdit( $text, $comment = '', $minor = 0 ) {
2959 wfProfileIn( __METHOD__
);
2961 $dbw = wfGetDB( DB_MASTER
);
2963 $revision = new Revision( array(
2964 'page' => $this->getId(),
2966 'comment' => $comment,
2967 'minor_edit' => $minor ?
1 : 0,
2969 $revision->insertOn( $dbw );
2970 $this->updateRevisionOn( $dbw, $revision );
2973 wfProfileOut( __METHOD__
);
2977 * Used to increment the view counter
2980 * @param integer $id article id
2982 function incViewCount( $id ) {
2983 $id = intval( $id );
2984 global $wgHitcounterUpdateFreq, $wgDBtype;
2986 $dbw = wfGetDB( DB_MASTER
);
2987 $pageTable = $dbw->tableName( 'page' );
2988 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2989 $acchitsTable = $dbw->tableName( 'acchits' );
2991 if( $wgHitcounterUpdateFreq <= 1 ) {
2992 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2996 # Not important enough to warrant an error page in case of failure
2997 $oldignore = $dbw->ignoreErrors( true );
2999 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3001 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3002 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3003 # Most of the time (or on SQL errors), skip row count check
3004 $dbw->ignoreErrors( $oldignore );
3008 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3009 $row = $dbw->fetchObject( $res );
3010 $rown = intval( $row->n
);
3011 if( $rown >= $wgHitcounterUpdateFreq ){
3012 wfProfileIn( 'Article::incViewCount-collect' );
3013 $old_user_abort = ignore_user_abort( true );
3015 if ($wgDBtype == 'mysql')
3016 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3017 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3018 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3019 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3021 $dbw->query("DELETE FROM $hitcounterTable");
3022 if ($wgDBtype == 'mysql') {
3023 $dbw->query('UNLOCK TABLES');
3024 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3025 'WHERE page_id = hc_id');
3028 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3029 "FROM $acchitsTable WHERE page_id = hc_id");
3031 $dbw->query("DROP TABLE $acchitsTable");
3033 ignore_user_abort( $old_user_abort );
3034 wfProfileOut( 'Article::incViewCount-collect' );
3036 $dbw->ignoreErrors( $oldignore );
3040 * The onArticle*() functions are supposed to be a kind of hooks
3041 * which should be called whenever any of the specified actions
3044 * This is a good place to put code to clear caches, for instance.
3046 * This is called on page move and undelete, as well as edit
3048 * @param $title_obj a title object
3051 static function onArticleCreate($title) {
3052 # The talk page isn't in the regular link tables, so we need to update manually:
3053 if ( $title->isTalkPage() ) {
3054 $other = $title->getSubjectPage();
3056 $other = $title->getTalkPage();
3058 $other->invalidateCache();
3059 $other->purgeSquid();
3061 $title->touchLinks();
3062 $title->purgeSquid();
3063 $title->deleteTitleProtection();
3066 static function onArticleDelete( $title ) {
3067 global $wgUseFileCache, $wgMessageCache;
3069 // Update existence markers on article/talk tabs...
3070 if( $title->isTalkPage() ) {
3071 $other = $title->getSubjectPage();
3073 $other = $title->getTalkPage();
3075 $other->invalidateCache();
3076 $other->purgeSquid();
3078 $title->touchLinks();
3079 $title->purgeSquid();
3082 if ( $wgUseFileCache ) {
3083 $cm = new HTMLFileCache( $title );
3084 @unlink
( $cm->fileCacheName() );
3087 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3088 $wgMessageCache->replace( $title->getDBkey(), false );
3090 if( $title->getNamespace() == NS_IMAGE
) {
3091 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3092 $update->doUpdate();
3097 * Purge caches on page update etc
3099 static function onArticleEdit( $title ) {
3100 global $wgDeferredUpdateList, $wgUseFileCache;
3102 // Invalidate caches of articles which include this page
3103 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3105 // Invalidate the caches of all pages which redirect here
3106 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3108 # Purge squid for this page only
3109 $title->purgeSquid();
3112 if ( $wgUseFileCache ) {
3113 $cm = new HTMLFileCache( $title );
3114 @unlink
( $cm->fileCacheName() );
3121 * Overriden by ImagePage class, only present here to avoid a fatal error
3122 * Called for ?action=revert
3124 public function revert(){
3126 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3130 * Info about this page
3131 * Called for ?action=info when $wgAllowPageInfo is on.
3136 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3138 if ( !$wgAllowPageInfo ) {
3139 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3143 $page = $this->mTitle
->getSubjectPage();
3145 $wgOut->setPagetitle( $page->getPrefixedText() );
3146 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3147 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3149 if( !$this->mTitle
->exists() ) {
3150 $wgOut->addHtml( '<div class="noarticletext">' );
3151 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3152 // This doesn't quite make sense; the user is asking for
3153 // information about the _page_, not the message... -- RC
3154 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3156 $msg = $wgUser->isLoggedIn()
3158 : 'noarticletextanon';
3159 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3161 $wgOut->addHtml( '</div>' );
3163 $dbr = wfGetDB( DB_SLAVE
);
3165 'wl_title' => $page->getDBkey(),
3166 'wl_namespace' => $page->getNamespace() );
3167 $numwatchers = $dbr->selectField(
3172 $this->getSelectOptions() );
3174 $pageInfo = $this->pageCountInfo( $page );
3175 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3177 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3178 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3180 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3182 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3184 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3186 $wgOut->addHTML( '</ul>' );
3192 * Return the total number of edits and number of unique editors
3193 * on a given page. If page does not exist, returns false.
3195 * @param Title $title
3199 function pageCountInfo( $title ) {
3200 $id = $title->getArticleId();
3205 $dbr = wfGetDB( DB_SLAVE
);
3207 $rev_clause = array( 'rev_page' => $id );
3209 $edits = $dbr->selectField(
3214 $this->getSelectOptions() );
3216 $authors = $dbr->selectField(
3218 'COUNT(DISTINCT rev_user_text)',
3221 $this->getSelectOptions() );
3223 return array( 'edits' => $edits, 'authors' => $authors );
3227 * Return a list of templates used by this article.
3228 * Uses the templatelinks table
3230 * @return array Array of Title objects
3232 function getUsedTemplates() {
3234 $id = $this->mTitle
->getArticleID();
3239 $dbr = wfGetDB( DB_SLAVE
);
3240 $res = $dbr->select( array( 'templatelinks' ),
3241 array( 'tl_namespace', 'tl_title' ),
3242 array( 'tl_from' => $id ),
3243 'Article:getUsedTemplates' );
3244 if ( false !== $res ) {
3245 if ( $dbr->numRows( $res ) ) {
3246 while ( $row = $dbr->fetchObject( $res ) ) {
3247 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3251 $dbr->freeResult( $res );
3256 * Returns a list of hidden categories this page is a member of.
3257 * Uses the page_props and categorylinks tables.
3259 * @return array Array of Title objects
3261 function getHiddenCategories() {
3263 $id = $this->mTitle
->getArticleID();
3268 $dbr = wfGetDB( DB_SLAVE
);
3269 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3271 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3272 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3273 'Article:getHiddenCategories' );
3274 if ( false !== $res ) {
3275 if ( $dbr->numRows( $res ) ) {
3276 while ( $row = $dbr->fetchObject( $res ) ) {
3277 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3281 $dbr->freeResult( $res );
3286 * Return an auto-generated summary if the text provided is a redirect.
3288 * @param string $text The wikitext to check
3289 * @return string '' or an appropriate summary
3291 public static function getRedirectAutosummary( $text ) {
3292 $rt = Title
::newFromRedirect( $text );
3293 if( is_object( $rt ) )
3294 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3300 * Return an auto-generated summary if the new text is much shorter than
3303 * @param string $oldtext The previous text of the page
3304 * @param string $text The submitted text of the page
3305 * @return string An appropriate autosummary, or an empty string.
3307 public static function getBlankingAutosummary( $oldtext, $text ) {
3308 if ($oldtext!='' && $text=='') {
3309 return wfMsgForContent('autosumm-blank');
3310 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3311 #Removing more than 90% of the article
3313 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3314 return wfMsgForContent('autosumm-replace', $truncatedtext);
3321 * Return an applicable autosummary if one exists for the given edit.
3322 * @param string $oldtext The previous text of the page.
3323 * @param string $newtext The submitted text of the page.
3324 * @param bitmask $flags A bitmask of flags submitted for the edit.
3325 * @return string An appropriate autosummary, or an empty string.
3327 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3328 global $wgUseAutomaticEditSummaries;
3329 if ( !$wgUseAutomaticEditSummaries ) return '';
3331 # This code is UGLY UGLY UGLY.
3332 # Somebody PLEASE come up with a more elegant way to do it.
3334 #Redirect autosummaries
3335 $summary = self
::getRedirectAutosummary( $newtext );
3340 #Blanking autosummaries
3341 if (!($flags & EDIT_NEW
))
3342 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3347 #New page autosummaries
3348 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3349 #If they're making a new article, give its text, truncated, in the summary.
3351 $truncatedtext = $wgContLang->truncate(
3352 str_replace("\n", ' ', $newtext),
3353 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3355 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3365 * Add the primary page-view wikitext to the output buffer
3366 * Saves the text into the parser cache if possible.
3367 * Updates templatelinks if it is out of date.
3369 * @param string $text
3370 * @param bool $cache
3372 public function outputWikiText( $text, $cache = true ) {
3373 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3375 $popts = $wgOut->parserOptions();
3376 $popts->setTidy(true);
3377 $popts->enableLimitReport();
3378 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3379 $popts, true, true, $this->getRevIdFetched() );
3380 $popts->setTidy(false);
3381 $popts->enableLimitReport( false );
3382 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3383 $parserCache = ParserCache
::singleton();
3384 $parserCache->save( $parserOutput, $this, $wgUser );
3387 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3388 // templatelinks table may have become out of sync,
3389 // especially if using variable-based transclusions.
3390 // For paranoia, check if things have changed and if
3391 // so apply updates to the database. This will ensure
3392 // that cascaded protections apply as soon as the changes
3395 # Get templates from templatelinks
3396 $id = $this->mTitle
->getArticleID();
3398 $tlTemplates = array();
3400 $dbr = wfGetDB( DB_SLAVE
);
3401 $res = $dbr->select( array( 'templatelinks' ),
3402 array( 'tl_namespace', 'tl_title' ),
3403 array( 'tl_from' => $id ),
3404 'Article:getUsedTemplates' );
3408 if ( false !== $res ) {
3409 if ( $dbr->numRows( $res ) ) {
3410 while ( $row = $dbr->fetchObject( $res ) ) {
3411 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3416 # Get templates from parser output.
3417 $poTemplates_allns = $parserOutput->getTemplates();
3419 $poTemplates = array ();
3420 foreach ( $poTemplates_allns as $ns_templates ) {
3421 $poTemplates = array_merge( $poTemplates, $ns_templates );
3425 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3427 if ( count( $templates_diff ) > 0 ) {
3428 # Whee, link updates time.
3429 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3431 $dbw = wfGetDb( DB_MASTER
);
3440 $wgOut->addParserOutput( $parserOutput );
3444 * Update all the appropriate counts in the category table, given that
3445 * we've added the categories $added and deleted the categories $deleted.
3447 * @param $added array The names of categories that were added
3448 * @param $deleted array The names of categories that were deleted
3451 public function updateCategoryCounts( $added, $deleted ) {
3452 $ns = $this->mTitle
->getNamespace();
3453 $dbw = wfGetDB( DB_MASTER
);
3455 # First make sure the rows exist. If one of the "deleted" ones didn't
3456 # exist, we might legitimately not create it, but it's simpler to just
3457 # create it and then give it a negative value, since the value is bogus
3460 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3461 $insertCats = array_merge( $added, $deleted );
3462 if( !$insertCats ) {
3463 # Okay, nothing to do
3466 $insertRows = array();
3467 foreach( $insertCats as $cat ) {
3468 $insertRows[] = array( 'cat_title' => $cat );
3470 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3472 $addFields = array( 'cat_pages = cat_pages + 1' );
3473 $removeFields = array( 'cat_pages = cat_pages - 1' );
3474 if( $ns == NS_CATEGORY
) {
3475 $addFields[] = 'cat_subcats = cat_subcats + 1';
3476 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3477 } elseif( $ns == NS_IMAGE
) {
3478 $addFields[] = 'cat_files = cat_files + 1';
3479 $removeFields[] = 'cat_files = cat_files - 1';
3486 array( 'cat_title' => $added ),
3494 array( 'cat_title' => $deleted ),