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.
1365 * @param $baseRevId, the revision ID this edit was based off, if any
1367 * @return bool success
1369 function doEdit( $text, $summary, $flags = 0, $baseRevId = false ) {
1370 global $wgUser, $wgDBtransactions;
1372 wfProfileIn( __METHOD__
);
1375 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1376 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1378 $flags |
= EDIT_UPDATE
;
1384 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1385 &$summary, $flags & EDIT_MINOR
,
1386 null, null, &$flags ) ) )
1388 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1389 wfProfileOut( __METHOD__
);
1393 # Silently ignore EDIT_MINOR if not allowed
1394 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1395 $bot = $flags & EDIT_FORCE_BOT
;
1397 $oldtext = $this->getContent();
1398 $oldsize = strlen( $oldtext );
1400 # Provide autosummaries if one is not provided.
1401 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1402 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1404 $editInfo = $this->prepareTextForEdit( $text );
1405 $text = $editInfo->pst
;
1406 $newsize = strlen( $text );
1408 $dbw = wfGetDB( DB_MASTER
);
1409 $now = wfTimestampNow();
1411 if ( $flags & EDIT_UPDATE
) {
1412 # Update article, but only if changed.
1414 # Make sure the revision is either completely inserted or not inserted at all
1415 if( !$wgDBtransactions ) {
1416 $userAbort = ignore_user_abort( true );
1422 $changed = ( strcmp( $text, $oldtext ) != 0 );
1425 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1426 - (int)$this->isCountable( $oldtext );
1427 $this->mTotalAdjustment
= 0;
1429 $lastRevision = $dbw->selectField(
1430 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1432 if ( !$lastRevision ) {
1433 # Article gone missing
1434 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1435 wfProfileOut( __METHOD__
);
1439 $revision = new Revision( array(
1440 'page' => $this->getId(),
1441 'comment' => $summary,
1442 'minor_edit' => $isminor,
1444 'parent_id' => $lastRevision
1448 $revisionId = $revision->insertOn( $dbw );
1450 wfRunHooks( 'newRevisionFromEditComplete', array($this->mTitle
, $revision, $baseRevId) );
1453 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1456 /* Belated edit conflict! Run away!! */
1460 # Update recentchanges
1461 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1462 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1463 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1466 # Mark as patrolled if the user can do so
1467 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1468 RecentChange
::markPatrolled( $rcid );
1469 PatrolLog
::record( $rcid, true );
1472 $wgUser->incEditCount();
1477 // Keep the same revision ID, but do some updates on it
1478 $revisionId = $this->getRevIdFetched();
1479 // Update page_touched, this is usually implicit in the page update
1480 // Other cache updates are done in onArticleEdit()
1481 $this->mTitle
->invalidateCache();
1484 if( !$wgDBtransactions ) {
1485 ignore_user_abort( $userAbort );
1489 # Invalidate cache of this article and all pages using this article
1490 # as a template. Partly deferred.
1491 Article
::onArticleEdit( $this->mTitle
);
1493 # Update links tables, site stats, etc.
1494 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1497 # Create new article
1499 # Set statistics members
1500 # We work out if it's countable after PST to avoid counter drift
1501 # when articles are created with {{subst:}}
1502 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1503 $this->mTotalAdjustment
= 1;
1507 # Add the page record; stake our claim on this title!
1508 # This will fail with a database query exception if the article already exists
1509 $newid = $this->insertOn( $dbw );
1511 # Save the revision text...
1512 $revision = new Revision( array(
1514 'comment' => $summary,
1515 'minor_edit' => $isminor,
1518 $revisionId = $revision->insertOn( $dbw );
1520 wfRunHooks( 'newRevisionFromEditComplete', array($this->mTitle
, $revision, false) );
1522 $this->mTitle
->resetArticleID( $newid );
1524 # Update the page record with revision data
1525 $this->updateRevisionOn( $dbw, $revision, 0 );
1527 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1528 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1529 '', strlen( $text ), $revisionId );
1530 # Mark as patrolled if the user can
1531 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1532 RecentChange
::markPatrolled( $rcid );
1533 PatrolLog
::record( $rcid, true );
1536 $wgUser->incEditCount();
1539 # Update links, etc.
1540 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1543 Article
::onArticleCreate( $this->mTitle
);
1545 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1546 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1549 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1554 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1555 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1558 wfProfileOut( __METHOD__
);
1563 * @deprecated wrapper for doRedirect
1565 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1566 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1570 * Output a redirect back to the article.
1571 * This is typically used after an edit.
1573 * @param boolean $noRedir Add redirect=no
1574 * @param string $sectionAnchor section to redirect to, including "#"
1575 * @param string $extraq, extra query params
1577 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1580 $query = 'redirect=no';
1582 $query .= "&$query";
1586 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1590 * Mark this particular edit/page as patrolled
1592 function markpatrolled() {
1593 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1594 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1596 # Check patrol config options
1598 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1599 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1603 # If we haven't been given an rc_id value, we can't do anything
1604 $rcid = (int) $wgRequest->getVal('rcid');
1605 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1606 if ( is_null ( $rc ) )
1608 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1612 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1613 // Only new pages can be patrolled if the general patrolling is off....???
1614 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1616 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1621 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1623 if (count($permission_errors)>0)
1625 $wgOut->showPermissionsErrorPage( $permission_errors );
1629 # Handle the 'MarkPatrolled' hook
1630 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1634 #It would be nice to see where the user had actually come from, but for now just guess
1635 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1636 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1638 # If it's left up to us, check that the user is allowed to patrol this edit
1639 # If the user has the "autopatrol" right, then we'll assume there are no
1640 # other conditions stopping them doing so
1641 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1642 $rc = RecentChange
::newFromId( $rcid );
1643 # Graceful error handling, as we've done before here...
1644 # (If the recent change doesn't exist, then it doesn't matter whether
1645 # the user is allowed to patrol it or not; nothing is going to happen
1646 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1647 # The user made this edit, and can't patrol it
1648 # Tell them so, and then back off
1649 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1650 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1651 $wgOut->returnToMain( false, $return );
1656 # Check that the revision isn't patrolled already
1657 # Prevents duplicate log entries
1658 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1659 # Mark the edit as patrolled
1660 RecentChange
::markPatrolled( $rcid );
1661 PatrolLog
::record( $rcid );
1662 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1666 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1667 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1668 $wgOut->returnToMain( false, $return );
1672 * User-interface handler for the "watch" action
1677 global $wgUser, $wgOut;
1679 if ( $wgUser->isAnon() ) {
1680 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1683 if ( wfReadOnly() ) {
1684 $wgOut->readOnlyPage();
1688 if( $this->doWatch() ) {
1689 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1690 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1692 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1695 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1699 * Add this page to $wgUser's watchlist
1700 * @return bool true on successful watch operation
1702 function doWatch() {
1704 if( $wgUser->isAnon() ) {
1708 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1709 $wgUser->addWatch( $this->mTitle
);
1711 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1718 * User interface handler for the "unwatch" action.
1720 function unwatch() {
1722 global $wgUser, $wgOut;
1724 if ( $wgUser->isAnon() ) {
1725 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1728 if ( wfReadOnly() ) {
1729 $wgOut->readOnlyPage();
1733 if( $this->doUnwatch() ) {
1734 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1735 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1737 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1740 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1744 * Stop watching a page
1745 * @return bool true on successful unwatch
1747 function doUnwatch() {
1749 if( $wgUser->isAnon() ) {
1753 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1754 $wgUser->removeWatch( $this->mTitle
);
1756 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1763 * action=protect handler
1765 function protect() {
1766 $form = new ProtectionForm( $this );
1771 * action=unprotect handler (alias)
1773 function unprotect() {
1778 * Update the article's restriction field, and leave a log entry.
1780 * @param array $limit set of restriction keys
1781 * @param string $reason
1782 * @return bool true on success
1784 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1785 global $wgUser, $wgRestrictionTypes, $wgContLang;
1787 $id = $this->mTitle
->getArticleID();
1788 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1796 // Take this opportunity to purge out expired restrictions
1797 Title
::purgeExpiredRestrictions();
1799 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1800 # we expect a single selection, but the schema allows otherwise.
1802 foreach( $wgRestrictionTypes as $action )
1803 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1805 $current = Article
::flattenRestrictions( $current );
1806 $updated = Article
::flattenRestrictions( $limit );
1808 $changed = ( $current != $updated );
1809 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1810 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1811 $protect = ( $updated != '' );
1813 # If nothing's changed, do nothing
1815 global $wgGroupPermissions;
1816 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1818 $dbw = wfGetDB( DB_MASTER
);
1820 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1822 $expiry_description = '';
1823 if ( $encodedExpiry != 'infinity' ) {
1824 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1827 # Prepare a null revision to be added to the history
1828 $modified = $current != '' && $protect;
1830 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1832 $comment_type = 'unprotectedarticle';
1834 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1836 foreach( $limit as $action => $restrictions ) {
1837 # Check if the group level required to edit also can protect pages
1838 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1839 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1840 $wgGroupPermissions[$restrictions]['protect'] );
1843 $cascade_description = '';
1845 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1849 $comment .= ": $reason";
1851 $comment .= " [$updated]";
1852 if ( $expiry_description && $protect )
1853 $comment .= "$expiry_description";
1855 $comment .= "$cascade_description";
1857 # Update restrictions table
1858 foreach( $limit as $action => $restrictions ) {
1859 if ($restrictions != '' ) {
1860 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1861 array( 'pr_page' => $id, 'pr_type' => $action
1862 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1863 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1865 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1866 'pr_type' => $action ), __METHOD__
);
1870 # Insert a null revision
1871 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1872 $nullRevId = $nullRevision->insertOn( $dbw );
1874 wfRunHooks( 'newRevisionFromEditComplete', array($this->mTitle
, $nullRevision, false) );
1876 # Update page record
1877 $dbw->update( 'page',
1879 'page_touched' => $dbw->timestamp(),
1880 'page_restrictions' => '',
1881 'page_latest' => $nullRevId
1882 ), array( /* WHERE */
1884 ), 'Article::protect'
1886 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1888 # Update the protection log
1889 $log = new LogPage( 'protect' );
1891 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1893 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1897 } # End "changed" check
1903 * Take an array of page restrictions and flatten it to a string
1904 * suitable for insertion into the page_restrictions field.
1905 * @param array $limit
1909 function flattenRestrictions( $limit ) {
1910 if( !is_array( $limit ) ) {
1911 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1915 foreach( $limit as $action => $restrictions ) {
1916 if( $restrictions != '' ) {
1917 $bits[] = "$action=$restrictions";
1920 return implode( ':', $bits );
1924 * Auto-generates a deletion reason
1925 * @param bool &$hasHistory Whether the page has a history
1927 public function generateReason(&$hasHistory)
1930 $dbw = wfGetDB(DB_MASTER
);
1931 // Get the last revision
1932 $rev = Revision
::newFromTitle($this->mTitle
);
1935 // Get the article's contents
1936 $contents = $rev->getText();
1938 // If the page is blank, use the text from the previous revision,
1939 // which can only be blank if there's a move/import/protect dummy revision involved
1942 $prev = $rev->getPrevious();
1945 $contents = $prev->getText();
1950 // Find out if there was only one contributor
1951 // Only scan the last 20 revisions
1953 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1954 array('LIMIT' => $limit));
1956 // This page has no revisions, which is very weird
1958 if($res->numRows() > 1)
1961 $hasHistory = false;
1962 $row = $dbw->fetchObject($res);
1963 $onlyAuthor = $row->rev_user_text
;
1964 // Try to find a second contributor
1965 while( $row = $dbw->fetchObject($res) ) {
1966 if($row->rev_user_text
!= $onlyAuthor) {
1967 $onlyAuthor = false;
1971 $dbw->freeResult($res);
1973 // Generate the summary with a '$1' placeholder
1975 // The current revision is blank and the one before is also
1976 // blank. It's just not our lucky day
1977 $reason = wfMsgForContent('exbeforeblank', '$1');
1980 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1982 $reason = wfMsgForContent('excontent', '$1');
1985 // Replace newlines with spaces to prevent uglyness
1986 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1987 // Calculate the maximum amount of chars to get
1988 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1989 $maxLength = 255 - (strlen($reason) - 2) - 3;
1990 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1991 // Remove possible unfinished links
1992 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1993 // Now replace the '$1' placeholder
1994 $reason = str_replace( '$1', $contents, $reason );
2000 * UI entry point for page deletion
2003 global $wgUser, $wgOut, $wgRequest;
2005 $confirm = $wgRequest->wasPosted() &&
2006 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2008 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2009 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2011 $reason = $this->DeleteReasonList
;
2013 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2014 // Entry from drop down menu + additional comment
2015 $reason .= ': ' . $this->DeleteReason
;
2016 } elseif ( $reason == 'other' ) {
2017 $reason = $this->DeleteReason
;
2019 # Flag to hide all contents of the archived revisions
2020 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('hiderevision');
2022 # This code desperately needs to be totally rewritten
2024 # Read-only check...
2025 if ( wfReadOnly() ) {
2026 $wgOut->readOnlyPage();
2031 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2033 if (count($permission_errors)>0) {
2034 $wgOut->showPermissionsErrorPage( $permission_errors );
2038 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2040 # Better double-check that it hasn't been deleted yet!
2041 $dbw = wfGetDB( DB_MASTER
);
2042 $conds = $this->mTitle
->pageCond();
2043 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2044 if ( $latest === false ) {
2045 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2049 # Hack for big sites
2050 $bigHistory = $this->isBigDeletion();
2051 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2052 global $wgLang, $wgDeleteRevisionsLimit;
2053 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2054 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2059 $this->doDelete( $reason, $suppress );
2060 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2062 } elseif( $this->mTitle
->userIsWatching() ) {
2068 // Generate deletion reason
2069 $hasHistory = false;
2070 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2072 // If the page has a history, insert a warning
2073 if( $hasHistory && !$confirm ) {
2074 $skin=$wgUser->getSkin();
2075 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2077 global $wgLang, $wgDeleteRevisionsLimit;
2078 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2079 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2083 return $this->confirmDelete( '', $reason );
2087 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2089 function isBigDeletion() {
2090 global $wgDeleteRevisionsLimit;
2091 if( $wgDeleteRevisionsLimit ) {
2092 $revCount = $this->estimateRevisionCount();
2093 return $revCount > $wgDeleteRevisionsLimit;
2099 * @return int approximate revision count
2101 function estimateRevisionCount() {
2103 // For an exact count...
2104 //return $dbr->selectField( 'revision', 'COUNT(*)',
2105 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2106 return $dbr->estimateRowCount( 'revision', '*',
2107 array( 'rev_page' => $this->getId() ), __METHOD__
);
2111 * Get the last N authors
2112 * @param int $num Number of revisions to get
2113 * @param string $revLatest The latest rev_id, selected from the master (optional)
2114 * @return array Array of authors, duplicates not removed
2116 function getLastNAuthors( $num, $revLatest = 0 ) {
2117 wfProfileIn( __METHOD__
);
2119 // First try the slave
2120 // If that doesn't have the latest revision, try the master
2122 $db = wfGetDB( DB_SLAVE
);
2124 $res = $db->select( array( 'page', 'revision' ),
2125 array( 'rev_id', 'rev_user_text' ),
2127 'page_namespace' => $this->mTitle
->getNamespace(),
2128 'page_title' => $this->mTitle
->getDBkey(),
2129 'rev_page = page_id'
2130 ), __METHOD__
, $this->getSelectOptions( array(
2131 'ORDER BY' => 'rev_timestamp DESC',
2136 wfProfileOut( __METHOD__
);
2139 $row = $db->fetchObject( $res );
2140 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2141 $db = wfGetDB( DB_MASTER
);
2146 } while ( $continue );
2148 $authors = array( $row->rev_user_text
);
2149 while ( $row = $db->fetchObject( $res ) ) {
2150 $authors[] = $row->rev_user_text
;
2152 wfProfileOut( __METHOD__
);
2157 * Output deletion confirmation dialog
2158 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2159 * @param $reason string Prefilled reason
2161 function confirmDelete( $par, $reason ) {
2162 global $wgOut, $wgUser, $wgContLang;
2163 $align = $wgContLang->isRtl() ?
'left' : 'right';
2165 wfDebug( "Article::confirmDelete\n" );
2167 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2168 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2169 $wgOut->addWikiMsg( 'confirmdeletetext' );
2171 if( $wgUser->isAllowed( 'hiderevision' ) ) {
2172 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2173 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2174 $suppress .= "</td></tr>";
2179 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2180 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2181 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2182 Xml
::openElement( 'table' ) .
2183 "<tr id=\"wpDeleteReasonListRow\">
2184 <td align='$align'>" .
2185 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2188 Xml
::listDropDown( 'wpDeleteReasonList',
2189 wfMsgForContent( 'deletereason-dropdown' ),
2190 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2193 <tr id=\"wpDeleteReasonRow\">
2194 <td align='$align'>" .
2195 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2198 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2204 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2211 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2214 Xml
::closeElement( 'table' ) .
2215 Xml
::closeElement( 'fieldset' ) .
2216 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2217 Xml
::closeElement( 'form' );
2219 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2220 $skin = $wgUser->getSkin();
2221 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2222 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2225 $wgOut->addHTML( $form );
2226 $this->showLogExtract( $wgOut );
2231 * Show relevant lines from the deletion log
2233 function showLogExtract( $out ) {
2234 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2235 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2240 * Perform a deletion and output success or failure messages
2242 function doDelete( $reason, $suppress = false ) {
2243 global $wgOut, $wgUser;
2244 wfDebug( __METHOD__
."\n" );
2246 $id = $this->getId();
2248 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2249 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2250 $deleted = $this->mTitle
->getPrefixedText();
2252 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2253 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2255 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2257 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2258 $wgOut->returnToMain( false );
2259 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2261 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2267 * Back-end article deletion
2268 * Deletes the article with database consistency, writes logs, purges caches
2271 function doDeleteArticle( $reason, $suppress = false ) {
2272 global $wgUseSquid, $wgDeferredUpdateList;
2273 global $wgUseTrackbacks;
2275 wfDebug( __METHOD__
."\n" );
2277 $dbw = wfGetDB( DB_MASTER
);
2278 $ns = $this->mTitle
->getNamespace();
2279 $t = $this->mTitle
->getDBkey();
2280 $id = $this->mTitle
->getArticleID();
2282 if ( $t == '' ||
$id == 0 ) {
2286 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2287 array_push( $wgDeferredUpdateList, $u );
2289 // Bitfields to further suppress the content
2292 // This should be 15...
2293 $bitfield |
= Revision
::DELETED_TEXT
;
2294 $bitfield |
= Revision
::DELETED_COMMENT
;
2295 $bitfield |
= Revision
::DELETED_USER
;
2296 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2298 $bitfield = 'rev_deleted';
2302 // For now, shunt the revision data into the archive table.
2303 // Text is *not* removed from the text table; bulk storage
2304 // is left intact to avoid breaking block-compression or
2305 // immutable storage schemes.
2307 // For backwards compatibility, note that some older archive
2308 // table entries will have ar_text and ar_flags fields still.
2310 // In the future, we may keep revisions and mark them with
2311 // the rev_deleted field, which is reserved for this purpose.
2312 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2314 'ar_namespace' => 'page_namespace',
2315 'ar_title' => 'page_title',
2316 'ar_comment' => 'rev_comment',
2317 'ar_user' => 'rev_user',
2318 'ar_user_text' => 'rev_user_text',
2319 'ar_timestamp' => 'rev_timestamp',
2320 'ar_minor_edit' => 'rev_minor_edit',
2321 'ar_rev_id' => 'rev_id',
2322 'ar_text_id' => 'rev_text_id',
2323 'ar_text' => '\'\'', // Be explicit to appease
2324 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2325 'ar_len' => 'rev_len',
2326 'ar_page_id' => 'page_id',
2327 'ar_deleted' => $bitfield
2330 'page_id = rev_page'
2334 # Delete restrictions for it
2335 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2337 # Fix category table counts
2339 $res = $dbw->select( 'categorylinks', 'cl_to',
2340 array( 'cl_from' => $id ), __METHOD__
);
2341 foreach( $res as $row ) {
2342 $cats []= $row->cl_to
;
2344 $this->updateCategoryCounts( array(), $cats );
2346 # Now that it's safely backed up, delete it
2347 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2348 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2354 # If using cascading deletes, we can skip some explicit deletes
2355 if ( !$dbw->cascadingDeletes() ) {
2356 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2358 if ($wgUseTrackbacks)
2359 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2361 # Delete outgoing links
2362 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2363 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2364 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2365 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2366 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2367 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2368 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2371 # If using cleanup triggers, we can skip some manual deletes
2372 if ( !$dbw->cleanupTriggers() ) {
2374 # Clean up recentchanges entries...
2375 $dbw->delete( 'recentchanges',
2376 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2382 Article
::onArticleDelete( $this->mTitle
);
2384 # Clear the cached article id so the interface doesn't act like we exist
2385 $this->mTitle
->resetArticleID( 0 );
2386 $this->mTitle
->mArticleID
= 0;
2388 # Log the deletion, if the page was suppressed, log it at Oversight instead
2389 $logtype = $suppress ?
'suppress' : 'delete';
2390 $log = new LogPage( $logtype );
2392 # Make sure logging got through
2393 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2399 * Roll back the most recent consecutive set of edits to a page
2400 * from the same user; fails if there are no eligible edits to
2401 * roll back to, e.g. user is the sole contributor. This function
2402 * performs permissions checks on $wgUser, then calls commitRollback()
2403 * to do the dirty work
2405 * @param string $fromP - Name of the user whose edits to rollback.
2406 * @param string $summary - Custom summary. Set to default summary if empty.
2407 * @param string $token - Rollback token.
2408 * @param bool $bot - If true, mark all reverted edits as bot.
2410 * @param array $resultDetails contains result-specific array of additional values
2411 * 'alreadyrolled' : 'current' (rev)
2412 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2414 * @return array of errors, each error formatted as
2415 * array(messagekey, param1, param2, ...).
2416 * On success, the array is empty. This array can also be passed to
2417 * OutputPage::showPermissionsErrorPage().
2419 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2421 $resultDetails = null;
2424 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2425 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2426 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2427 $errors[] = array( 'sessionfailure' );
2429 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2430 $errors[] = array( 'actionthrottledtext' );
2432 # If there were errors, bail out now
2436 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2440 * Backend implementation of doRollback(), please refer there for parameter
2441 * and return value documentation
2443 * NOTE: This function does NOT check ANY permissions, it just commits the
2444 * rollback to the DB Therefore, you should only call this function direct-
2445 * ly if you want to use custom permissions checks. If you don't, use
2446 * doRollback() instead.
2448 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2449 global $wgUseRCPatrol, $wgUser, $wgLang;
2450 $dbw = wfGetDB( DB_MASTER
);
2452 if( wfReadOnly() ) {
2453 return array( array( 'readonlytext' ) );
2456 # Get the last editor
2457 $current = Revision
::newFromTitle( $this->mTitle
);
2458 if( is_null( $current ) ) {
2459 # Something wrong... no page?
2460 return array(array('notanarticle'));
2463 $from = str_replace( '_', ' ', $fromP );
2464 if( $from != $current->getUserText() ) {
2465 $resultDetails = array( 'current' => $current );
2466 return array(array('alreadyrolled',
2467 htmlspecialchars($this->mTitle
->getPrefixedText()),
2468 htmlspecialchars($fromP),
2469 htmlspecialchars($current->getUserText())
2473 # Get the last edit not by this guy
2474 $user = intval( $current->getUser() );
2475 $user_text = $dbw->addQuotes( $current->getUserText() );
2476 $s = $dbw->selectRow( 'revision',
2477 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2478 array( 'rev_page' => $current->getPage(),
2479 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2481 array( 'USE INDEX' => 'page_timestamp',
2482 'ORDER BY' => 'rev_timestamp DESC' )
2484 if( $s === false ) {
2485 # No one else ever edited this page
2486 return array(array('cantrollback'));
2487 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2488 # Only admins can see this text
2489 return array(array('notvisiblerev'));
2493 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2494 # Mark all reverted edits as bot
2497 if ( $wgUseRCPatrol ) {
2498 # Mark all reverted edits as patrolled
2499 $set['rc_patrolled'] = 1;
2503 $dbw->update( 'recentchanges', $set,
2505 'rc_cur_id' => $current->getPage(),
2506 'rc_user_text' => $current->getUserText(),
2507 "rc_timestamp > '{$s->rev_timestamp}'",
2512 # Generate the edit summary if necessary
2513 $target = Revision
::newFromId( $s->rev_id
);
2514 if( empty( $summary ) ){
2515 $summary = wfMsgForContent( 'revertpage' );
2518 # Allow the custom summary to use the same args as the default message
2520 $target->getUserText(), $from, $s->rev_id
,
2521 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2522 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2524 $summary = wfMsgReplaceArgs( $summary, $args );
2527 $flags = EDIT_UPDATE
;
2529 if ($wgUser->isAllowed('minoredit'))
2530 $flags |
= EDIT_MINOR
;
2532 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2533 $flags |
= EDIT_FORCE_BOT
;
2534 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2536 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2538 $resultDetails = array(
2539 'summary' => $summary,
2540 'current' => $current,
2541 'target' => $target,
2547 * User interface for rollback operations
2549 function rollback() {
2550 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2553 $result = $this->doRollback(
2554 $wgRequest->getVal( 'from' ),
2555 $wgRequest->getText( 'summary' ),
2556 $wgRequest->getVal( 'token' ),
2557 $wgRequest->getBool( 'bot' ),
2561 if( in_array( array( 'blocked' ), $result ) ) {
2562 $wgOut->blockedPage();
2565 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2566 $wgOut->rateLimited();
2569 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2570 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2571 $errArray = $result[0];
2572 $errMsg = array_shift( $errArray );
2573 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2574 if( isset( $details['current'] ) ){
2575 $current = $details['current'];
2576 if( $current->getComment() != '' ) {
2577 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2582 # Display permissions errors before read-only message -- there's no
2583 # point in misleading the user into thinking the inability to rollback
2584 # is only temporary.
2585 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2586 # array_diff is completely broken for arrays of arrays, sigh. Re-
2587 # move any 'readonlytext' error manually.
2589 foreach( $result as $error ) {
2590 if( $error != array( 'readonlytext' ) ) {
2594 $wgOut->showPermissionsErrorPage( $out );
2597 if( $result == array( array('readonlytext') ) ) {
2598 $wgOut->readOnlyPage();
2602 $current = $details['current'];
2603 $target = $details['target'];
2604 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2605 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2606 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2607 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2608 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2609 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2610 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2611 $wgOut->returnToMain( false, $this->mTitle
);
2616 * Do standard deferred updates after page view
2619 function viewUpdates() {
2620 global $wgDeferredUpdateList, $wgUser;
2622 if ( 0 != $this->getID() ) {
2623 # Don't update page view counters on views from bot users (bug 14044)
2624 global $wgDisableCounters;
2625 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2626 Article
::incViewCount( $this->getID() );
2627 $u = new SiteStatsUpdate( 1, 0, 0 );
2628 array_push( $wgDeferredUpdateList, $u );
2632 # Update newtalk / watchlist notification status
2633 $wgUser->clearNotification( $this->mTitle
);
2637 * Prepare text which is about to be saved.
2638 * Returns a stdclass with source, pst and output members
2640 function prepareTextForEdit( $text, $revid=null ) {
2641 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2643 return $this->mPreparedEdit
;
2646 $edit = (object)array();
2647 $edit->revid
= $revid;
2648 $edit->newText
= $text;
2649 $edit->pst
= $this->preSaveTransform( $text );
2650 $options = new ParserOptions
;
2651 $options->setTidy( true );
2652 $options->enableLimitReport();
2653 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2654 $edit->oldText
= $this->getContent();
2655 $this->mPreparedEdit
= $edit;
2660 * Do standard deferred updates after page edit.
2661 * Update links tables, site stats, search index and message cache.
2662 * Every 100th edit, prune the recent changes table.
2665 * @param $text New text of the article
2666 * @param $summary Edit summary
2667 * @param $minoredit Minor edit
2668 * @param $timestamp_of_pagechange Timestamp associated with the page change
2669 * @param $newid rev_id value of the new revision
2670 * @param $changed Whether or not the content actually changed
2672 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2673 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2675 wfProfileIn( __METHOD__
);
2678 # Be careful not to double-PST: $text is usually already PST-ed once
2679 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2680 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2681 $editInfo = $this->prepareTextForEdit( $text, $newid );
2683 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2684 $editInfo = $this->mPreparedEdit
;
2687 # Save it to the parser cache
2688 if ( $wgEnableParserCache ) {
2689 $parserCache = ParserCache
::singleton();
2690 $parserCache->save( $editInfo->output
, $this, $wgUser );
2693 # Update the links tables
2694 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2697 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2698 if ( 0 == mt_rand( 0, 99 ) ) {
2699 // Flush old entries from the `recentchanges` table; we do this on
2700 // random requests so as to avoid an increase in writes for no good reason
2702 $dbw = wfGetDB( DB_MASTER
);
2703 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2704 $recentchanges = $dbw->tableName( 'recentchanges' );
2705 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2706 $dbw->query( $sql );
2710 $id = $this->getID();
2711 $title = $this->mTitle
->getPrefixedDBkey();
2712 $shortTitle = $this->mTitle
->getDBkey();
2715 wfProfileOut( __METHOD__
);
2719 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2720 array_push( $wgDeferredUpdateList, $u );
2721 $u = new SearchUpdate( $id, $title, $text );
2722 array_push( $wgDeferredUpdateList, $u );
2724 # If this is another user's talk page, update newtalk
2725 # Don't do this if $changed = false otherwise some idiot can null-edit a
2726 # load of user talk pages and piss people off, nor if it's a minor edit
2727 # by a properly-flagged bot.
2728 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2729 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2730 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2731 $other = User
::newFromName( $shortTitle );
2732 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2733 // An anonymous user
2734 $other = new User();
2735 $other->setName( $shortTitle );
2738 $other->setNewtalk( true );
2743 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2744 $wgMessageCache->replace( $shortTitle, $text );
2747 wfProfileOut( __METHOD__
);
2751 * Perform article updates on a special page creation.
2753 * @param Revision $rev
2755 * @todo This is a shitty interface function. Kill it and replace the
2756 * other shitty functions like editUpdates and such so it's not needed
2759 function createUpdates( $rev ) {
2760 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2761 $this->mTotalAdjustment
= 1;
2762 $this->editUpdates( $rev->getText(), $rev->getComment(),
2763 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2767 * Generate the navigation links when browsing through an article revisions
2768 * It shows the information as:
2769 * Revision as of \<date\>; view current revision
2770 * \<- Previous version | Next Version -\>
2773 * @param string $oldid Revision ID of this article revision
2775 function setOldSubtitle( $oldid=0 ) {
2776 global $wgLang, $wgOut, $wgUser;
2778 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2782 $revision = Revision
::newFromId( $oldid );
2784 $current = ( $oldid == $this->mLatest
);
2785 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2786 $sk = $wgUser->getSkin();
2788 ?
wfMsg( 'currentrevisionlink' )
2789 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2792 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2793 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2795 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2796 : wfMsg( 'previousrevision' );
2798 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2800 $nextlink = $current
2801 ?
wfMsg( 'nextrevision' )
2802 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2803 $nextdiff = $current
2805 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2808 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2809 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2810 if( $revision->isCurrent() ) {
2811 // We don't handle top deleted edits too well
2812 $cdel = wfMsgHtml('rev-delundel');
2813 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2814 // If revision was hidden from sysops
2815 $cdel = wfMsgHtml('rev-delundel');
2817 $cdel = $sk->makeKnownLinkObj( $revdel,
2818 wfMsgHtml('rev-delundel'),
2819 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2820 '&oldid=' . urlencode( $oldid ) );
2821 // Bolden oversighted content
2822 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2823 $cdel = "<strong>$cdel</strong>";
2825 $cdel = "(<small>$cdel</small>) ";
2827 # Show user links if allowed to see them. Normally they
2828 # are hidden regardless, but since we can already see the text here...
2829 $userlinks = $sk->revUserTools( $revision, false );
2831 $m = wfMsg( 'revision-info-current' );
2832 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2833 ?
'revision-info-current'
2836 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2838 "\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";
2839 $wgOut->setSubtitle( $r );
2843 * This function is called right before saving the wikitext,
2844 * so we can do things like signatures and links-in-context.
2846 * @param string $text
2848 function preSaveTransform( $text ) {
2849 global $wgParser, $wgUser;
2850 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2853 /* Caching functions */
2856 * checkLastModified returns true if it has taken care of all
2857 * output to the client that is necessary for this request.
2858 * (that is, it has sent a cached version of the page)
2860 function tryFileCache() {
2861 static $called = false;
2863 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2867 if($this->isFileCacheable()) {
2868 $touched = $this->mTouched
;
2869 $cache = new HTMLFileCache( $this->mTitle
);
2870 if($cache->isFileCacheGood( $touched )) {
2871 wfDebug( "Article::tryFileCache(): about to load file\n" );
2872 $cache->loadFromFileCache();
2875 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2876 ob_start( array(&$cache, 'saveToFileCache' ) );
2879 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2884 * Check if the page can be cached
2887 function isFileCacheable() {
2888 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2889 $action = $wgRequest->getVal( 'action' );
2890 $oldid = $wgRequest->getVal( 'oldid' );
2891 $diff = $wgRequest->getVal( 'diff' );
2892 $redirect = $wgRequest->getVal( 'redirect' );
2893 $printable = $wgRequest->getVal( 'printable' );
2894 $page = $wgRequest->getVal( 'page' );
2896 //check for non-standard user language; this covers uselang,
2897 //and extensions for auto-detecting user language.
2898 $ulang = $wgLang->getCode();
2899 $clang = $wgContLang->getCode();
2901 $cacheable = $wgUseFileCache
2902 && (!$wgShowIPinHeader)
2903 && ($this->getID() != 0)
2904 && ($wgUser->isAnon())
2905 && (!$wgUser->getNewtalk())
2906 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2907 && (empty( $action ) ||
$action == 'view')
2910 && (!isset($redirect))
2911 && (!isset($printable))
2913 && (!$this->mRedirectedFrom
)
2914 && ($ulang === $clang);
2917 //extension may have reason to disable file caching on some pages.
2918 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2925 * Loads page_touched and returns a value indicating if it should be used
2928 function checkTouched() {
2929 if( !$this->mDataLoaded
) {
2930 $this->loadPageData();
2932 return !$this->mIsRedirect
;
2936 * Get the page_touched field
2938 function getTouched() {
2939 # Ensure that page data has been loaded
2940 if( !$this->mDataLoaded
) {
2941 $this->loadPageData();
2943 return $this->mTouched
;
2947 * Get the page_latest field
2949 function getLatest() {
2950 if ( !$this->mDataLoaded
) {
2951 $this->loadPageData();
2953 return $this->mLatest
;
2957 * Edit an article without doing all that other stuff
2958 * The article must already exist; link tables etc
2959 * are not updated, caches are not flushed.
2961 * @param string $text text submitted
2962 * @param string $comment comment submitted
2963 * @param bool $minor whereas it's a minor modification
2965 function quickEdit( $text, $comment = '', $minor = 0 ) {
2966 wfProfileIn( __METHOD__
);
2968 $dbw = wfGetDB( DB_MASTER
);
2970 $revision = new Revision( array(
2971 'page' => $this->getId(),
2973 'comment' => $comment,
2974 'minor_edit' => $minor ?
1 : 0,
2976 $revision->insertOn( $dbw );
2977 wfRunHooks( 'newRevisionFromEditComplete', array($this->mTitle
, $revision, false) );
2978 $this->updateRevisionOn( $dbw, $revision );
2981 wfProfileOut( __METHOD__
);
2985 * Used to increment the view counter
2988 * @param integer $id article id
2990 function incViewCount( $id ) {
2991 $id = intval( $id );
2992 global $wgHitcounterUpdateFreq, $wgDBtype;
2994 $dbw = wfGetDB( DB_MASTER
);
2995 $pageTable = $dbw->tableName( 'page' );
2996 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2997 $acchitsTable = $dbw->tableName( 'acchits' );
2999 if( $wgHitcounterUpdateFreq <= 1 ) {
3000 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3004 # Not important enough to warrant an error page in case of failure
3005 $oldignore = $dbw->ignoreErrors( true );
3007 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3009 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3010 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3011 # Most of the time (or on SQL errors), skip row count check
3012 $dbw->ignoreErrors( $oldignore );
3016 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3017 $row = $dbw->fetchObject( $res );
3018 $rown = intval( $row->n
);
3019 if( $rown >= $wgHitcounterUpdateFreq ){
3020 wfProfileIn( 'Article::incViewCount-collect' );
3021 $old_user_abort = ignore_user_abort( true );
3023 if ($wgDBtype == 'mysql')
3024 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3025 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3026 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3027 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3029 $dbw->query("DELETE FROM $hitcounterTable");
3030 if ($wgDBtype == 'mysql') {
3031 $dbw->query('UNLOCK TABLES');
3032 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3033 'WHERE page_id = hc_id');
3036 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3037 "FROM $acchitsTable WHERE page_id = hc_id");
3039 $dbw->query("DROP TABLE $acchitsTable");
3041 ignore_user_abort( $old_user_abort );
3042 wfProfileOut( 'Article::incViewCount-collect' );
3044 $dbw->ignoreErrors( $oldignore );
3048 * The onArticle*() functions are supposed to be a kind of hooks
3049 * which should be called whenever any of the specified actions
3052 * This is a good place to put code to clear caches, for instance.
3054 * This is called on page move and undelete, as well as edit
3056 * @param $title_obj a title object
3059 static function onArticleCreate($title) {
3060 # The talk page isn't in the regular link tables, so we need to update manually:
3061 if ( $title->isTalkPage() ) {
3062 $other = $title->getSubjectPage();
3064 $other = $title->getTalkPage();
3066 $other->invalidateCache();
3067 $other->purgeSquid();
3069 $title->touchLinks();
3070 $title->purgeSquid();
3071 $title->deleteTitleProtection();
3074 static function onArticleDelete( $title ) {
3075 global $wgUseFileCache, $wgMessageCache;
3077 // Update existence markers on article/talk tabs...
3078 if( $title->isTalkPage() ) {
3079 $other = $title->getSubjectPage();
3081 $other = $title->getTalkPage();
3083 $other->invalidateCache();
3084 $other->purgeSquid();
3086 $title->touchLinks();
3087 $title->purgeSquid();
3090 if ( $wgUseFileCache ) {
3091 $cm = new HTMLFileCache( $title );
3092 @unlink
( $cm->fileCacheName() );
3095 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3096 $wgMessageCache->replace( $title->getDBkey(), false );
3098 if( $title->getNamespace() == NS_IMAGE
) {
3099 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3100 $update->doUpdate();
3105 * Purge caches on page update etc
3107 static function onArticleEdit( $title ) {
3108 global $wgDeferredUpdateList, $wgUseFileCache;
3110 // Invalidate caches of articles which include this page
3111 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3113 // Invalidate the caches of all pages which redirect here
3114 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3116 # Purge squid for this page only
3117 $title->purgeSquid();
3120 if ( $wgUseFileCache ) {
3121 $cm = new HTMLFileCache( $title );
3122 @unlink
( $cm->fileCacheName() );
3129 * Overriden by ImagePage class, only present here to avoid a fatal error
3130 * Called for ?action=revert
3132 public function revert(){
3134 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3138 * Info about this page
3139 * Called for ?action=info when $wgAllowPageInfo is on.
3144 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3146 if ( !$wgAllowPageInfo ) {
3147 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3151 $page = $this->mTitle
->getSubjectPage();
3153 $wgOut->setPagetitle( $page->getPrefixedText() );
3154 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3155 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3157 if( !$this->mTitle
->exists() ) {
3158 $wgOut->addHtml( '<div class="noarticletext">' );
3159 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3160 // This doesn't quite make sense; the user is asking for
3161 // information about the _page_, not the message... -- RC
3162 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3164 $msg = $wgUser->isLoggedIn()
3166 : 'noarticletextanon';
3167 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3169 $wgOut->addHtml( '</div>' );
3171 $dbr = wfGetDB( DB_SLAVE
);
3173 'wl_title' => $page->getDBkey(),
3174 'wl_namespace' => $page->getNamespace() );
3175 $numwatchers = $dbr->selectField(
3180 $this->getSelectOptions() );
3182 $pageInfo = $this->pageCountInfo( $page );
3183 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3185 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3186 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3188 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3190 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3192 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3194 $wgOut->addHTML( '</ul>' );
3200 * Return the total number of edits and number of unique editors
3201 * on a given page. If page does not exist, returns false.
3203 * @param Title $title
3207 function pageCountInfo( $title ) {
3208 $id = $title->getArticleId();
3213 $dbr = wfGetDB( DB_SLAVE
);
3215 $rev_clause = array( 'rev_page' => $id );
3217 $edits = $dbr->selectField(
3222 $this->getSelectOptions() );
3224 $authors = $dbr->selectField(
3226 'COUNT(DISTINCT rev_user_text)',
3229 $this->getSelectOptions() );
3231 return array( 'edits' => $edits, 'authors' => $authors );
3235 * Return a list of templates used by this article.
3236 * Uses the templatelinks table
3238 * @return array Array of Title objects
3240 function getUsedTemplates() {
3242 $id = $this->mTitle
->getArticleID();
3247 $dbr = wfGetDB( DB_SLAVE
);
3248 $res = $dbr->select( array( 'templatelinks' ),
3249 array( 'tl_namespace', 'tl_title' ),
3250 array( 'tl_from' => $id ),
3251 'Article:getUsedTemplates' );
3252 if ( false !== $res ) {
3253 if ( $dbr->numRows( $res ) ) {
3254 while ( $row = $dbr->fetchObject( $res ) ) {
3255 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3259 $dbr->freeResult( $res );
3264 * Returns a list of hidden categories this page is a member of.
3265 * Uses the page_props and categorylinks tables.
3267 * @return array Array of Title objects
3269 function getHiddenCategories() {
3271 $id = $this->mTitle
->getArticleID();
3276 $dbr = wfGetDB( DB_SLAVE
);
3277 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3279 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3280 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3281 'Article:getHiddenCategories' );
3282 if ( false !== $res ) {
3283 if ( $dbr->numRows( $res ) ) {
3284 while ( $row = $dbr->fetchObject( $res ) ) {
3285 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3289 $dbr->freeResult( $res );
3294 * Return an auto-generated summary if the text provided is a redirect.
3296 * @param string $text The wikitext to check
3297 * @return string '' or an appropriate summary
3299 public static function getRedirectAutosummary( $text ) {
3300 $rt = Title
::newFromRedirect( $text );
3301 if( is_object( $rt ) )
3302 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3308 * Return an auto-generated summary if the new text is much shorter than
3311 * @param string $oldtext The previous text of the page
3312 * @param string $text The submitted text of the page
3313 * @return string An appropriate autosummary, or an empty string.
3315 public static function getBlankingAutosummary( $oldtext, $text ) {
3316 if ($oldtext!='' && $text=='') {
3317 return wfMsgForContent('autosumm-blank');
3318 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3319 #Removing more than 90% of the article
3321 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3322 return wfMsgForContent('autosumm-replace', $truncatedtext);
3329 * Return an applicable autosummary if one exists for the given edit.
3330 * @param string $oldtext The previous text of the page.
3331 * @param string $newtext The submitted text of the page.
3332 * @param bitmask $flags A bitmask of flags submitted for the edit.
3333 * @return string An appropriate autosummary, or an empty string.
3335 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3336 global $wgUseAutomaticEditSummaries;
3337 if ( !$wgUseAutomaticEditSummaries ) return '';
3339 # This code is UGLY UGLY UGLY.
3340 # Somebody PLEASE come up with a more elegant way to do it.
3342 #Redirect autosummaries
3343 $summary = self
::getRedirectAutosummary( $newtext );
3348 #Blanking autosummaries
3349 if (!($flags & EDIT_NEW
))
3350 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3355 #New page autosummaries
3356 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3357 #If they're making a new article, give its text, truncated, in the summary.
3359 $truncatedtext = $wgContLang->truncate(
3360 str_replace("\n", ' ', $newtext),
3361 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3363 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3373 * Add the primary page-view wikitext to the output buffer
3374 * Saves the text into the parser cache if possible.
3375 * Updates templatelinks if it is out of date.
3377 * @param string $text
3378 * @param bool $cache
3380 public function outputWikiText( $text, $cache = true ) {
3381 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3383 $popts = $wgOut->parserOptions();
3384 $popts->setTidy(true);
3385 $popts->enableLimitReport();
3386 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3387 $popts, true, true, $this->getRevIdFetched() );
3388 $popts->setTidy(false);
3389 $popts->enableLimitReport( false );
3390 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3391 $parserCache = ParserCache
::singleton();
3392 $parserCache->save( $parserOutput, $this, $wgUser );
3395 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3396 // templatelinks table may have become out of sync,
3397 // especially if using variable-based transclusions.
3398 // For paranoia, check if things have changed and if
3399 // so apply updates to the database. This will ensure
3400 // that cascaded protections apply as soon as the changes
3403 # Get templates from templatelinks
3404 $id = $this->mTitle
->getArticleID();
3406 $tlTemplates = array();
3408 $dbr = wfGetDB( DB_SLAVE
);
3409 $res = $dbr->select( array( 'templatelinks' ),
3410 array( 'tl_namespace', 'tl_title' ),
3411 array( 'tl_from' => $id ),
3412 'Article:getUsedTemplates' );
3416 if ( false !== $res ) {
3417 if ( $dbr->numRows( $res ) ) {
3418 while ( $row = $dbr->fetchObject( $res ) ) {
3419 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3424 # Get templates from parser output.
3425 $poTemplates_allns = $parserOutput->getTemplates();
3427 $poTemplates = array ();
3428 foreach ( $poTemplates_allns as $ns_templates ) {
3429 $poTemplates = array_merge( $poTemplates, $ns_templates );
3433 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3435 if ( count( $templates_diff ) > 0 ) {
3436 # Whee, link updates time.
3437 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3439 $dbw = wfGetDb( DB_MASTER
);
3448 $wgOut->addParserOutput( $parserOutput );
3452 * Update all the appropriate counts in the category table, given that
3453 * we've added the categories $added and deleted the categories $deleted.
3455 * @param $added array The names of categories that were added
3456 * @param $deleted array The names of categories that were deleted
3459 public function updateCategoryCounts( $added, $deleted ) {
3460 $ns = $this->mTitle
->getNamespace();
3461 $dbw = wfGetDB( DB_MASTER
);
3463 # First make sure the rows exist. If one of the "deleted" ones didn't
3464 # exist, we might legitimately not create it, but it's simpler to just
3465 # create it and then give it a negative value, since the value is bogus
3468 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3469 $insertCats = array_merge( $added, $deleted );
3470 if( !$insertCats ) {
3471 # Okay, nothing to do
3474 $insertRows = array();
3475 foreach( $insertCats as $cat ) {
3476 $insertRows[] = array( 'cat_title' => $cat );
3478 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3480 $addFields = array( 'cat_pages = cat_pages + 1' );
3481 $removeFields = array( 'cat_pages = cat_pages - 1' );
3482 if( $ns == NS_CATEGORY
) {
3483 $addFields[] = 'cat_subcats = cat_subcats + 1';
3484 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3485 } elseif( $ns == NS_IMAGE
) {
3486 $addFields[] = 'cat_files = cat_files + 1';
3487 $removeFields[] = 'cat_files = cat_files - 1';
3494 array( 'cat_title' => $added ),
3502 array( 'cat_title' => $deleted ),