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; //!<
41 * Constructor and clear the article
42 * @param $title Reference to a Title object.
43 * @param $oldId Integer revision ID, null to fetch from request, zero for current
45 function __construct( Title
$title, $oldId = null ) {
46 $this->mTitle
=& $title;
47 $this->mOldId
= $oldId;
52 * Tell the page view functions that this view was redirected
53 * from another page on the wiki.
54 * @param $from Title object.
56 function setRedirectedFrom( $from ) {
57 $this->mRedirectedFrom
= $from;
61 * If this page is a redirect, get its target
63 * The target will be fetched from the redirect table if possible.
64 * If this page doesn't have an entry there, call insertRedirect()
65 * @return mixed Title object, or null if this page is not a redirect
67 public function getRedirectTarget() {
68 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
70 if(!is_null($this->mRedirectTarget
))
71 return $this->mRedirectTarget
;
73 # Query the redirect table
74 $dbr = wfGetDB(DB_SLAVE
);
75 $res = $dbr->select('redirect',
76 array('rd_namespace', 'rd_title'),
77 array('rd_from' => $this->getID()),
80 $row = $dbr->fetchObject($res);
82 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
84 # This page doesn't have an entry in the redirect table
85 return $this->mRedirectTarget
= $this->insertRedirect();
89 * Insert an entry for this page into the redirect table.
91 * Don't call this function directly unless you know what you're doing.
92 * @return Title object
94 public function insertRedirect() {
95 $retval = Title
::newFromRedirect($this->getContent());
98 $dbw = wfGetDB(DB_MASTER
);
99 $dbw->insert('redirect', array(
100 'rd_from' => $this->getID(),
101 'rd_namespace' => $retval->getNamespace(),
102 'rd_title' => $retval->getDBKey()
108 * Get the Title object this page redirects to
110 * @param bool $getFragment should the fragment be set on the title
111 * @return mixed false, Title of in-wiki target, or string with URL
113 function followRedirect( $getFragment = false ) {
115 // We'll need to use the content of this page, as Article::getRedirectTarget()
116 // now loads the data from redirect table, wich doesn't store the fragment
117 $rt = Title
::newFromRedirect( $this->getContent() );
119 $rt = $this->getRedirectTarget();
121 # process if title object is valid and not special:userlogout
123 if( $rt->getInterwiki() != '' ) {
124 if( $rt->isLocal() ) {
125 // Offsite wikis need an HTTP redirect.
127 // This can be hard to reverse and may produce loops,
128 // so they may be disabled in the site configuration.
130 $source = $this->mTitle
->getFullURL( 'redirect=no' );
131 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
134 if( $rt->getNamespace() == NS_SPECIAL
) {
135 // Gotta handle redirects to special pages differently:
136 // Fill the HTTP response "Location" header and ignore
137 // the rest of the page we're on.
139 // This can be hard to reverse, so they may be disabled.
141 if( $rt->isSpecial( 'Userlogout' ) ) {
144 return $rt->getFullURL();
151 // No or invalid redirect
156 * get the title object of the article
158 function getTitle() {
159 return $this->mTitle
;
167 $this->mDataLoaded
= false;
168 $this->mContentLoaded
= false;
170 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
171 $this->mRedirectedFrom
= null; # Title object if set
172 $this->mRedirectTarget
= null; # Title object if set
174 $this->mTimestamp
= $this->mComment
= '';
175 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
176 $this->mTouched
= '19700101000000';
177 $this->mForUpdate
= false;
178 $this->mIsRedirect
= false;
179 $this->mRevIdFetched
= 0;
180 $this->mRedirectUrl
= false;
181 $this->mLatest
= false;
182 $this->mPreparedEdit
= false;
186 * Note that getContent/loadContent do not follow redirects anymore.
187 * If you need to fetch redirectable content easily, try
188 * the shortcut in Article::followContent()
190 * @todo There are still side-effects in this!
191 * In general, you should use the Revision class, not Article,
192 * to fetch text for purposes other than page views.
194 * @return Return the text of this revision
196 function getContent() {
197 global $wgUser, $wgOut, $wgMessageCache;
199 wfProfileIn( __METHOD__
);
201 if ( 0 == $this->getID() ) {
202 wfProfileOut( __METHOD__
);
203 $wgOut->setRobotpolicy( 'noindex,nofollow' );
205 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
206 $wgMessageCache->loadAllMessages();
207 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
209 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
212 return "<div class='noarticletext'>\n$ret\n</div>";
214 $this->loadContent();
215 wfProfileOut( __METHOD__
);
216 return $this->mContent
;
221 * This function returns the text of a section, specified by a number ($section).
222 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
223 * the first section before any such heading (section 0).
225 * If a section contains subsections, these are also returned.
227 * @param $text String: text to look in
228 * @param $section Integer: section number
229 * @return string text of the requested section
232 function getSection($text,$section) {
234 return $wgParser->getSection( $text, $section );
238 * @return int The oldid of the article that is to be shown, 0 for the
241 function getOldID() {
242 if ( is_null( $this->mOldId
) ) {
243 $this->mOldId
= $this->getOldIDFromRequest();
245 return $this->mOldId
;
249 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
251 * @return int The old id for the request
253 function getOldIDFromRequest() {
255 $this->mRedirectUrl
= false;
256 $oldid = $wgRequest->getVal( 'oldid' );
257 if ( isset( $oldid ) ) {
258 $oldid = intval( $oldid );
259 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
260 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
264 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
266 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
267 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
285 * Load the revision (including text) into this object
287 function loadContent() {
288 if ( $this->mContentLoaded
) return;
291 $oldid = $this->getOldID();
293 # Pre-fill content with error message so that if something
294 # fails we'll have something telling us what we intended.
295 $this->mOldId
= $oldid;
296 $this->fetchContent( $oldid );
301 * Fetch a page record with the given conditions
302 * @param Database $dbr
303 * @param array $conditions
306 function pageData( $dbr, $conditions ) {
320 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
321 $row = $dbr->selectRow(
327 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
332 * @param Database $dbr
333 * @param Title $title
335 function pageDataFromTitle( $dbr, $title ) {
336 return $this->pageData( $dbr, array(
337 'page_namespace' => $title->getNamespace(),
338 'page_title' => $title->getDBkey() ) );
342 * @param Database $dbr
345 function pageDataFromId( $dbr, $id ) {
346 return $this->pageData( $dbr, array( 'page_id' => $id ) );
350 * Set the general counter, title etc data loaded from
353 * @param object $data
356 function loadPageData( $data = 'fromdb' ) {
357 if ( $data === 'fromdb' ) {
358 $dbr = $this->getDB();
359 $data = $this->pageDataFromId( $dbr, $this->getId() );
362 $lc = LinkCache
::singleton();
364 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
366 $this->mTitle
->mArticleID
= $data->page_id
;
368 # Old-fashioned restrictions.
369 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
371 $this->mCounter
= $data->page_counter
;
372 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
373 $this->mIsRedirect
= $data->page_is_redirect
;
374 $this->mLatest
= $data->page_latest
;
376 if ( is_object( $this->mTitle
) ) {
377 $lc->addBadLinkObj( $this->mTitle
);
379 $this->mTitle
->mArticleID
= 0;
382 $this->mDataLoaded
= true;
386 * Get text of an article from database
387 * Does *NOT* follow redirects.
388 * @param int $oldid 0 for whatever the latest revision is
391 function fetchContent( $oldid = 0 ) {
392 if ( $this->mContentLoaded
) {
393 return $this->mContent
;
396 $dbr = $this->getDB();
398 # Pre-fill content with error message so that if something
399 # fails we'll have something telling us what we intended.
400 $t = $this->mTitle
->getPrefixedText();
402 $t .= ',oldid='.$oldid;
404 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
407 $revision = Revision
::newFromId( $oldid );
408 if( is_null( $revision ) ) {
409 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
412 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
414 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
417 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
418 $this->loadPageData( $data );
420 if( !$this->mDataLoaded
) {
421 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
423 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
426 $this->loadPageData( $data );
428 $revision = Revision
::newFromId( $this->mLatest
);
429 if( is_null( $revision ) ) {
430 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
435 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
436 // We should instead work with the Revision object when we need it...
437 $this->mContent
= $revision->revText(); // Loads if user is allowed
439 $this->mUser
= $revision->getUser();
440 $this->mUserText
= $revision->getUserText();
441 $this->mComment
= $revision->getComment();
442 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
444 $this->mRevIdFetched
= $revision->getID();
445 $this->mContentLoaded
= true;
446 $this->mRevision
=& $revision;
448 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
450 return $this->mContent
;
454 * Read/write accessor to select FOR UPDATE
456 * @param $x Mixed: FIXME
458 function forUpdate( $x = NULL ) {
459 return wfSetVar( $this->mForUpdate
, $x );
463 * Get the database which should be used for reads
468 return wfGetDB( DB_MASTER
);
472 * Get options for all SELECT statements
474 * @param $options Array: an optional options array which'll be appended to
476 * @return Array: options
478 function getSelectOptions( $options = '' ) {
479 if ( $this->mForUpdate
) {
480 if ( is_array( $options ) ) {
481 $options[] = 'FOR UPDATE';
483 $options = 'FOR UPDATE';
490 * @return int Page ID
493 if( $this->mTitle
) {
494 return $this->mTitle
->getArticleID();
501 * @return bool Whether or not the page exists in the database
504 return $this->getId() != 0;
508 * @return int The view count for the page
510 function getCount() {
511 if ( -1 == $this->mCounter
) {
512 $id = $this->getID();
516 $dbr = wfGetDB( DB_SLAVE
);
517 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
518 'Article::getCount', $this->getSelectOptions() );
521 return $this->mCounter
;
525 * Determine whether a page would be suitable for being counted as an
526 * article in the site_stats table based on the title & its content
528 * @param $text String: text to analyze
531 function isCountable( $text ) {
532 global $wgUseCommaCount;
534 $token = $wgUseCommaCount ?
',' : '[[';
536 $this->mTitle
->isContentPage()
537 && !$this->isRedirect( $text )
538 && in_string( $token, $text );
542 * Tests if the article text represents a redirect
544 * @param $text String: FIXME
547 function isRedirect( $text = false ) {
548 if ( $text === false ) {
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 .= ',oldid='.$oldid;
806 $text = wfMsg( 'missingarticle', $t );
808 $text = wfMsg( 'noarticletext', $t );
812 # Another whitelist check in case oldid is altering the title
813 if ( !$this->mTitle
->userCanRead() ) {
814 $wgOut->loginToUse();
819 # We're looking at an old revision
821 if ( !empty( $oldid ) ) {
822 $wgOut->setRobotpolicy( 'noindex,nofollow' );
823 if( is_null( $this->mRevision
) ) {
824 // FIXME: This would be a nice place to load the 'no such page' text.
826 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
827 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
828 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
829 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
830 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
833 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
834 // and we are allowed to see...
842 $wgOut->setRevisionId( $this->getRevIdFetched() );
844 // Pages containing custom CSS or JavaScript get special treatment
845 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
846 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
848 // Give hooks a chance to customise the output
849 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
850 // Wrap the whole lot in a <pre> and don't parse
852 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
853 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
854 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
855 $wgOut->addHtml( "\n</pre>\n" );
860 elseif ( $rt = $this->getRedirectTarget() ) {
862 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
863 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
864 # Don't overwrite the subtitle if this was an old revision
865 if( !$wasRedirected && $this->isCurrent() ) {
866 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
868 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
870 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
871 '<span class="redirectText">'.$link.'</span>' );
873 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
874 $wgOut->addParserOutputNoText( $parseout );
875 } else if ( $pcache ) {
876 # Display content and save to parser cache
877 $this->outputWikiText( $text );
879 # Display content, don't attempt to save to parser cache
880 # Don't show section-edit links on old revisions... this way lies madness.
881 if( !$this->isCurrent() ) {
882 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
884 # Display content and don't save to parser cache
885 # With timing hack -- TS 2006-07-26
887 $this->outputWikiText( $text, false );
892 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
893 $this->mTitle
->getPrefixedDBkey()));
896 if( !$this->isCurrent() ) {
897 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
902 /* title may have been set from the cache */
903 $t = $wgOut->getPageTitle();
905 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
908 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
909 if( $ns == NS_USER_TALK
&&
910 IP
::isValid( $this->mTitle
->getText() ) ) {
911 $wgOut->addWikiMsg('anontalkpagetext');
914 # If we have been passed an &rcid= parameter, we want to give the user a
915 # chance to mark this new article as patrolled.
916 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
918 "<div class='patrollink'>" .
919 wfMsgHtml( 'markaspatrolledlink',
920 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
921 "action=markpatrolled&rcid=$rcid" )
928 if ($wgUseTrackbacks)
929 $this->addTrackbacks();
931 $this->viewUpdates();
932 wfProfileOut( __METHOD__
);
935 function addTrackbacks() {
936 global $wgOut, $wgUser;
938 $dbr = wfGetDB(DB_SLAVE
);
940 /* FROM */ 'trackbacks',
941 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
942 /* WHERE */ array('tb_page' => $this->getID())
945 if (!$dbr->numrows($tbs))
949 while ($o = $dbr->fetchObject($tbs)) {
951 if ($wgUser->isAllowed( 'trackback' )) {
952 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
953 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
954 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
957 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
964 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
967 function deletetrackback() {
968 global $wgUser, $wgRequest, $wgOut, $wgTitle;
970 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
971 $wgOut->addWikiMsg( 'sessionfailure' );
975 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
977 if (count($permission_errors)>0)
979 $wgOut->showPermissionsErrorPage( $permission_errors );
983 $db = wfGetDB(DB_MASTER
);
984 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
985 $wgTitle->invalidateCache();
986 $wgOut->addWikiMsg('trackbackdeleteok');
992 $wgOut->setArticleBodyOnly(true);
997 * Handle action=purge
1000 global $wgUser, $wgRequest, $wgOut;
1002 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1003 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1007 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1008 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1009 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1010 $msg = str_replace( '$1',
1011 "<form method=\"post\" action=\"$action\">\n" .
1012 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1013 "</form>\n", $msg );
1015 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1016 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1017 $wgOut->addHTML( $msg );
1022 * Perform the actions of a page purging
1024 function doPurge() {
1026 // Invalidate the cache
1027 $this->mTitle
->invalidateCache();
1029 if ( $wgUseSquid ) {
1030 // Commit the transaction before the purge is sent
1031 $dbw = wfGetDB( DB_MASTER
);
1032 $dbw->immediateCommit();
1035 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1036 $update->doUpdate();
1038 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1039 global $wgMessageCache;
1040 if ( $this->getID() == 0 ) {
1043 $text = $this->getContent();
1045 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1051 * Insert a new empty page record for this article.
1052 * This *must* be followed up by creating a revision
1053 * and running $this->updateToLatest( $rev_id );
1054 * or else the record will be left in a funky state.
1055 * Best if all done inside a transaction.
1057 * @param Database $dbw
1058 * @return int The newly created page_id key
1061 function insertOn( $dbw ) {
1062 wfProfileIn( __METHOD__
);
1064 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1065 $dbw->insert( 'page', array(
1066 'page_id' => $page_id,
1067 'page_namespace' => $this->mTitle
->getNamespace(),
1068 'page_title' => $this->mTitle
->getDBkey(),
1069 'page_counter' => 0,
1070 'page_restrictions' => '',
1071 'page_is_redirect' => 0, # Will set this shortly...
1073 'page_random' => wfRandom(),
1074 'page_touched' => $dbw->timestamp(),
1075 'page_latest' => 0, # Fill this in shortly...
1076 'page_len' => 0, # Fill this in shortly...
1078 $newid = $dbw->insertId();
1080 $this->mTitle
->resetArticleId( $newid );
1082 wfProfileOut( __METHOD__
);
1087 * Update the page record to point to a newly saved revision.
1089 * @param Database $dbw
1090 * @param Revision $revision For ID number, and text used to set
1091 length and redirect status fields
1092 * @param int $lastRevision If given, will not overwrite the page field
1093 * when different from the currently set value.
1094 * Giving 0 indicates the new page flag should
1096 * @param bool $lastRevIsRedirect If given, will optimize adding and
1097 * removing rows in redirect table.
1098 * @return bool true on success, false on failure
1101 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1102 wfProfileIn( __METHOD__
);
1104 $text = $revision->getText();
1105 $rt = Title
::newFromRedirect( $text );
1107 $conditions = array( 'page_id' => $this->getId() );
1108 if( !is_null( $lastRevision ) ) {
1109 # An extra check against threads stepping on each other
1110 $conditions['page_latest'] = $lastRevision;
1113 $dbw->update( 'page',
1115 'page_latest' => $revision->getId(),
1116 'page_touched' => $dbw->timestamp(),
1117 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1118 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1119 'page_len' => strlen( $text ),
1124 $result = $dbw->affectedRows() != 0;
1127 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1130 wfProfileOut( __METHOD__
);
1135 * Add row to the redirect table if this is a redirect, remove otherwise.
1137 * @param Database $dbw
1138 * @param $redirectTitle a title object pointing to the redirect target,
1139 * or NULL if this is not a redirect
1140 * @param bool $lastRevIsRedirect If given, will optimize adding and
1141 * removing rows in redirect table.
1142 * @return bool true on success, false on failure
1145 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1147 // Always update redirects (target link might have changed)
1148 // Update/Insert if we don't know if the last revision was a redirect or not
1149 // Delete if changing from redirect to non-redirect
1150 $isRedirect = !is_null($redirectTitle);
1151 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1153 wfProfileIn( __METHOD__
);
1157 // This title is a redirect, Add/Update row in the redirect table
1158 $set = array( /* SET */
1159 'rd_namespace' => $redirectTitle->getNamespace(),
1160 'rd_title' => $redirectTitle->getDBkey(),
1161 'rd_from' => $this->getId(),
1164 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1166 // This is not a redirect, remove row from redirect table
1167 $where = array( 'rd_from' => $this->getId() );
1168 $dbw->delete( 'redirect', $where, __METHOD__
);
1171 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1172 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1173 wfProfileOut( __METHOD__
);
1174 return ( $dbw->affectedRows() != 0 );
1181 * If the given revision is newer than the currently set page_latest,
1182 * update the page record. Otherwise, do nothing.
1184 * @param Database $dbw
1185 * @param Revision $revision
1187 function updateIfNewerOn( &$dbw, $revision ) {
1188 wfProfileIn( __METHOD__
);
1190 $row = $dbw->selectRow(
1191 array( 'revision', 'page' ),
1192 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1194 'page_id' => $this->getId(),
1195 'page_latest=rev_id' ),
1198 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1199 wfProfileOut( __METHOD__
);
1202 $prev = $row->rev_id
;
1203 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1205 # No or missing previous revision; mark the page as new
1207 $lastRevIsRedirect = null;
1210 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1211 wfProfileOut( __METHOD__
);
1216 * @return string Complete article text, or null if error
1218 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1219 wfProfileIn( __METHOD__
);
1221 if( $section == '' ) {
1222 // Whole-page edit; let the text through unmolested.
1224 if( is_null( $edittime ) ) {
1225 $rev = Revision
::newFromTitle( $this->mTitle
);
1227 $dbw = wfGetDB( DB_MASTER
);
1228 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1230 if( is_null( $rev ) ) {
1231 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1232 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1235 $oldtext = $rev->getText();
1237 if( $section == 'new' ) {
1238 # Inserting a new section
1239 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1240 $text = strlen( trim( $oldtext ) ) > 0
1241 ?
"{$oldtext}\n\n{$subject}{$text}"
1242 : "{$subject}{$text}";
1244 # Replacing an existing section; roll out the big guns
1246 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1251 wfProfileOut( __METHOD__
);
1256 * @deprecated use Article::doEdit()
1258 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1259 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1260 ( $isminor ? EDIT_MINOR
: 0 ) |
1261 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1262 ( $bot ? EDIT_FORCE_BOT
: 0 );
1264 # If this is a comment, add the summary as headline
1265 if ( $comment && $summary != "" ) {
1266 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1269 $this->doEdit( $text, $summary, $flags );
1271 $dbw = wfGetDB( DB_MASTER
);
1273 if (!$this->mTitle
->userIsWatching()) {
1279 if ( $this->mTitle
->userIsWatching() ) {
1285 $this->doRedirect( $this->isRedirect( $text ) );
1289 * @deprecated use Article::doEdit()
1291 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1292 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1293 ( $minor ? EDIT_MINOR
: 0 ) |
1294 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1296 $good = $this->doEdit( $text, $summary, $flags );
1298 $dbw = wfGetDB( DB_MASTER
);
1300 if (!$this->mTitle
->userIsWatching()) {
1306 if ( $this->mTitle
->userIsWatching() ) {
1313 $extraq = ''; // Give extensions a chance to modify URL query on update
1314 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1316 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1324 * Change an existing article or create a new article. Updates RC and all necessary caches,
1325 * optionally via the deferred update array.
1327 * $wgUser must be set before calling this function.
1329 * @param string $text New text
1330 * @param string $summary Edit summary
1331 * @param integer $flags bitfield:
1333 * Article is known or assumed to be non-existent, create a new one
1335 * Article is known or assumed to be pre-existing, update it
1337 * Mark this edit minor, if the user is allowed to do so
1339 * Do not log the change in recentchanges
1341 * Mark the edit a "bot" edit regardless of user rights
1342 * EDIT_DEFER_UPDATES
1343 * Defer some of the updates until the end of index.php
1345 * Fill in blank summaries with generated text where possible
1347 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1348 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1349 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1350 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1351 * to MediaWiki's performance-optimised locking strategy.
1353 * @return bool success
1355 function doEdit( $text, $summary, $flags = 0 ) {
1356 global $wgUser, $wgDBtransactions;
1358 wfProfileIn( __METHOD__
);
1361 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1362 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1364 $flags |
= EDIT_UPDATE
;
1370 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1371 &$summary, $flags & EDIT_MINOR
,
1372 null, null, &$flags ) ) )
1374 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1375 wfProfileOut( __METHOD__
);
1379 # Silently ignore EDIT_MINOR if not allowed
1380 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1381 $bot = $flags & EDIT_FORCE_BOT
;
1383 $oldtext = $this->getContent();
1384 $oldsize = strlen( $oldtext );
1386 # Provide autosummaries if one is not provided.
1387 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1388 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1390 $editInfo = $this->prepareTextForEdit( $text );
1391 $text = $editInfo->pst
;
1392 $newsize = strlen( $text );
1394 $dbw = wfGetDB( DB_MASTER
);
1395 $now = wfTimestampNow();
1397 if ( $flags & EDIT_UPDATE
) {
1398 # Update article, but only if changed.
1400 # Make sure the revision is either completely inserted or not inserted at all
1401 if( !$wgDBtransactions ) {
1402 $userAbort = ignore_user_abort( true );
1408 $changed = ( strcmp( $text, $oldtext ) != 0 );
1411 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1412 - (int)$this->isCountable( $oldtext );
1413 $this->mTotalAdjustment
= 0;
1415 $lastRevision = $dbw->selectField(
1416 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1418 if ( !$lastRevision ) {
1419 # Article gone missing
1420 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1421 wfProfileOut( __METHOD__
);
1425 $revision = new Revision( array(
1426 'page' => $this->getId(),
1427 'comment' => $summary,
1428 'minor_edit' => $isminor,
1430 'parent_id' => $lastRevision
1434 $revisionId = $revision->insertOn( $dbw );
1437 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1440 /* Belated edit conflict! Run away!! */
1444 # Update recentchanges
1445 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1446 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1447 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1450 # Mark as patrolled if the user can do so
1451 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1452 RecentChange
::markPatrolled( $rcid );
1453 PatrolLog
::record( $rcid, true );
1456 $wgUser->incEditCount();
1461 // Keep the same revision ID, but do some updates on it
1462 $revisionId = $this->getRevIdFetched();
1463 // Update page_touched, this is usually implicit in the page update
1464 // Other cache updates are done in onArticleEdit()
1465 $this->mTitle
->invalidateCache();
1468 if( !$wgDBtransactions ) {
1469 ignore_user_abort( $userAbort );
1473 # Invalidate cache of this article and all pages using this article
1474 # as a template. Partly deferred.
1475 Article
::onArticleEdit( $this->mTitle
);
1477 # Update links tables, site stats, etc.
1478 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1481 # Create new article
1483 # Set statistics members
1484 # We work out if it's countable after PST to avoid counter drift
1485 # when articles are created with {{subst:}}
1486 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1487 $this->mTotalAdjustment
= 1;
1491 # Add the page record; stake our claim on this title!
1492 # This will fail with a database query exception if the article already exists
1493 $newid = $this->insertOn( $dbw );
1495 # Save the revision text...
1496 $revision = new Revision( array(
1498 'comment' => $summary,
1499 'minor_edit' => $isminor,
1502 $revisionId = $revision->insertOn( $dbw );
1504 $this->mTitle
->resetArticleID( $newid );
1506 # Update the page record with revision data
1507 $this->updateRevisionOn( $dbw, $revision, 0 );
1509 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1510 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1511 '', strlen( $text ), $revisionId );
1512 # Mark as patrolled if the user can
1513 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1514 RecentChange
::markPatrolled( $rcid );
1515 PatrolLog
::record( $rcid, true );
1518 $wgUser->incEditCount();
1521 # Update links, etc.
1522 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1525 Article
::onArticleCreate( $this->mTitle
);
1527 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1528 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1531 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1536 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1537 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1540 wfProfileOut( __METHOD__
);
1545 * @deprecated wrapper for doRedirect
1547 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1548 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1552 * Output a redirect back to the article.
1553 * This is typically used after an edit.
1555 * @param boolean $noRedir Add redirect=no
1556 * @param string $sectionAnchor section to redirect to, including "#"
1557 * @param string $extraq, extra query params
1559 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1562 $query = 'redirect=no';
1564 $query .= "&$query";
1568 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1572 * Mark this particular edit/page as patrolled
1574 function markpatrolled() {
1575 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1576 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1578 # Check patrol config options
1580 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1581 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1585 # If we haven't been given an rc_id value, we can't do anything
1586 $rcid = (int) $wgRequest->getVal('rcid');
1587 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1588 if ( is_null ( $rc ) )
1590 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1594 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1595 // Only new pages can be patrolled if the general patrolling is off....???
1596 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1598 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1603 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1605 if (count($permission_errors)>0)
1607 $wgOut->showPermissionsErrorPage( $permission_errors );
1611 # Handle the 'MarkPatrolled' hook
1612 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1616 #It would be nice to see where the user had actually come from, but for now just guess
1617 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1618 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1620 # If it's left up to us, check that the user is allowed to patrol this edit
1621 # If the user has the "autopatrol" right, then we'll assume there are no
1622 # other conditions stopping them doing so
1623 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1624 $rc = RecentChange
::newFromId( $rcid );
1625 # Graceful error handling, as we've done before here...
1626 # (If the recent change doesn't exist, then it doesn't matter whether
1627 # the user is allowed to patrol it or not; nothing is going to happen
1628 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1629 # The user made this edit, and can't patrol it
1630 # Tell them so, and then back off
1631 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1632 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1633 $wgOut->returnToMain( false, $return );
1638 # Check that the revision isn't patrolled already
1639 # Prevents duplicate log entries
1640 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1641 # Mark the edit as patrolled
1642 RecentChange
::markPatrolled( $rcid );
1643 PatrolLog
::record( $rcid );
1644 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1648 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1649 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1650 $wgOut->returnToMain( false, $return );
1654 * User-interface handler for the "watch" action
1659 global $wgUser, $wgOut;
1661 if ( $wgUser->isAnon() ) {
1662 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1665 if ( wfReadOnly() ) {
1666 $wgOut->readOnlyPage();
1670 if( $this->doWatch() ) {
1671 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1672 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1674 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1677 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1681 * Add this page to $wgUser's watchlist
1682 * @return bool true on successful watch operation
1684 function doWatch() {
1686 if( $wgUser->isAnon() ) {
1690 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1691 $wgUser->addWatch( $this->mTitle
);
1693 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1700 * User interface handler for the "unwatch" action.
1702 function unwatch() {
1704 global $wgUser, $wgOut;
1706 if ( $wgUser->isAnon() ) {
1707 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1710 if ( wfReadOnly() ) {
1711 $wgOut->readOnlyPage();
1715 if( $this->doUnwatch() ) {
1716 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1717 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1719 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1722 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1726 * Stop watching a page
1727 * @return bool true on successful unwatch
1729 function doUnwatch() {
1731 if( $wgUser->isAnon() ) {
1735 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1736 $wgUser->removeWatch( $this->mTitle
);
1738 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1745 * action=protect handler
1747 function protect() {
1748 $form = new ProtectionForm( $this );
1753 * action=unprotect handler (alias)
1755 function unprotect() {
1760 * Update the article's restriction field, and leave a log entry.
1762 * @param array $limit set of restriction keys
1763 * @param string $reason
1764 * @return bool true on success
1766 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1767 global $wgUser, $wgRestrictionTypes, $wgContLang;
1769 $id = $this->mTitle
->getArticleID();
1770 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1778 // Take this opportunity to purge out expired restrictions
1779 Title
::purgeExpiredRestrictions();
1781 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1782 # we expect a single selection, but the schema allows otherwise.
1784 foreach( $wgRestrictionTypes as $action )
1785 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1787 $current = Article
::flattenRestrictions( $current );
1788 $updated = Article
::flattenRestrictions( $limit );
1790 $changed = ( $current != $updated );
1791 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1792 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1793 $protect = ( $updated != '' );
1795 # If nothing's changed, do nothing
1797 global $wgGroupPermissions;
1798 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1800 $dbw = wfGetDB( DB_MASTER
);
1802 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1804 $expiry_description = '';
1805 if ( $encodedExpiry != 'infinity' ) {
1806 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1809 # Prepare a null revision to be added to the history
1810 $modified = $current != '' && $protect;
1812 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1814 $comment_type = 'unprotectedarticle';
1816 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1818 foreach( $limit as $action => $restrictions ) {
1819 # Check if the group level required to edit also can protect pages
1820 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1821 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1822 $wgGroupPermissions[$restrictions]['protect'] );
1825 $cascade_description = '';
1827 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1831 $comment .= ": $reason";
1833 $comment .= " [$updated]";
1834 if ( $expiry_description && $protect )
1835 $comment .= "$expiry_description";
1837 $comment .= "$cascade_description";
1839 # Update restrictions table
1840 foreach( $limit as $action => $restrictions ) {
1841 if ($restrictions != '' ) {
1842 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1843 array( 'pr_page' => $id, 'pr_type' => $action
1844 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1845 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1847 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1848 'pr_type' => $action ), __METHOD__
);
1852 # Insert a null revision
1853 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1854 $nullRevId = $nullRevision->insertOn( $dbw );
1856 # Update page record
1857 $dbw->update( 'page',
1859 'page_touched' => $dbw->timestamp(),
1860 'page_restrictions' => '',
1861 'page_latest' => $nullRevId
1862 ), array( /* WHERE */
1864 ), 'Article::protect'
1866 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1868 # Update the protection log
1869 $log = new LogPage( 'protect' );
1874 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1876 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1880 } # End "changed" check
1886 * Take an array of page restrictions and flatten it to a string
1887 * suitable for insertion into the page_restrictions field.
1888 * @param array $limit
1892 function flattenRestrictions( $limit ) {
1893 if( !is_array( $limit ) ) {
1894 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1898 foreach( $limit as $action => $restrictions ) {
1899 if( $restrictions != '' ) {
1900 $bits[] = "$action=$restrictions";
1903 return implode( ':', $bits );
1907 * Auto-generates a deletion reason
1908 * @param bool &$hasHistory Whether the page has a history
1910 public function generateReason(&$hasHistory)
1913 $dbw = wfGetDB(DB_MASTER
);
1914 // Get the last revision
1915 $rev = Revision
::newFromTitle($this->mTitle
);
1918 // Get the article's contents
1919 $contents = $rev->getText();
1921 // If the page is blank, use the text from the previous revision,
1922 // which can only be blank if there's a move/import/protect dummy revision involved
1925 $prev = $rev->getPrevious();
1928 $contents = $prev->getText();
1933 // Find out if there was only one contributor
1934 // Only scan the last 20 revisions
1936 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1937 array('LIMIT' => $limit));
1939 // This page has no revisions, which is very weird
1941 if($res->numRows() > 1)
1944 $hasHistory = false;
1945 $row = $dbw->fetchObject($res);
1946 $onlyAuthor = $row->rev_user_text
;
1947 // Try to find a second contributor
1948 while( $row = $dbw->fetchObject($res) ) {
1949 if($row->rev_user_text
!= $onlyAuthor) {
1950 $onlyAuthor = false;
1954 $dbw->freeResult($res);
1956 // Generate the summary with a '$1' placeholder
1958 // The current revision is blank and the one before is also
1959 // blank. It's just not our lucky day
1960 $reason = wfMsgForContent('exbeforeblank', '$1');
1963 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1965 $reason = wfMsgForContent('excontent', '$1');
1968 // Replace newlines with spaces to prevent uglyness
1969 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1970 // Calculate the maximum amount of chars to get
1971 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1972 $maxLength = 255 - (strlen($reason) - 2) - 3;
1973 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1974 // Remove possible unfinished links
1975 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1976 // Now replace the '$1' placeholder
1977 $reason = str_replace( '$1', $contents, $reason );
1983 * UI entry point for page deletion
1986 global $wgUser, $wgOut, $wgRequest;
1988 $confirm = $wgRequest->wasPosted() &&
1989 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1991 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1992 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1994 $reason = $this->DeleteReasonList
;
1996 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1997 // Entry from drop down menu + additional comment
1998 $reason .= ': ' . $this->DeleteReason
;
1999 } elseif ( $reason == 'other' ) {
2000 $reason = $this->DeleteReason
;
2002 # Flag to hide all contents of the archived revisions
2003 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
2005 # This code desperately needs to be totally rewritten
2007 # Read-only check...
2008 if ( wfReadOnly() ) {
2009 $wgOut->readOnlyPage();
2014 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2016 if (count($permission_errors)>0) {
2017 $wgOut->showPermissionsErrorPage( $permission_errors );
2021 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2023 # Better double-check that it hasn't been deleted yet!
2024 $dbw = wfGetDB( DB_MASTER
);
2025 $conds = $this->mTitle
->pageCond();
2026 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2027 if ( $latest === false ) {
2028 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2032 # Hack for big sites
2033 $bigHistory = $this->isBigDeletion();
2034 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2035 global $wgLang, $wgDeleteRevisionsLimit;
2036 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2037 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2042 $this->doDelete( $reason, $suppress );
2043 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2045 } elseif( $this->mTitle
->userIsWatching() ) {
2051 // Generate deletion reason
2052 $hasHistory = false;
2053 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2055 // If the page has a history, insert a warning
2056 if( $hasHistory && !$confirm ) {
2057 $skin=$wgUser->getSkin();
2058 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2060 global $wgLang, $wgDeleteRevisionsLimit;
2061 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2062 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2066 return $this->confirmDelete( '', $reason );
2070 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2072 function isBigDeletion() {
2073 global $wgDeleteRevisionsLimit;
2074 if( $wgDeleteRevisionsLimit ) {
2075 $revCount = $this->estimateRevisionCount();
2076 return $revCount > $wgDeleteRevisionsLimit;
2082 * @return int approximate revision count
2084 function estimateRevisionCount() {
2086 // For an exact count...
2087 //return $dbr->selectField( 'revision', 'COUNT(*)',
2088 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2089 return $dbr->estimateRowCount( 'revision', '*',
2090 array( 'rev_page' => $this->getId() ), __METHOD__
);
2094 * Get the last N authors
2095 * @param int $num Number of revisions to get
2096 * @param string $revLatest The latest rev_id, selected from the master (optional)
2097 * @return array Array of authors, duplicates not removed
2099 function getLastNAuthors( $num, $revLatest = 0 ) {
2100 wfProfileIn( __METHOD__
);
2102 // First try the slave
2103 // If that doesn't have the latest revision, try the master
2105 $db = wfGetDB( DB_SLAVE
);
2107 $res = $db->select( array( 'page', 'revision' ),
2108 array( 'rev_id', 'rev_user_text' ),
2110 'page_namespace' => $this->mTitle
->getNamespace(),
2111 'page_title' => $this->mTitle
->getDBkey(),
2112 'rev_page = page_id'
2113 ), __METHOD__
, $this->getSelectOptions( array(
2114 'ORDER BY' => 'rev_timestamp DESC',
2119 wfProfileOut( __METHOD__
);
2122 $row = $db->fetchObject( $res );
2123 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2124 $db = wfGetDB( DB_MASTER
);
2129 } while ( $continue );
2131 $authors = array( $row->rev_user_text
);
2132 while ( $row = $db->fetchObject( $res ) ) {
2133 $authors[] = $row->rev_user_text
;
2135 wfProfileOut( __METHOD__
);
2140 * Output deletion confirmation dialog
2141 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2142 * @param $reason string Prefilled reason
2144 function confirmDelete( $par, $reason ) {
2145 global $wgOut, $wgUser, $wgContLang;
2146 $align = $wgContLang->isRtl() ?
'left' : 'right';
2148 wfDebug( "Article::confirmDelete\n" );
2150 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2151 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2152 $wgOut->addWikiMsg( 'confirmdeletetext' );
2154 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2155 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2156 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2157 $suppress .= "</td></tr>";
2162 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2163 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2164 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2165 Xml
::openElement( 'table' ) .
2166 "<tr id=\"wpDeleteReasonListRow\">
2167 <td align='$align'>" .
2168 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2171 Xml
::listDropDown( 'wpDeleteReasonList',
2172 wfMsgForContent( 'deletereason-dropdown' ),
2173 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2176 <tr id=\"wpDeleteReasonRow\">
2177 <td align='$align'>" .
2178 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2181 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2187 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2194 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2197 Xml
::closeElement( 'table' ) .
2198 Xml
::closeElement( 'fieldset' ) .
2199 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2200 Xml
::closeElement( 'form' );
2202 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2203 $skin = $wgUser->getSkin();
2204 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2205 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2208 $wgOut->addHTML( $form );
2209 $this->showLogExtract( $wgOut );
2214 * Show relevant lines from the deletion log
2216 function showLogExtract( $out ) {
2217 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2218 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2223 * Perform a deletion and output success or failure messages
2225 function doDelete( $reason, $suppress = false ) {
2226 global $wgOut, $wgUser;
2227 wfDebug( __METHOD__
."\n" );
2229 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2230 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2231 $deleted = $this->mTitle
->getPrefixedText();
2233 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2234 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2236 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2238 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2239 $wgOut->returnToMain( false );
2240 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2242 $wgOut->showFatalError( wfMsg( 'cannotdelete' ).'<br/>'.wfMsg('cannotdelete-merge') );
2248 * Back-end article deletion
2249 * Deletes the article with database consistency, writes logs, purges caches
2252 function doDeleteArticle( $reason, $suppress = false ) {
2253 global $wgUseSquid, $wgDeferredUpdateList;
2254 global $wgUseTrackbacks;
2256 wfDebug( __METHOD__
."\n" );
2258 $dbw = wfGetDB( DB_MASTER
);
2259 $ns = $this->mTitle
->getNamespace();
2260 $t = $this->mTitle
->getDBkey();
2261 $id = $this->mTitle
->getArticleID();
2263 if ( $t == '' ||
$id == 0 ) {
2267 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2268 array_push( $wgDeferredUpdateList, $u );
2270 // Bitfields to further suppress the content
2273 // This should be 15...
2274 $bitfield |
= Revision
::DELETED_TEXT
;
2275 $bitfield |
= Revision
::DELETED_COMMENT
;
2276 $bitfield |
= Revision
::DELETED_USER
;
2277 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2279 $bitfield = 'rev_deleted';
2282 // For now, shunt the revision data into the archive table.
2283 // Text is *not* removed from the text table; bulk storage
2284 // is left intact to avoid breaking block-compression or
2285 // immutable storage schemes.
2287 // For backwards compatibility, note that some older archive
2288 // table entries will have ar_text and ar_flags fields still.
2290 // In the future, we may keep revisions and mark them with
2291 // the rev_deleted field, which is reserved for this purpose.
2292 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2294 'ar_namespace' => 'page_namespace',
2295 'ar_title' => 'page_title',
2296 'ar_comment' => 'rev_comment',
2297 'ar_user' => 'rev_user',
2298 'ar_user_text' => 'rev_user_text',
2299 'ar_timestamp' => 'rev_timestamp',
2300 'ar_minor_edit' => 'rev_minor_edit',
2301 'ar_rev_id' => 'rev_id',
2302 'ar_text_id' => 'rev_text_id',
2303 'ar_text' => '\'\'', // Be explicit to appease
2304 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2305 'ar_len' => 'rev_len',
2306 'ar_page_id' => 'page_id',
2307 'ar_deleted' => $bitfield
2310 'page_id = rev_page'
2314 # Delete restrictions for it
2315 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2317 # Fix category table counts
2319 $res = $dbw->select( 'categorylinks', 'cl_to',
2320 array( 'cl_from' => $id ), __METHOD__
);
2321 foreach( $res as $row ) {
2322 $cats []= $row->cl_to
;
2324 $this->updateCategoryCounts( array(), $cats );
2326 # Now that it's safely backed up, delete it
2327 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2329 # If using cascading deletes, we can skip some explicit deletes
2330 if ( !$dbw->cascadingDeletes() ) {
2331 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2333 if ($wgUseTrackbacks)
2334 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2336 # Delete outgoing links
2337 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2338 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2339 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2340 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2341 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2342 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2343 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2346 # If using cleanup triggers, we can skip some manual deletes
2347 if ( !$dbw->cleanupTriggers() ) {
2349 # Clean up recentchanges entries...
2350 $dbw->delete( 'recentchanges',
2351 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2356 Article
::onArticleDelete( $this->mTitle
);
2358 # Clear the cached article id so the interface doesn't act like we exist
2359 $this->mTitle
->resetArticleID( 0 );
2360 $this->mTitle
->mArticleID
= 0;
2362 # Log the deletion, if the page was suppressed, log it at Oversight instead
2363 $logtype = $suppress ?
'suppress' : 'delete';
2364 $log = new LogPage( $logtype );
2365 $log->addEntry( 'delete', $this->mTitle
, $reason );
2371 * Roll back the most recent consecutive set of edits to a page
2372 * from the same user; fails if there are no eligible edits to
2373 * roll back to, e.g. user is the sole contributor. This function
2374 * performs permissions checks on $wgUser, then calls commitRollback()
2375 * to do the dirty work
2377 * @param string $fromP - Name of the user whose edits to rollback.
2378 * @param string $summary - Custom summary. Set to default summary if empty.
2379 * @param string $token - Rollback token.
2380 * @param bool $bot - If true, mark all reverted edits as bot.
2382 * @param array $resultDetails contains result-specific array of additional values
2383 * 'alreadyrolled' : 'current' (rev)
2384 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2386 * @return array of errors, each error formatted as
2387 * array(messagekey, param1, param2, ...).
2388 * On success, the array is empty. This array can also be passed to
2389 * OutputPage::showPermissionsErrorPage().
2391 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2393 $resultDetails = null;
2396 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2397 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2398 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2399 $errors[] = array( 'sessionfailure' );
2401 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2402 $errors[] = array( 'actionthrottledtext' );
2404 # If there were errors, bail out now
2408 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2412 * Backend implementation of doRollback(), please refer there for parameter
2413 * and return value documentation
2415 * NOTE: This function does NOT check ANY permissions, it just commits the
2416 * rollback to the DB Therefore, you should only call this function direct-
2417 * ly if you want to use custom permissions checks. If you don't, use
2418 * doRollback() instead.
2420 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2421 global $wgUseRCPatrol, $wgUser;
2422 $dbw = wfGetDB( DB_MASTER
);
2424 if( wfReadOnly() ) {
2425 return array( array( 'readonlytext' ) );
2428 # Get the last editor
2429 $current = Revision
::newFromTitle( $this->mTitle
);
2430 if( is_null( $current ) ) {
2431 # Something wrong... no page?
2432 return array(array('notanarticle'));
2435 $from = str_replace( '_', ' ', $fromP );
2436 if( $from != $current->getUserText() ) {
2437 $resultDetails = array( 'current' => $current );
2438 return array(array('alreadyrolled',
2439 htmlspecialchars($this->mTitle
->getPrefixedText()),
2440 htmlspecialchars($fromP),
2441 htmlspecialchars($current->getUserText())
2445 # Get the last edit not by this guy
2446 $user = intval( $current->getUser() );
2447 $user_text = $dbw->addQuotes( $current->getUserText() );
2448 $s = $dbw->selectRow( 'revision',
2449 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2450 array( 'rev_page' => $current->getPage(),
2451 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2453 array( 'USE INDEX' => 'page_timestamp',
2454 'ORDER BY' => 'rev_timestamp DESC' )
2456 if( $s === false ) {
2457 # No one else ever edited this page
2458 return array(array('cantrollback'));
2459 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2460 # Only admins can see this text
2461 return array(array('notvisiblerev'));
2465 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2466 # Mark all reverted edits as bot
2469 if ( $wgUseRCPatrol ) {
2470 # Mark all reverted edits as patrolled
2471 $set['rc_patrolled'] = 1;
2475 $dbw->update( 'recentchanges', $set,
2477 'rc_cur_id' => $current->getPage(),
2478 'rc_user_text' => $current->getUserText(),
2479 "rc_timestamp > '{$s->rev_timestamp}'",
2484 # Generate the edit summary if necessary
2485 $target = Revision
::newFromId( $s->rev_id
);
2486 if( empty( $summary ) )
2489 $summary = wfMsgForContent( 'revertpage',
2490 $target->getUserText(), $from,
2491 $s->rev_id
, $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2492 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2497 $flags = EDIT_UPDATE
;
2499 if ($wgUser->isAllowed('minoredit'))
2500 $flags |
= EDIT_MINOR
;
2502 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2503 $flags |
= EDIT_FORCE_BOT
;
2504 $this->doEdit( $target->getText(), $summary, $flags );
2506 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2508 $resultDetails = array(
2509 'summary' => $summary,
2510 'current' => $current,
2511 'target' => $target,
2517 * User interface for rollback operations
2519 function rollback() {
2520 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2523 $result = $this->doRollback(
2524 $wgRequest->getVal( 'from' ),
2525 $wgRequest->getText( 'summary' ),
2526 $wgRequest->getVal( 'token' ),
2527 $wgRequest->getBool( 'bot' ),
2531 if( in_array( array( 'blocked' ), $result ) ) {
2532 $wgOut->blockedPage();
2535 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2536 $wgOut->rateLimited();
2539 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2540 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2541 $errArray = $result[0];
2542 $errMsg = array_shift( $errArray );
2543 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2544 if( isset( $details['current'] ) ){
2545 $current = $details['current'];
2546 if( $current->getComment() != '' ) {
2547 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2552 # Display permissions errors before read-only message -- there's no
2553 # point in misleading the user into thinking the inability to rollback
2554 # is only temporary.
2555 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2556 # array_diff is completely broken for arrays of arrays, sigh. Re-
2557 # move any 'readonlytext' error manually.
2559 foreach( $result as $error ) {
2560 if( $error != array( 'readonlytext' ) ) {
2564 $wgOut->showPermissionsErrorPage( $out );
2567 if( $result == array( array('readonlytext') ) ) {
2568 $wgOut->readOnlyPage();
2572 $current = $details['current'];
2573 $target = $details['target'];
2574 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2575 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2576 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2577 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2578 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2579 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2580 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2581 $wgOut->returnToMain( false, $this->mTitle
);
2586 * Do standard deferred updates after page view
2589 function viewUpdates() {
2590 global $wgDeferredUpdateList;
2592 if ( 0 != $this->getID() ) {
2593 global $wgDisableCounters;
2594 if( !$wgDisableCounters ) {
2595 Article
::incViewCount( $this->getID() );
2596 $u = new SiteStatsUpdate( 1, 0, 0 );
2597 array_push( $wgDeferredUpdateList, $u );
2601 # Update newtalk / watchlist notification status
2603 $wgUser->clearNotification( $this->mTitle
);
2607 * Prepare text which is about to be saved.
2608 * Returns a stdclass with source, pst and output members
2610 function prepareTextForEdit( $text, $revid=null ) {
2611 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2613 return $this->mPreparedEdit
;
2616 $edit = (object)array();
2617 $edit->revid
= $revid;
2618 $edit->newText
= $text;
2619 $edit->pst
= $this->preSaveTransform( $text );
2620 $options = new ParserOptions
;
2621 $options->setTidy( true );
2622 $options->enableLimitReport();
2623 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2624 $edit->oldText
= $this->getContent();
2625 $this->mPreparedEdit
= $edit;
2630 * Do standard deferred updates after page edit.
2631 * Update links tables, site stats, search index and message cache.
2632 * Every 100th edit, prune the recent changes table.
2635 * @param $text New text of the article
2636 * @param $summary Edit summary
2637 * @param $minoredit Minor edit
2638 * @param $timestamp_of_pagechange Timestamp associated with the page change
2639 * @param $newid rev_id value of the new revision
2640 * @param $changed Whether or not the content actually changed
2642 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2643 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2645 wfProfileIn( __METHOD__
);
2648 # Be careful not to double-PST: $text is usually already PST-ed once
2649 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2650 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2651 $editInfo = $this->prepareTextForEdit( $text, $newid );
2653 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2654 $editInfo = $this->mPreparedEdit
;
2657 # Save it to the parser cache
2658 if ( $wgEnableParserCache ) {
2659 $parserCache = ParserCache
::singleton();
2660 $parserCache->save( $editInfo->output
, $this, $wgUser );
2663 # Update the links tables
2664 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2667 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2668 if ( 0 == mt_rand( 0, 99 ) ) {
2669 // Flush old entries from the `recentchanges` table; we do this on
2670 // random requests so as to avoid an increase in writes for no good reason
2672 $dbw = wfGetDB( DB_MASTER
);
2673 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2674 $recentchanges = $dbw->tableName( 'recentchanges' );
2675 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2676 $dbw->query( $sql );
2680 $id = $this->getID();
2681 $title = $this->mTitle
->getPrefixedDBkey();
2682 $shortTitle = $this->mTitle
->getDBkey();
2685 wfProfileOut( __METHOD__
);
2689 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2690 array_push( $wgDeferredUpdateList, $u );
2691 $u = new SearchUpdate( $id, $title, $text );
2692 array_push( $wgDeferredUpdateList, $u );
2694 # If this is another user's talk page, update newtalk
2695 # Don't do this if $changed = false otherwise some idiot can null-edit a
2696 # load of user talk pages and piss people off, nor if it's a minor edit
2697 # by a properly-flagged bot.
2698 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2699 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2700 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2701 $other = User
::newFromName( $shortTitle );
2702 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2703 // An anonymous user
2704 $other = new User();
2705 $other->setName( $shortTitle );
2708 $other->setNewtalk( true );
2713 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2714 $wgMessageCache->replace( $shortTitle, $text );
2717 wfProfileOut( __METHOD__
);
2721 * Perform article updates on a special page creation.
2723 * @param Revision $rev
2725 * @todo This is a shitty interface function. Kill it and replace the
2726 * other shitty functions like editUpdates and such so it's not needed
2729 function createUpdates( $rev ) {
2730 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2731 $this->mTotalAdjustment
= 1;
2732 $this->editUpdates( $rev->getText(), $rev->getComment(),
2733 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2737 * Generate the navigation links when browsing through an article revisions
2738 * It shows the information as:
2739 * Revision as of \<date\>; view current revision
2740 * \<- Previous version | Next Version -\>
2743 * @param string $oldid Revision ID of this article revision
2745 function setOldSubtitle( $oldid=0 ) {
2746 global $wgLang, $wgOut, $wgUser;
2748 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2752 $revision = Revision
::newFromId( $oldid );
2754 $current = ( $oldid == $this->mLatest
);
2755 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2756 $sk = $wgUser->getSkin();
2758 ?
wfMsg( 'currentrevisionlink' )
2759 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2762 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2763 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2765 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2766 : wfMsg( 'previousrevision' );
2768 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2770 $nextlink = $current
2771 ?
wfMsg( 'nextrevision' )
2772 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2773 $nextdiff = $current
2775 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2778 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2779 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2780 if( $revision->isCurrent() ) {
2781 // We don't handle top deleted edits too well
2782 $cdel = wfMsgHtml('rev-delundel');
2783 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2784 // If revision was hidden from sysops
2785 $cdel = wfMsgHtml('rev-delundel');
2787 $cdel = $sk->makeKnownLinkObj( $revdel,
2788 wfMsgHtml('rev-delundel'),
2789 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2790 '&oldid=' . urlencode( $oldid ) );
2791 // Bolden oversighted content
2792 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2793 $cdel = "<strong>$cdel</strong>";
2795 $cdel = "(<small>$cdel</small>) ";
2797 # Show user links if allowed to see them. Normally they
2798 # are hidden regardless, but since we can already see the text here...
2799 $userlinks = $sk->revUserTools( $revision, false );
2801 $m = wfMsg( 'revision-info-current' );
2802 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2803 ?
'revision-info-current'
2806 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2808 "\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";
2809 $wgOut->setSubtitle( $r );
2813 * This function is called right before saving the wikitext,
2814 * so we can do things like signatures and links-in-context.
2816 * @param string $text
2818 function preSaveTransform( $text ) {
2819 global $wgParser, $wgUser;
2820 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2823 /* Caching functions */
2826 * checkLastModified returns true if it has taken care of all
2827 * output to the client that is necessary for this request.
2828 * (that is, it has sent a cached version of the page)
2830 function tryFileCache() {
2831 static $called = false;
2833 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2837 if($this->isFileCacheable()) {
2838 $touched = $this->mTouched
;
2839 $cache = new HTMLFileCache( $this->mTitle
);
2840 if($cache->isFileCacheGood( $touched )) {
2841 wfDebug( "Article::tryFileCache(): about to load file\n" );
2842 $cache->loadFromFileCache();
2845 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2846 ob_start( array(&$cache, 'saveToFileCache' ) );
2849 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2854 * Check if the page can be cached
2857 function isFileCacheable() {
2858 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2859 $action = $wgRequest->getVal( 'action' );
2860 $oldid = $wgRequest->getVal( 'oldid' );
2861 $diff = $wgRequest->getVal( 'diff' );
2862 $redirect = $wgRequest->getVal( 'redirect' );
2863 $printable = $wgRequest->getVal( 'printable' );
2864 $page = $wgRequest->getVal( 'page' );
2866 //check for non-standard user language; this covers uselang,
2867 //and extensions for auto-detecting user language.
2868 $ulang = $wgLang->getCode();
2869 $clang = $wgContLang->getCode();
2871 $cacheable = $wgUseFileCache
2872 && (!$wgShowIPinHeader)
2873 && ($this->getID() != 0)
2874 && ($wgUser->isAnon())
2875 && (!$wgUser->getNewtalk())
2876 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2877 && (empty( $action ) ||
$action == 'view')
2880 && (!isset($redirect))
2881 && (!isset($printable))
2883 && (!$this->mRedirectedFrom
)
2884 && ($ulang === $clang);
2887 //extension may have reason to disable file caching on some pages.
2888 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2895 * Loads page_touched and returns a value indicating if it should be used
2898 function checkTouched() {
2899 if( !$this->mDataLoaded
) {
2900 $this->loadPageData();
2902 return !$this->mIsRedirect
;
2906 * Get the page_touched field
2908 function getTouched() {
2909 # Ensure that page data has been loaded
2910 if( !$this->mDataLoaded
) {
2911 $this->loadPageData();
2913 return $this->mTouched
;
2917 * Get the page_latest field
2919 function getLatest() {
2920 if ( !$this->mDataLoaded
) {
2921 $this->loadPageData();
2923 return $this->mLatest
;
2927 * Edit an article without doing all that other stuff
2928 * The article must already exist; link tables etc
2929 * are not updated, caches are not flushed.
2931 * @param string $text text submitted
2932 * @param string $comment comment submitted
2933 * @param bool $minor whereas it's a minor modification
2935 function quickEdit( $text, $comment = '', $minor = 0 ) {
2936 wfProfileIn( __METHOD__
);
2938 $dbw = wfGetDB( DB_MASTER
);
2940 $revision = new Revision( array(
2941 'page' => $this->getId(),
2943 'comment' => $comment,
2944 'minor_edit' => $minor ?
1 : 0,
2946 $revision->insertOn( $dbw );
2947 $this->updateRevisionOn( $dbw, $revision );
2950 wfProfileOut( __METHOD__
);
2954 * Used to increment the view counter
2957 * @param integer $id article id
2959 function incViewCount( $id ) {
2960 $id = intval( $id );
2961 global $wgHitcounterUpdateFreq, $wgDBtype;
2963 $dbw = wfGetDB( DB_MASTER
);
2964 $pageTable = $dbw->tableName( 'page' );
2965 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2966 $acchitsTable = $dbw->tableName( 'acchits' );
2968 if( $wgHitcounterUpdateFreq <= 1 ) {
2969 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2973 # Not important enough to warrant an error page in case of failure
2974 $oldignore = $dbw->ignoreErrors( true );
2976 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2978 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2979 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2980 # Most of the time (or on SQL errors), skip row count check
2981 $dbw->ignoreErrors( $oldignore );
2985 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2986 $row = $dbw->fetchObject( $res );
2987 $rown = intval( $row->n
);
2988 if( $rown >= $wgHitcounterUpdateFreq ){
2989 wfProfileIn( 'Article::incViewCount-collect' );
2990 $old_user_abort = ignore_user_abort( true );
2992 if ($wgDBtype == 'mysql')
2993 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2994 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2995 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2996 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2998 $dbw->query("DELETE FROM $hitcounterTable");
2999 if ($wgDBtype == 'mysql') {
3000 $dbw->query('UNLOCK TABLES');
3001 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3002 'WHERE page_id = hc_id');
3005 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3006 "FROM $acchitsTable WHERE page_id = hc_id");
3008 $dbw->query("DROP TABLE $acchitsTable");
3010 ignore_user_abort( $old_user_abort );
3011 wfProfileOut( 'Article::incViewCount-collect' );
3013 $dbw->ignoreErrors( $oldignore );
3017 * The onArticle*() functions are supposed to be a kind of hooks
3018 * which should be called whenever any of the specified actions
3021 * This is a good place to put code to clear caches, for instance.
3023 * This is called on page move and undelete, as well as edit
3025 * @param $title_obj a title object
3028 static function onArticleCreate($title) {
3029 # The talk page isn't in the regular link tables, so we need to update manually:
3030 if ( $title->isTalkPage() ) {
3031 $other = $title->getSubjectPage();
3033 $other = $title->getTalkPage();
3035 $other->invalidateCache();
3036 $other->purgeSquid();
3038 $title->touchLinks();
3039 $title->purgeSquid();
3040 $title->deleteTitleProtection();
3043 static function onArticleDelete( $title ) {
3044 global $wgUseFileCache, $wgMessageCache;
3046 // Update existence markers on article/talk tabs...
3047 if( $title->isTalkPage() ) {
3048 $other = $title->getSubjectPage();
3050 $other = $title->getTalkPage();
3052 $other->invalidateCache();
3053 $other->purgeSquid();
3055 $title->touchLinks();
3056 $title->purgeSquid();
3059 if ( $wgUseFileCache ) {
3060 $cm = new HTMLFileCache( $title );
3061 @unlink
( $cm->fileCacheName() );
3064 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3065 $wgMessageCache->replace( $title->getDBkey(), false );
3067 if( $title->getNamespace() == NS_IMAGE
) {
3068 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3069 $update->doUpdate();
3074 * Purge caches on page update etc
3076 static function onArticleEdit( $title ) {
3077 global $wgDeferredUpdateList, $wgUseFileCache;
3079 // Invalidate caches of articles which include this page
3080 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3082 // Invalidate the caches of all pages which redirect here
3083 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3085 # Purge squid for this page only
3086 $title->purgeSquid();
3089 if ( $wgUseFileCache ) {
3090 $cm = new HTMLFileCache( $title );
3091 @unlink
( $cm->fileCacheName() );
3098 * Overriden by ImagePage class, only present here to avoid a fatal error
3099 * Called for ?action=revert
3101 public function revert(){
3103 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3107 * Info about this page
3108 * Called for ?action=info when $wgAllowPageInfo is on.
3113 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3115 if ( !$wgAllowPageInfo ) {
3116 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3120 $page = $this->mTitle
->getSubjectPage();
3122 $wgOut->setPagetitle( $page->getPrefixedText() );
3123 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3124 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3126 if( !$this->mTitle
->exists() ) {
3127 $wgOut->addHtml( '<div class="noarticletext">' );
3128 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3129 // This doesn't quite make sense; the user is asking for
3130 // information about the _page_, not the message... -- RC
3131 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3133 $msg = $wgUser->isLoggedIn()
3135 : 'noarticletextanon';
3136 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3138 $wgOut->addHtml( '</div>' );
3140 $dbr = wfGetDB( DB_SLAVE
);
3142 'wl_title' => $page->getDBkey(),
3143 'wl_namespace' => $page->getNamespace() );
3144 $numwatchers = $dbr->selectField(
3149 $this->getSelectOptions() );
3151 $pageInfo = $this->pageCountInfo( $page );
3152 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3154 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3155 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3157 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3159 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3161 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3163 $wgOut->addHTML( '</ul>' );
3169 * Return the total number of edits and number of unique editors
3170 * on a given page. If page does not exist, returns false.
3172 * @param Title $title
3176 function pageCountInfo( $title ) {
3177 $id = $title->getArticleId();
3182 $dbr = wfGetDB( DB_SLAVE
);
3184 $rev_clause = array( 'rev_page' => $id );
3186 $edits = $dbr->selectField(
3191 $this->getSelectOptions() );
3193 $authors = $dbr->selectField(
3195 'COUNT(DISTINCT rev_user_text)',
3198 $this->getSelectOptions() );
3200 return array( 'edits' => $edits, 'authors' => $authors );
3204 * Return a list of templates used by this article.
3205 * Uses the templatelinks table
3207 * @return array Array of Title objects
3209 function getUsedTemplates() {
3211 $id = $this->mTitle
->getArticleID();
3216 $dbr = wfGetDB( DB_SLAVE
);
3217 $res = $dbr->select( array( 'templatelinks' ),
3218 array( 'tl_namespace', 'tl_title' ),
3219 array( 'tl_from' => $id ),
3220 'Article:getUsedTemplates' );
3221 if ( false !== $res ) {
3222 if ( $dbr->numRows( $res ) ) {
3223 while ( $row = $dbr->fetchObject( $res ) ) {
3224 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3228 $dbr->freeResult( $res );
3233 * Returns a list of hidden categories this page is a member of.
3234 * Uses the page_props and categorylinks tables.
3236 * @return array Array of Title objects
3238 function getHiddenCategories() {
3240 $id = $this->mTitle
->getArticleID();
3245 $dbr = wfGetDB( DB_SLAVE
);
3246 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3248 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3249 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3250 'Article:getHiddenCategories' );
3251 if ( false !== $res ) {
3252 if ( $dbr->numRows( $res ) ) {
3253 while ( $row = $dbr->fetchObject( $res ) ) {
3254 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3258 $dbr->freeResult( $res );
3263 * Return an auto-generated summary if the text provided is a redirect.
3265 * @param string $text The wikitext to check
3266 * @return string '' or an appropriate summary
3268 public static function getRedirectAutosummary( $text ) {
3269 $rt = Title
::newFromRedirect( $text );
3270 if( is_object( $rt ) )
3271 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3277 * Return an auto-generated summary if the new text is much shorter than
3280 * @param string $oldtext The previous text of the page
3281 * @param string $text The submitted text of the page
3282 * @return string An appropriate autosummary, or an empty string.
3284 public static function getBlankingAutosummary( $oldtext, $text ) {
3285 if ($oldtext!='' && $text=='') {
3286 return wfMsgForContent('autosumm-blank');
3287 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3288 #Removing more than 90% of the article
3290 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3291 return wfMsgForContent('autosumm-replace', $truncatedtext);
3298 * Return an applicable autosummary if one exists for the given edit.
3299 * @param string $oldtext The previous text of the page.
3300 * @param string $newtext The submitted text of the page.
3301 * @param bitmask $flags A bitmask of flags submitted for the edit.
3302 * @return string An appropriate autosummary, or an empty string.
3304 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3306 # This code is UGLY UGLY UGLY.
3307 # Somebody PLEASE come up with a more elegant way to do it.
3309 #Redirect autosummaries
3310 $summary = self
::getRedirectAutosummary( $newtext );
3315 #Blanking autosummaries
3316 if (!($flags & EDIT_NEW
))
3317 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3322 #New page autosummaries
3323 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3324 #If they're making a new article, give its text, truncated, in the summary.
3326 $truncatedtext = $wgContLang->truncate(
3327 str_replace("\n", ' ', $newtext),
3328 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3330 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3340 * Add the primary page-view wikitext to the output buffer
3341 * Saves the text into the parser cache if possible.
3342 * Updates templatelinks if it is out of date.
3344 * @param string $text
3345 * @param bool $cache
3347 public function outputWikiText( $text, $cache = true ) {
3348 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3350 $popts = $wgOut->parserOptions();
3351 $popts->setTidy(true);
3352 $popts->enableLimitReport();
3353 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3354 $popts, true, true, $this->getRevIdFetched() );
3355 $popts->setTidy(false);
3356 $popts->enableLimitReport( false );
3357 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3358 $parserCache = ParserCache
::singleton();
3359 $parserCache->save( $parserOutput, $this, $wgUser );
3362 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3363 // templatelinks table may have become out of sync,
3364 // especially if using variable-based transclusions.
3365 // For paranoia, check if things have changed and if
3366 // so apply updates to the database. This will ensure
3367 // that cascaded protections apply as soon as the changes
3370 # Get templates from templatelinks
3371 $id = $this->mTitle
->getArticleID();
3373 $tlTemplates = array();
3375 $dbr = wfGetDB( DB_SLAVE
);
3376 $res = $dbr->select( array( 'templatelinks' ),
3377 array( 'tl_namespace', 'tl_title' ),
3378 array( 'tl_from' => $id ),
3379 'Article:getUsedTemplates' );
3383 if ( false !== $res ) {
3384 if ( $dbr->numRows( $res ) ) {
3385 while ( $row = $dbr->fetchObject( $res ) ) {
3386 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3391 # Get templates from parser output.
3392 $poTemplates_allns = $parserOutput->getTemplates();
3394 $poTemplates = array ();
3395 foreach ( $poTemplates_allns as $ns_templates ) {
3396 $poTemplates = array_merge( $poTemplates, $ns_templates );
3400 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3402 if ( count( $templates_diff ) > 0 ) {
3403 # Whee, link updates time.
3404 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3406 $dbw = wfGetDb( DB_MASTER
);
3415 $wgOut->addParserOutput( $parserOutput );
3419 * Update all the appropriate counts in the category table, given that
3420 * we've added the categories $added and deleted the categories $deleted.
3422 * @param $added array The names of categories that were added
3423 * @param $deleted array The names of categories that were deleted
3426 public function updateCategoryCounts( $added, $deleted ) {
3427 $ns = $this->mTitle
->getNamespace();
3428 $dbw = wfGetDB( DB_MASTER
);
3430 # First make sure the rows exist. If one of the "deleted" ones didn't
3431 # exist, we might legitimately not create it, but it's simpler to just
3432 # create it and then give it a negative value, since the value is bogus
3435 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3436 $insertCats = array_merge( $added, $deleted );
3437 if( !$insertCats ) {
3438 # Okay, nothing to do
3441 $insertRows = array();
3442 foreach( $insertCats as $cat ) {
3443 $insertRows[] = array( 'cat_title' => $cat );
3445 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3447 $addFields = array( 'cat_pages = cat_pages + 1' );
3448 $removeFields = array( 'cat_pages = cat_pages - 1' );
3449 if( $ns == NS_CATEGORY
) {
3450 $addFields[] = 'cat_subcats = cat_subcats + 1';
3451 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3452 } elseif( $ns == NS_IMAGE
) {
3453 $addFields[] = 'cat_files = cat_files + 1';
3454 $removeFields[] = 'cat_files = cat_files - 1';
3461 array( 'cat_title' => $added ),
3469 array( 'cat_title' => $deleted ),