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; //!<
40 * Constructor and clear the article
41 * @param $title Reference to a Title object.
42 * @param $oldId Integer revision ID, null to fetch from request, zero for current
44 function __construct( Title
$title, $oldId = null ) {
45 $this->mTitle
=& $title;
46 $this->mOldId
= $oldId;
51 * Tell the page view functions that this view was redirected
52 * from another page on the wiki.
53 * @param $from Title object.
55 function setRedirectedFrom( $from ) {
56 $this->mRedirectedFrom
= $from;
60 * @return mixed false, Title of in-wiki target, or string with URL
62 function followRedirect() {
63 $text = $this->getContent();
64 $rt = Title
::newFromRedirect( $text );
66 # process if title object is valid and not special:userlogout
68 if( $rt->getInterwiki() != '' ) {
69 if( $rt->isLocal() ) {
70 // Offsite wikis need an HTTP redirect.
72 // This can be hard to reverse and may produce loops,
73 // so they may be disabled in the site configuration.
75 $source = $this->mTitle
->getFullURL( 'redirect=no' );
76 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
79 if( $rt->getNamespace() == NS_SPECIAL
) {
80 // Gotta handle redirects to special pages differently:
81 // Fill the HTTP response "Location" header and ignore
82 // the rest of the page we're on.
84 // This can be hard to reverse, so they may be disabled.
86 if( $rt->isSpecial( 'Userlogout' ) ) {
89 return $rt->getFullURL();
96 // No or invalid redirect
101 * get the title object of the article
103 function getTitle() {
104 return $this->mTitle
;
112 $this->mDataLoaded
= false;
113 $this->mContentLoaded
= false;
115 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
116 $this->mRedirectedFrom
= null; # Title object if set
118 $this->mTimestamp
= $this->mComment
= '';
119 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
120 $this->mTouched
= '19700101000000';
121 $this->mForUpdate
= false;
122 $this->mIsRedirect
= false;
123 $this->mRevIdFetched
= 0;
124 $this->mRedirectUrl
= false;
125 $this->mLatest
= false;
126 $this->mPreparedEdit
= false;
130 * Note that getContent/loadContent do not follow redirects anymore.
131 * If you need to fetch redirectable content easily, try
132 * the shortcut in Article::followContent()
134 * @todo There are still side-effects in this!
135 * In general, you should use the Revision class, not Article,
136 * to fetch text for purposes other than page views.
138 * @return Return the text of this revision
140 function getContent() {
141 global $wgUser, $wgOut, $wgMessageCache;
143 wfProfileIn( __METHOD__
);
145 if ( 0 == $this->getID() ) {
146 wfProfileOut( __METHOD__
);
147 $wgOut->setRobotpolicy( 'noindex,nofollow' );
149 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
150 $wgMessageCache->loadAllMessages();
151 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
153 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
156 return "<div class='noarticletext'>$ret</div>";
158 $this->loadContent();
159 wfProfileOut( __METHOD__
);
160 return $this->mContent
;
165 * This function returns the text of a section, specified by a number ($section).
166 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
167 * the first section before any such heading (section 0).
169 * If a section contains subsections, these are also returned.
171 * @param $text String: text to look in
172 * @param $section Integer: section number
173 * @return string text of the requested section
176 function getSection($text,$section) {
178 return $wgParser->getSection( $text, $section );
182 * @return int The oldid of the article that is to be shown, 0 for the
185 function getOldID() {
186 if ( is_null( $this->mOldId
) ) {
187 $this->mOldId
= $this->getOldIDFromRequest();
189 return $this->mOldId
;
193 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
195 * @return int The old id for the request
197 function getOldIDFromRequest() {
199 $this->mRedirectUrl
= false;
200 $oldid = $wgRequest->getVal( 'oldid' );
201 if ( isset( $oldid ) ) {
202 $oldid = intval( $oldid );
203 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
204 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
208 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
210 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
211 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
229 * Load the revision (including text) into this object
231 function loadContent() {
232 if ( $this->mContentLoaded
) return;
235 $oldid = $this->getOldID();
237 # Pre-fill content with error message so that if something
238 # fails we'll have something telling us what we intended.
239 $this->mOldId
= $oldid;
240 $this->fetchContent( $oldid );
245 * Fetch a page record with the given conditions
246 * @param Database $dbr
247 * @param array $conditions
250 function pageData( $dbr, $conditions ) {
264 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
265 $row = $dbr->selectRow(
271 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
276 * @param Database $dbr
277 * @param Title $title
279 function pageDataFromTitle( $dbr, $title ) {
280 return $this->pageData( $dbr, array(
281 'page_namespace' => $title->getNamespace(),
282 'page_title' => $title->getDBkey() ) );
286 * @param Database $dbr
289 function pageDataFromId( $dbr, $id ) {
290 return $this->pageData( $dbr, array( 'page_id' => $id ) );
294 * Set the general counter, title etc data loaded from
297 * @param object $data
300 function loadPageData( $data = 'fromdb' ) {
301 if ( $data === 'fromdb' ) {
302 $dbr = $this->getDB();
303 $data = $this->pageDataFromId( $dbr, $this->getId() );
306 $lc =& LinkCache
::singleton();
308 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
310 $this->mTitle
->mArticleID
= $data->page_id
;
312 # Old-fashioned restrictions.
313 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
315 $this->mCounter
= $data->page_counter
;
316 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
317 $this->mIsRedirect
= $data->page_is_redirect
;
318 $this->mLatest
= $data->page_latest
;
320 if ( is_object( $this->mTitle
) ) {
321 $lc->addBadLinkObj( $this->mTitle
);
323 $this->mTitle
->mArticleID
= 0;
326 $this->mDataLoaded
= true;
330 * Get text of an article from database
331 * Does *NOT* follow redirects.
332 * @param int $oldid 0 for whatever the latest revision is
335 function fetchContent( $oldid = 0 ) {
336 if ( $this->mContentLoaded
) {
337 return $this->mContent
;
340 $dbr = $this->getDB();
342 # Pre-fill content with error message so that if something
343 # fails we'll have something telling us what we intended.
344 $t = $this->mTitle
->getPrefixedText();
346 $t .= ',oldid='.$oldid;
348 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
351 $revision = Revision
::newFromId( $oldid );
352 if( is_null( $revision ) ) {
353 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
356 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
358 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
361 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
362 $this->loadPageData( $data );
364 if( !$this->mDataLoaded
) {
365 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
367 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
370 $this->loadPageData( $data );
372 $revision = Revision
::newFromId( $this->mLatest
);
373 if( is_null( $revision ) ) {
374 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
379 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
380 // We should instead work with the Revision object when we need it...
381 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
382 //$this->mContent = $revision->getText();
384 $this->mUser
= $revision->getUser();
385 $this->mUserText
= $revision->getUserText();
386 $this->mComment
= $revision->getComment();
387 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
389 $this->mRevIdFetched
= $revision->getID();
390 $this->mContentLoaded
= true;
391 $this->mRevision
=& $revision;
393 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
395 return $this->mContent
;
399 * Read/write accessor to select FOR UPDATE
401 * @param $x Mixed: FIXME
403 function forUpdate( $x = NULL ) {
404 return wfSetVar( $this->mForUpdate
, $x );
408 * Get the database which should be used for reads
413 return wfGetDB( DB_MASTER
);
417 * Get options for all SELECT statements
419 * @param $options Array: an optional options array which'll be appended to
421 * @return Array: options
423 function getSelectOptions( $options = '' ) {
424 if ( $this->mForUpdate
) {
425 if ( is_array( $options ) ) {
426 $options[] = 'FOR UPDATE';
428 $options = 'FOR UPDATE';
435 * @return int Page ID
438 if( $this->mTitle
) {
439 return $this->mTitle
->getArticleID();
446 * @return bool Whether or not the page exists in the database
449 return $this->getId() != 0;
453 * @return int The view count for the page
455 function getCount() {
456 if ( -1 == $this->mCounter
) {
457 $id = $this->getID();
461 $dbr = wfGetDB( DB_SLAVE
);
462 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
463 'Article::getCount', $this->getSelectOptions() );
466 return $this->mCounter
;
470 * Determine whether a page would be suitable for being counted as an
471 * article in the site_stats table based on the title & its content
473 * @param $text String: text to analyze
476 function isCountable( $text ) {
477 global $wgUseCommaCount;
479 $token = $wgUseCommaCount ?
',' : '[[';
481 $this->mTitle
->isContentPage()
482 && !$this->isRedirect( $text )
483 && in_string( $token, $text );
487 * Tests if the article text represents a redirect
489 * @param $text String: FIXME
492 function isRedirect( $text = false ) {
493 if ( $text === false ) {
494 $this->loadContent();
495 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
497 $titleObj = Title
::newFromRedirect( $text );
499 return $titleObj !== NULL;
503 * Returns true if the currently-referenced revision is the current edit
504 * to this page (and it exists).
507 function isCurrent() {
508 # If no oldid, this is the current version.
509 if ($this->getOldID() == 0)
512 return $this->exists() &&
513 isset( $this->mRevision
) &&
514 $this->mRevision
->isCurrent();
518 * Loads everything except the text
519 * This isn't necessary for all uses, so it's only done if needed.
522 function loadLastEdit() {
523 if ( -1 != $this->mUser
)
526 # New or non-existent articles have no user information
527 $id = $this->getID();
528 if ( 0 == $id ) return;
530 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
531 if( !is_null( $this->mLastRevision
) ) {
532 $this->mUser
= $this->mLastRevision
->getUser();
533 $this->mUserText
= $this->mLastRevision
->getUserText();
534 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
535 $this->mComment
= $this->mLastRevision
->getComment();
536 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
537 $this->mRevIdFetched
= $this->mLastRevision
->getID();
541 function getTimestamp() {
542 // Check if the field has been filled by ParserCache::get()
543 if ( !$this->mTimestamp
) {
544 $this->loadLastEdit();
546 return wfTimestamp(TS_MW
, $this->mTimestamp
);
550 $this->loadLastEdit();
554 function getUserText() {
555 $this->loadLastEdit();
556 return $this->mUserText
;
559 function getComment() {
560 $this->loadLastEdit();
561 return $this->mComment
;
564 function getMinorEdit() {
565 $this->loadLastEdit();
566 return $this->mMinorEdit
;
569 function getRevIdFetched() {
570 $this->loadLastEdit();
571 return $this->mRevIdFetched
;
575 * @todo Document, fixme $offset never used.
576 * @param $limit Integer: default 0.
577 * @param $offset Integer: default 0.
579 function getContributors($limit = 0, $offset = 0) {
580 # XXX: this is expensive; cache this info somewhere.
583 $dbr = wfGetDB( DB_SLAVE
);
584 $revTable = $dbr->tableName( 'revision' );
585 $userTable = $dbr->tableName( 'user' );
586 $user = $this->getUser();
587 $pageId = $this->getId();
589 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
590 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
591 WHERE rev_page = $pageId
592 AND rev_user != $user
593 GROUP BY rev_user, rev_user_text, user_real_name
594 ORDER BY timestamp DESC";
596 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
597 $sql .= ' '. $this->getSelectOptions();
599 $res = $dbr->query($sql, __METHOD__
);
601 while ( $line = $dbr->fetchObject( $res ) ) {
602 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
605 $dbr->freeResult($res);
610 * This is the default action of the script: just view the page of
614 global $wgUser, $wgOut, $wgRequest, $wgContLang;
615 global $wgEnableParserCache, $wgStylePath, $wgParser;
616 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
617 global $wgDefaultRobotPolicy;
618 $sk = $wgUser->getSkin();
620 wfProfileIn( __METHOD__
);
622 $parserCache =& ParserCache
::singleton();
623 $ns = $this->mTitle
->getNamespace(); # shortcut
625 # Get variables from query string
626 $oldid = $this->getOldID();
628 # getOldID may want us to redirect somewhere else
629 if ( $this->mRedirectUrl
) {
630 $wgOut->redirect( $this->mRedirectUrl
);
631 wfProfileOut( __METHOD__
);
635 $diff = $wgRequest->getVal( 'diff' );
636 $rcid = $wgRequest->getVal( 'rcid' );
637 $rdfrom = $wgRequest->getVal( 'rdfrom' );
638 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
639 $purge = $wgRequest->getVal( 'action' ) == 'purge';
641 $wgOut->setArticleFlag( true );
643 # Discourage indexing of printable versions, but encourage following
644 if( $wgOut->isPrintable() ) {
645 $policy = 'noindex,follow';
646 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
647 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
648 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
649 # Honour customised robot policies for this namespace
650 $policy = $wgNamespaceRobotPolicies[$ns];
652 $policy = $wgDefaultRobotPolicy;
654 $wgOut->setRobotPolicy( $policy );
656 # If we got diff and oldid in the query, we want to see a
657 # diff page instead of the article.
659 if ( !is_null( $diff ) ) {
660 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
662 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
663 // DifferenceEngine directly fetched the revision:
664 $this->mRevIdFetched
= $de->mNewid
;
665 $de->showDiffPage( $diffOnly );
667 // Needed to get the page's current revision
668 $this->loadPageData();
669 if( $diff == 0 ||
$diff == $this->mLatest
) {
670 # Run view updates for current revision only
671 $this->viewUpdates();
673 wfProfileOut( __METHOD__
);
677 if ( empty( $oldid ) && $this->checkTouched() ) {
678 $wgOut->setETag($parserCache->getETag($this, $wgUser));
680 if( $wgOut->checkLastModified( $this->mTouched
) ){
681 wfProfileOut( __METHOD__
);
683 } else if ( $this->tryFileCache() ) {
684 # tell wgOut that output is taken care of
686 $this->viewUpdates();
687 wfProfileOut( __METHOD__
);
692 # Should the parser cache be used?
693 $pcache = $wgEnableParserCache
694 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
697 && !$this->mTitle
->isCssOrJsPage()
698 && !$this->mTitle
->isCssJsSubpage();
699 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
700 if ( $wgUser->getOption( 'stubthreshold' ) ) {
701 wfIncrStats( 'pcache_miss_stub' );
704 $wasRedirected = false;
705 if ( isset( $this->mRedirectedFrom
) ) {
706 // This is an internally redirected page view.
707 // We'll need a backlink to the source page for navigation.
708 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
709 $sk = $wgUser->getSkin();
710 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
711 $s = wfMsg( 'redirectedfrom', $redir );
712 $wgOut->setSubtitle( $s );
714 // Set the fragment if one was specified in the redirect
715 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
716 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
717 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
719 $wasRedirected = true;
721 } elseif ( !empty( $rdfrom ) ) {
722 // This is an externally redirected view, from some other wiki.
723 // If it was reported from a trusted site, supply a backlink.
724 global $wgRedirectSources;
725 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
726 $sk = $wgUser->getSkin();
727 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
728 $s = wfMsg( 'redirectedfrom', $redir );
729 $wgOut->setSubtitle( $s );
730 $wasRedirected = true;
735 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
737 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
738 // Ensure that UI elements requiring revision ID have
739 // the correct version information.
740 $wgOut->setRevisionId( $this->mLatest
);
744 if ( !$outputDone ) {
745 $text = $this->getContent();
746 if ( $text === false ) {
747 # Failed to load, replace text with error message
748 $t = $this->mTitle
->getPrefixedText();
750 $t .= ',oldid='.$oldid;
751 $text = wfMsg( 'missingarticle', $t );
753 $text = wfMsg( 'noarticletext', $t );
757 # Another whitelist check in case oldid is altering the title
758 if ( !$this->mTitle
->userCanRead() ) {
759 $wgOut->loginToUse();
764 # We're looking at an old revision
766 if ( !empty( $oldid ) ) {
767 $wgOut->setRobotpolicy( 'noindex,nofollow' );
768 if( is_null( $this->mRevision
) ) {
769 // FIXME: This would be a nice place to load the 'no such page' text.
771 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
772 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
773 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
774 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
775 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
778 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
779 // and we are allowed to see...
787 $wgOut->setRevisionId( $this->getRevIdFetched() );
789 // Pages containing custom CSS or JavaScript get special treatment
790 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
791 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
793 // Give hooks a chance to customise the output
794 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
795 // Wrap the whole lot in a <pre> and don't parse
797 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
798 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
799 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
800 $wgOut->addHtml( "\n</pre>\n" );
805 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
807 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
808 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
809 # Don't overwrite the subtitle if this was an old revision
810 if( !$wasRedirected && $this->isCurrent() ) {
811 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
813 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
815 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
816 '<span class="redirectText">'.$link.'</span>' );
818 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
819 $wgOut->addParserOutputNoText( $parseout );
820 } else if ( $pcache ) {
821 # Display content and save to parser cache
822 $this->outputWikiText( $text );
824 # Display content, don't attempt to save to parser cache
825 # Don't show section-edit links on old revisions... this way lies madness.
826 if( !$this->isCurrent() ) {
827 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
829 # Display content and don't save to parser cache
830 # With timing hack -- TS 2006-07-26
832 $this->outputWikiText( $text, false );
837 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
838 $this->mTitle
->getPrefixedDBkey()));
841 if( !$this->isCurrent() ) {
842 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
847 /* title may have been set from the cache */
848 $t = $wgOut->getPageTitle();
850 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
853 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
854 if( $ns == NS_USER_TALK
&&
855 User
::isIP( $this->mTitle
->getText() ) ) {
856 $wgOut->addWikiMsg('anontalkpagetext');
859 # If we have been passed an &rcid= parameter, we want to give the user a
860 # chance to mark this new article as patrolled.
861 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
863 "<div class='patrollink'>" .
864 wfMsgHtml( 'markaspatrolledlink',
865 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
866 "action=markpatrolled&rcid=$rcid" )
873 if ($wgUseTrackbacks)
874 $this->addTrackbacks();
876 $this->viewUpdates();
877 wfProfileOut( __METHOD__
);
880 function addTrackbacks() {
881 global $wgOut, $wgUser;
883 $dbr = wfGetDB(DB_SLAVE
);
885 /* FROM */ 'trackbacks',
886 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
887 /* WHERE */ array('tb_page' => $this->getID())
890 if (!$dbr->numrows($tbs))
894 while ($o = $dbr->fetchObject($tbs)) {
896 if ($wgUser->isAllowed( 'trackback' )) {
897 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
898 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
899 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
901 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
908 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
911 function deletetrackback() {
912 global $wgUser, $wgRequest, $wgOut, $wgTitle;
914 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
915 $wgOut->addWikiMsg( 'sessionfailure' );
919 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
921 if (count($permission_errors)>0)
923 $wgOut->showPermissionsErrorPage( $permission_errors );
927 $db = wfGetDB(DB_MASTER
);
928 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
929 $wgTitle->invalidateCache();
930 $wgOut->addWikiMsg('trackbackdeleteok');
936 $wgOut->setArticleBodyOnly(true);
941 * Handle action=purge
944 global $wgUser, $wgRequest, $wgOut;
946 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
947 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
951 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
952 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
953 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
954 $msg = str_replace( '$1',
955 "<form method=\"post\" action=\"$action\">\n" .
956 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
959 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
960 $wgOut->setRobotpolicy( 'noindex,nofollow' );
961 $wgOut->addHTML( $msg );
966 * Perform the actions of a page purging
970 // Invalidate the cache
971 $this->mTitle
->invalidateCache();
974 // Commit the transaction before the purge is sent
975 $dbw = wfGetDB( DB_MASTER
);
976 $dbw->immediateCommit();
979 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
982 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
983 global $wgMessageCache;
984 if ( $this->getID() == 0 ) {
987 $text = $this->getContent();
989 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
995 * Insert a new empty page record for this article.
996 * This *must* be followed up by creating a revision
997 * and running $this->updateToLatest( $rev_id );
998 * or else the record will be left in a funky state.
999 * Best if all done inside a transaction.
1001 * @param Database $dbw
1002 * @return int The newly created page_id key
1005 function insertOn( $dbw ) {
1006 wfProfileIn( __METHOD__
);
1008 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1009 $dbw->insert( 'page', array(
1010 'page_id' => $page_id,
1011 'page_namespace' => $this->mTitle
->getNamespace(),
1012 'page_title' => $this->mTitle
->getDBkey(),
1013 'page_counter' => 0,
1014 'page_restrictions' => '',
1015 'page_is_redirect' => 0, # Will set this shortly...
1017 'page_random' => wfRandom(),
1018 'page_touched' => $dbw->timestamp(),
1019 'page_latest' => 0, # Fill this in shortly...
1020 'page_len' => 0, # Fill this in shortly...
1022 $newid = $dbw->insertId();
1024 $this->mTitle
->resetArticleId( $newid );
1026 wfProfileOut( __METHOD__
);
1031 * Update the page record to point to a newly saved revision.
1033 * @param Database $dbw
1034 * @param Revision $revision For ID number, and text used to set
1035 length and redirect status fields
1036 * @param int $lastRevision If given, will not overwrite the page field
1037 * when different from the currently set value.
1038 * Giving 0 indicates the new page flag should
1040 * @param bool $lastRevIsRedirect If given, will optimize adding and
1041 * removing rows in redirect table.
1042 * @return bool true on success, false on failure
1045 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1046 wfProfileIn( __METHOD__
);
1048 $text = $revision->getText();
1049 $rt = Title
::newFromRedirect( $text );
1051 $conditions = array( 'page_id' => $this->getId() );
1052 if( !is_null( $lastRevision ) ) {
1053 # An extra check against threads stepping on each other
1054 $conditions['page_latest'] = $lastRevision;
1057 $dbw->update( 'page',
1059 'page_latest' => $revision->getId(),
1060 'page_touched' => $dbw->timestamp(),
1061 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1062 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1063 'page_len' => strlen( $text ),
1068 $result = $dbw->affectedRows() != 0;
1071 // FIXME: Should the result from updateRedirectOn() be returned instead?
1072 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1075 wfProfileOut( __METHOD__
);
1080 * Add row to the redirect table if this is a redirect, remove otherwise.
1082 * @param Database $dbw
1083 * @param $redirectTitle a title object pointing to the redirect target,
1084 * or NULL if this is not a redirect
1085 * @param bool $lastRevIsRedirect If given, will optimize adding and
1086 * removing rows in redirect table.
1087 * @return bool true on success, false on failure
1090 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1092 // Always update redirects (target link might have changed)
1093 // Update/Insert if we don't know if the last revision was a redirect or not
1094 // Delete if changing from redirect to non-redirect
1095 $isRedirect = !is_null($redirectTitle);
1096 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1098 wfProfileIn( __METHOD__
);
1102 // This title is a redirect, Add/Update row in the redirect table
1103 $set = array( /* SET */
1104 'rd_namespace' => $redirectTitle->getNamespace(),
1105 'rd_title' => $redirectTitle->getDBkey(),
1106 'rd_from' => $this->getId(),
1109 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1111 // This is not a redirect, remove row from redirect table
1112 $where = array( 'rd_from' => $this->getId() );
1113 $dbw->delete( 'redirect', $where, __METHOD__
);
1116 wfProfileOut( __METHOD__
);
1117 return ( $dbw->affectedRows() != 0 );
1124 * If the given revision is newer than the currently set page_latest,
1125 * update the page record. Otherwise, do nothing.
1127 * @param Database $dbw
1128 * @param Revision $revision
1130 function updateIfNewerOn( &$dbw, $revision ) {
1131 wfProfileIn( __METHOD__
);
1133 $row = $dbw->selectRow(
1134 array( 'revision', 'page' ),
1135 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1137 'page_id' => $this->getId(),
1138 'page_latest=rev_id' ),
1141 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1142 wfProfileOut( __METHOD__
);
1145 $prev = $row->rev_id
;
1146 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1148 # No or missing previous revision; mark the page as new
1150 $lastRevIsRedirect = null;
1153 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1154 wfProfileOut( __METHOD__
);
1159 * @return string Complete article text, or null if error
1161 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1162 wfProfileIn( __METHOD__
);
1164 if( $section == '' ) {
1165 // Whole-page edit; let the text through unmolested.
1167 if( is_null( $edittime ) ) {
1168 $rev = Revision
::newFromTitle( $this->mTitle
);
1170 $dbw = wfGetDB( DB_MASTER
);
1171 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1173 if( is_null( $rev ) ) {
1174 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1175 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1178 $oldtext = $rev->getText();
1180 if( $section == 'new' ) {
1181 # Inserting a new section
1182 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1183 $text = strlen( trim( $oldtext ) ) > 0
1184 ?
"{$oldtext}\n\n{$subject}{$text}"
1185 : "{$subject}{$text}";
1187 # Replacing an existing section; roll out the big guns
1189 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1194 wfProfileOut( __METHOD__
);
1199 * @deprecated use Article::doEdit()
1201 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1202 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1203 ( $isminor ? EDIT_MINOR
: 0 ) |
1204 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1205 ( $bot ? EDIT_FORCE_BOT
: 0 );
1207 # If this is a comment, add the summary as headline
1208 if ( $comment && $summary != "" ) {
1209 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1212 $this->doEdit( $text, $summary, $flags );
1214 $dbw = wfGetDB( DB_MASTER
);
1216 if (!$this->mTitle
->userIsWatching()) {
1222 if ( $this->mTitle
->userIsWatching() ) {
1228 $this->doRedirect( $this->isRedirect( $text ) );
1232 * @deprecated use Article::doEdit()
1234 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1235 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1236 ( $minor ? EDIT_MINOR
: 0 ) |
1237 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1239 $good = $this->doEdit( $text, $summary, $flags );
1241 $dbw = wfGetDB( DB_MASTER
);
1243 if (!$this->mTitle
->userIsWatching()) {
1249 if ( $this->mTitle
->userIsWatching() ) {
1256 $extraq = ''; // Give extensions a chance to modify URL query on update
1257 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1259 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1267 * Change an existing article or create a new article. Updates RC and all necessary caches,
1268 * optionally via the deferred update array.
1270 * $wgUser must be set before calling this function.
1272 * @param string $text New text
1273 * @param string $summary Edit summary
1274 * @param integer $flags bitfield:
1276 * Article is known or assumed to be non-existent, create a new one
1278 * Article is known or assumed to be pre-existing, update it
1280 * Mark this edit minor, if the user is allowed to do so
1282 * Do not log the change in recentchanges
1284 * Mark the edit a "bot" edit regardless of user rights
1285 * EDIT_DEFER_UPDATES
1286 * Defer some of the updates until the end of index.php
1288 * Fill in blank summaries with generated text where possible
1290 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1291 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1292 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1293 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1294 * to MediaWiki's performance-optimised locking strategy.
1296 * @return bool success
1298 function doEdit( $text, $summary, $flags = 0 ) {
1299 global $wgUser, $wgDBtransactions;
1301 wfProfileIn( __METHOD__
);
1304 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1305 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1307 $flags |
= EDIT_UPDATE
;
1313 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1314 &$summary, $flags & EDIT_MINOR
,
1315 null, null, &$flags ) ) )
1317 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1318 wfProfileOut( __METHOD__
);
1322 # Silently ignore EDIT_MINOR if not allowed
1323 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1324 $bot = $flags & EDIT_FORCE_BOT
;
1326 $oldtext = $this->getContent();
1327 $oldsize = strlen( $oldtext );
1329 # Provide autosummaries if one is not provided.
1330 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1331 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1333 $editInfo = $this->prepareTextForEdit( $text );
1334 $text = $editInfo->pst
;
1335 $newsize = strlen( $text );
1337 $dbw = wfGetDB( DB_MASTER
);
1338 $now = wfTimestampNow();
1340 if ( $flags & EDIT_UPDATE
) {
1341 # Update article, but only if changed.
1343 # Make sure the revision is either completely inserted or not inserted at all
1344 if( !$wgDBtransactions ) {
1345 $userAbort = ignore_user_abort( true );
1351 $changed = ( strcmp( $text, $oldtext ) != 0 );
1354 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1355 - (int)$this->isCountable( $oldtext );
1356 $this->mTotalAdjustment
= 0;
1358 $lastRevision = $dbw->selectField(
1359 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1361 if ( !$lastRevision ) {
1362 # Article gone missing
1363 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1364 wfProfileOut( __METHOD__
);
1368 $revision = new Revision( array(
1369 'page' => $this->getId(),
1370 'comment' => $summary,
1371 'minor_edit' => $isminor,
1376 $revisionId = $revision->insertOn( $dbw );
1379 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1382 /* Belated edit conflict! Run away!! */
1386 # Update recentchanges
1387 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1388 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1389 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1392 # Mark as patrolled if the user can do so
1393 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1394 RecentChange
::markPatrolled( $rcid );
1395 PatrolLog
::record( $rcid, true );
1398 $wgUser->incEditCount();
1403 // Keep the same revision ID, but do some updates on it
1404 $revisionId = $this->getRevIdFetched();
1405 // Update page_touched, this is usually implicit in the page update
1406 // Other cache updates are done in onArticleEdit()
1407 $this->mTitle
->invalidateCache();
1410 if( !$wgDBtransactions ) {
1411 ignore_user_abort( $userAbort );
1415 # Invalidate cache of this article and all pages using this article
1416 # as a template. Partly deferred.
1417 Article
::onArticleEdit( $this->mTitle
);
1419 # Update links tables, site stats, etc.
1420 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1423 # Create new article
1425 # Set statistics members
1426 # We work out if it's countable after PST to avoid counter drift
1427 # when articles are created with {{subst:}}
1428 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1429 $this->mTotalAdjustment
= 1;
1433 # Add the page record; stake our claim on this title!
1434 # This will fail with a database query exception if the article already exists
1435 $newid = $this->insertOn( $dbw );
1437 # Save the revision text...
1438 $revision = new Revision( array(
1440 'comment' => $summary,
1441 'minor_edit' => $isminor,
1444 $revisionId = $revision->insertOn( $dbw );
1446 $this->mTitle
->resetArticleID( $newid );
1448 # Update the page record with revision data
1449 $this->updateRevisionOn( $dbw, $revision, 0 );
1451 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1452 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1453 '', strlen( $text ), $revisionId );
1454 # Mark as patrolled if the user can
1455 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1456 RecentChange
::markPatrolled( $rcid );
1457 PatrolLog
::record( $rcid, true );
1460 $wgUser->incEditCount();
1463 # Update links, etc.
1464 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1467 Article
::onArticleCreate( $this->mTitle
);
1469 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1470 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1473 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1478 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1479 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1482 wfProfileOut( __METHOD__
);
1487 * @deprecated wrapper for doRedirect
1489 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1490 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1494 * Output a redirect back to the article.
1495 * This is typically used after an edit.
1497 * @param boolean $noRedir Add redirect=no
1498 * @param string $sectionAnchor section to redirect to, including "#"
1500 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1503 $query = 'redirect=no';
1505 $query .= "&$query";
1509 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1513 * Mark this particular edit/page as patrolled
1515 function markpatrolled() {
1516 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1517 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1519 # Check patrol config options
1521 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1522 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1526 # If we haven't been given an rc_id value, we can't do anything
1527 $rcid = (int) $wgRequest->getVal('rcid');
1528 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1529 if ( is_null ( $rc ) )
1531 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1535 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1536 // Only new pages can be patrolled if the general patrolling is off....???
1537 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1539 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1544 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1546 if (count($permission_errors)>0)
1548 $wgOut->showPermissionsErrorPage( $permission_errors );
1552 # Handle the 'MarkPatrolled' hook
1553 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1557 #It would be nice to see where the user had actually come from, but for now just guess
1558 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1559 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1561 # If it's left up to us, check that the user is allowed to patrol this edit
1562 # If the user has the "autopatrol" right, then we'll assume there are no
1563 # other conditions stopping them doing so
1564 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1565 $rc = RecentChange
::newFromId( $rcid );
1566 # Graceful error handling, as we've done before here...
1567 # (If the recent change doesn't exist, then it doesn't matter whether
1568 # the user is allowed to patrol it or not; nothing is going to happen
1569 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1570 # The user made this edit, and can't patrol it
1571 # Tell them so, and then back off
1572 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1573 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1574 $wgOut->returnToMain( false, $return );
1579 # Check that the revision isn't patrolled already
1580 # Prevents duplicate log entries
1581 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1582 # Mark the edit as patrolled
1583 RecentChange
::markPatrolled( $rcid );
1584 PatrolLog
::record( $rcid );
1585 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1589 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1590 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1591 $wgOut->returnToMain( false, $return );
1595 * User-interface handler for the "watch" action
1600 global $wgUser, $wgOut;
1602 if ( $wgUser->isAnon() ) {
1603 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1606 if ( wfReadOnly() ) {
1607 $wgOut->readOnlyPage();
1611 if( $this->doWatch() ) {
1612 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1613 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1615 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1618 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1622 * Add this page to $wgUser's watchlist
1623 * @return bool true on successful watch operation
1625 function doWatch() {
1627 if( $wgUser->isAnon() ) {
1631 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1632 $wgUser->addWatch( $this->mTitle
);
1634 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1641 * User interface handler for the "unwatch" action.
1643 function unwatch() {
1645 global $wgUser, $wgOut;
1647 if ( $wgUser->isAnon() ) {
1648 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1651 if ( wfReadOnly() ) {
1652 $wgOut->readOnlyPage();
1656 if( $this->doUnwatch() ) {
1657 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1658 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1660 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1663 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1667 * Stop watching a page
1668 * @return bool true on successful unwatch
1670 function doUnwatch() {
1672 if( $wgUser->isAnon() ) {
1676 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1677 $wgUser->removeWatch( $this->mTitle
);
1679 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1686 * action=protect handler
1688 function protect() {
1689 $form = new ProtectionForm( $this );
1694 * action=unprotect handler (alias)
1696 function unprotect() {
1701 * Update the article's restriction field, and leave a log entry.
1703 * @param array $limit set of restriction keys
1704 * @param string $reason
1705 * @return bool true on success
1707 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1708 global $wgUser, $wgRestrictionTypes, $wgContLang;
1710 $id = $this->mTitle
->getArticleID();
1711 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1719 // Take this opportunity to purge out expired restrictions
1720 Title
::purgeExpiredRestrictions();
1722 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1723 # we expect a single selection, but the schema allows otherwise.
1725 foreach( $wgRestrictionTypes as $action )
1726 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1728 $current = Article
::flattenRestrictions( $current );
1729 $updated = Article
::flattenRestrictions( $limit );
1731 $changed = ( $current != $updated );
1732 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1733 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1734 $protect = ( $updated != '' );
1736 # If nothing's changed, do nothing
1738 global $wgGroupPermissions;
1739 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1741 $dbw = wfGetDB( DB_MASTER
);
1743 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1745 $expiry_description = '';
1746 if ( $encodedExpiry != 'infinity' ) {
1747 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1750 # Prepare a null revision to be added to the history
1751 $modified = $current != '' && $protect;
1753 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1755 $comment_type = 'unprotectedarticle';
1757 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1759 foreach( $limit as $action => $restrictions ) {
1760 # Check if the group level required to edit also can protect pages
1761 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1762 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1765 $cascade_description = '';
1767 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1771 $comment .= ": $reason";
1773 $comment .= " [$updated]";
1774 if ( $expiry_description && $protect )
1775 $comment .= "$expiry_description";
1777 $comment .= "$cascade_description";
1779 # Update restrictions table
1780 foreach( $limit as $action => $restrictions ) {
1781 if ($restrictions != '' ) {
1782 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1783 array( 'pr_page' => $id, 'pr_type' => $action
1784 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1785 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1787 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1788 'pr_type' => $action ), __METHOD__
);
1792 # Insert a null revision
1793 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1794 $nullRevId = $nullRevision->insertOn( $dbw );
1796 # Update page record
1797 $dbw->update( 'page',
1799 'page_touched' => $dbw->timestamp(),
1800 'page_restrictions' => '',
1801 'page_latest' => $nullRevId
1802 ), array( /* WHERE */
1804 ), 'Article::protect'
1806 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1808 # Update the protection log
1809 $log = new LogPage( 'protect' );
1814 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1816 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1820 } # End "changed" check
1826 * Take an array of page restrictions and flatten it to a string
1827 * suitable for insertion into the page_restrictions field.
1828 * @param array $limit
1832 function flattenRestrictions( $limit ) {
1833 if( !is_array( $limit ) ) {
1834 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1838 foreach( $limit as $action => $restrictions ) {
1839 if( $restrictions != '' ) {
1840 $bits[] = "$action=$restrictions";
1843 return implode( ':', $bits );
1847 * Auto-generates a deletion reason
1848 * @param bool &$hasHistory Whether the page has a history
1850 public function generateReason(&$hasHistory)
1853 $dbw = wfGetDB(DB_MASTER
);
1854 // Get the last revision
1855 $rev = Revision
::newFromTitle($this->mTitle
);
1858 // Get the article's contents
1859 $contents = $rev->getText();
1861 // If the page is blank, use the text from the previous revision,
1862 // which can only be blank if there's a move/import/protect dummy revision involved
1865 $prev = $rev->getPrevious();
1868 $contents = $prev->getText();
1873 // Find out if there was only one contributor
1874 // Only scan the last 20 revisions
1876 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1877 array('LIMIT' => $limit));
1879 // This page has no revisions, which is very weird
1881 if($res->numRows() > 1)
1884 $hasHistory = false;
1885 $row = $dbw->fetchObject($res);
1886 $onlyAuthor = $row->rev_user_text
;
1887 // Try to find a second contributor
1888 while( $row = $dbw->fetchObject($res) ) {
1889 if($row->rev_user_text
!= $onlyAuthor) {
1890 $onlyAuthor = false;
1894 $dbw->freeResult($res);
1896 // Generate the summary with a '$1' placeholder
1898 // The current revision is blank and the one before is also
1899 // blank. It's just not our lucky day
1900 $reason = wfMsgForContent('exbeforeblank', '$1');
1903 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1905 $reason = wfMsgForContent('excontent', '$1');
1908 // Replace newlines with spaces to prevent uglyness
1909 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1910 // Calculate the maximum amount of chars to get
1911 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1912 $maxLength = 255 - (strlen($reason) - 2) - 3;
1913 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1914 // Remove possible unfinished links
1915 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1916 // Now replace the '$1' placeholder
1917 $reason = str_replace( '$1', $contents, $reason );
1923 * UI entry point for page deletion
1926 global $wgUser, $wgOut, $wgRequest;
1928 $confirm = $wgRequest->wasPosted() &&
1929 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1931 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1932 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1934 $reason = $this->DeleteReasonList
;
1936 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1937 // Entry from drop down menu + additional comment
1938 $reason .= ': ' . $this->DeleteReason
;
1939 } elseif ( $reason == 'other' ) {
1940 $reason = $this->DeleteReason
;
1943 # This code desperately needs to be totally rewritten
1945 # Read-only check...
1946 if ( wfReadOnly() ) {
1947 $wgOut->readOnlyPage();
1952 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1954 if (count($permission_errors)>0) {
1955 $wgOut->showPermissionsErrorPage( $permission_errors );
1959 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
1961 # Better double-check that it hasn't been deleted yet!
1962 $dbw = wfGetDB( DB_MASTER
);
1963 $conds = $this->mTitle
->pageCond();
1964 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1965 if ( $latest === false ) {
1966 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1970 # Hack for big sites
1971 $bigHistory = $this->isBigDeletion();
1972 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
1973 global $wgLang, $wgDeleteRevisionsLimit;
1974 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
1975 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1980 $this->doDelete( $reason );
1981 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1983 } elseif( $this->mTitle
->userIsWatching() ) {
1989 // Generate deletion reason
1990 $hasHistory = false;
1991 if ( !$reason ) $reason = $this->generateReason($hasHistory);
1993 // If the page has a history, insert a warning
1994 if( $hasHistory && !$confirm ) {
1995 $skin=$wgUser->getSkin();
1996 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1998 global $wgLang, $wgDeleteRevisionsLimit;
1999 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2000 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2004 return $this->confirmDelete( '', $reason );
2008 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2010 function isBigDeletion() {
2011 global $wgDeleteRevisionsLimit;
2012 if( $wgDeleteRevisionsLimit ) {
2013 $revCount = $this->estimateRevisionCount();
2014 return $revCount > $wgDeleteRevisionsLimit;
2020 * @return int approximate revision count
2022 function estimateRevisionCount() {
2024 // For an exact count...
2025 //return $dbr->selectField( 'revision', 'COUNT(*)',
2026 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2027 return $dbr->estimateRowCount( 'revision', '*',
2028 array( 'rev_page' => $this->getId() ), __METHOD__
);
2032 * Get the last N authors
2033 * @param int $num Number of revisions to get
2034 * @param string $revLatest The latest rev_id, selected from the master (optional)
2035 * @return array Array of authors, duplicates not removed
2037 function getLastNAuthors( $num, $revLatest = 0 ) {
2038 wfProfileIn( __METHOD__
);
2040 // First try the slave
2041 // If that doesn't have the latest revision, try the master
2043 $db = wfGetDB( DB_SLAVE
);
2045 $res = $db->select( array( 'page', 'revision' ),
2046 array( 'rev_id', 'rev_user_text' ),
2048 'page_namespace' => $this->mTitle
->getNamespace(),
2049 'page_title' => $this->mTitle
->getDBkey(),
2050 'rev_page = page_id'
2051 ), __METHOD__
, $this->getSelectOptions( array(
2052 'ORDER BY' => 'rev_timestamp DESC',
2057 wfProfileOut( __METHOD__
);
2060 $row = $db->fetchObject( $res );
2061 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2062 $db = wfGetDB( DB_MASTER
);
2067 } while ( $continue );
2069 $authors = array( $row->rev_user_text
);
2070 while ( $row = $db->fetchObject( $res ) ) {
2071 $authors[] = $row->rev_user_text
;
2073 wfProfileOut( __METHOD__
);
2078 * Output deletion confirmation dialog
2079 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2080 * @param $reason string Prefilled reason
2082 function confirmDelete( $par, $reason ) {
2083 global $wgOut, $wgUser, $wgContLang;
2084 $align = $wgContLang->isRtl() ?
'left' : 'right';
2086 wfDebug( "Article::confirmDelete\n" );
2088 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2089 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2090 $wgOut->addWikiMsg( 'confirmdeletetext' );
2092 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2093 Xml
::openElement( 'fieldset' ) .
2094 Xml
::element( 'legend', array(), wfMsg( 'delete-legend' ) ) .
2095 Xml
::openElement( 'table' ) .
2096 "<tr id=\"wpDeleteReasonListRow\">
2097 <td align='$align'>" .
2098 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2101 Xml
::listDropDown( 'wpDeleteReasonList',
2102 wfMsgForContent( 'deletereason-dropdown' ),
2103 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2106 <tr id=\"wpDeleteReasonRow\">
2107 <td align='$align'>" .
2108 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2111 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2117 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2123 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2126 Xml
::closeElement( 'table' ) .
2127 Xml
::closeElement( 'fieldset' ) .
2128 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2129 Xml
::closeElement( 'form' );
2131 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2132 $skin = $wgUser->getSkin();
2133 $link = $skin->makeLink ( 'MediaWiki:deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2134 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2137 $wgOut->addHTML( $form );
2138 $this->showLogExtract( $wgOut );
2143 * Show relevant lines from the deletion log
2145 function showLogExtract( $out ) {
2146 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2147 $logViewer = new LogViewer(
2150 array( 'page' => $this->mTitle
->getPrefixedText(),
2151 'type' => 'delete' ) ) ) );
2152 $logViewer->showList( $out );
2157 * Perform a deletion and output success or failure messages
2159 function doDelete( $reason ) {
2160 global $wgOut, $wgUser;
2161 wfDebug( __METHOD__
."\n" );
2163 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2164 if ( $this->doDeleteArticle( $reason ) ) {
2165 $deleted = $this->mTitle
->getPrefixedText();
2167 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2168 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2170 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2172 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2173 $wgOut->returnToMain( false );
2174 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2176 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2182 * Back-end article deletion
2183 * Deletes the article with database consistency, writes logs, purges caches
2186 function doDeleteArticle( $reason ) {
2187 global $wgUseSquid, $wgDeferredUpdateList;
2188 global $wgUseTrackbacks;
2190 wfDebug( __METHOD__
."\n" );
2192 $dbw = wfGetDB( DB_MASTER
);
2193 $ns = $this->mTitle
->getNamespace();
2194 $t = $this->mTitle
->getDBkey();
2195 $id = $this->mTitle
->getArticleID();
2197 if ( $t == '' ||
$id == 0 ) {
2201 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2202 array_push( $wgDeferredUpdateList, $u );
2204 // For now, shunt the revision data into the archive table.
2205 // Text is *not* removed from the text table; bulk storage
2206 // is left intact to avoid breaking block-compression or
2207 // immutable storage schemes.
2209 // For backwards compatibility, note that some older archive
2210 // table entries will have ar_text and ar_flags fields still.
2212 // In the future, we may keep revisions and mark them with
2213 // the rev_deleted field, which is reserved for this purpose.
2214 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2216 'ar_namespace' => 'page_namespace',
2217 'ar_title' => 'page_title',
2218 'ar_comment' => 'rev_comment',
2219 'ar_user' => 'rev_user',
2220 'ar_user_text' => 'rev_user_text',
2221 'ar_timestamp' => 'rev_timestamp',
2222 'ar_minor_edit' => 'rev_minor_edit',
2223 'ar_rev_id' => 'rev_id',
2224 'ar_text_id' => 'rev_text_id',
2225 'ar_text' => '\'\'', // Be explicit to appease
2226 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2227 'ar_len' => 'rev_len',
2228 'ar_page_id' => 'page_id',
2231 'page_id = rev_page'
2235 # Delete restrictions for it
2236 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2238 # Now that it's safely backed up, delete it
2239 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2241 # If using cascading deletes, we can skip some explicit deletes
2242 if ( !$dbw->cascadingDeletes() ) {
2244 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2246 if ($wgUseTrackbacks)
2247 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2249 # Delete outgoing links
2250 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2251 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2252 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2253 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2254 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2255 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2256 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2259 # If using cleanup triggers, we can skip some manual deletes
2260 if ( !$dbw->cleanupTriggers() ) {
2262 # Clean up recentchanges entries...
2263 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2267 Article
::onArticleDelete( $this->mTitle
);
2270 $log = new LogPage( 'delete' );
2271 $log->addEntry( 'delete', $this->mTitle
, $reason );
2273 # Clear the cached article id so the interface doesn't act like we exist
2274 $this->mTitle
->resetArticleID( 0 );
2275 $this->mTitle
->mArticleID
= 0;
2280 * Roll back the most recent consecutive set of edits to a page
2281 * from the same user; fails if there are no eligible edits to
2282 * roll back to, e.g. user is the sole contributor. This function
2283 * performs permissions checks on $wgUser, then calls commitRollback()
2284 * to do the dirty work
2286 * @param string $fromP - Name of the user whose edits to rollback.
2287 * @param string $summary - Custom summary. Set to default summary if empty.
2288 * @param string $token - Rollback token.
2289 * @param bool $bot - If true, mark all reverted edits as bot.
2291 * @param array $resultDetails contains result-specific array of additional values
2292 * 'alreadyrolled' : 'current' (rev)
2293 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2295 * @return array of errors, each error formatted as
2296 * array(messagekey, param1, param2, ...).
2297 * On success, the array is empty. This array can also be passed to
2298 * OutputPage::showPermissionsErrorPage().
2300 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2302 $resultDetails = null;
2305 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2306 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2307 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2308 $errors[] = array( 'sessionfailure' );
2310 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2311 $errors[] = array( 'actionthrottledtext' );
2313 # If there were errors, bail out now
2317 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2321 * Backend implementation of doRollback(), please refer there for parameter
2322 * and return value documentation
2324 * NOTE: This function does NOT check ANY permissions, it just commits the
2325 * rollback to the DB Therefore, you should only call this function direct-
2326 * ly if you want to use custom permissions checks. If you don't, use
2327 * doRollback() instead.
2329 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2330 global $wgUseRCPatrol, $wgUser;
2331 $dbw = wfGetDB( DB_MASTER
);
2333 if( wfReadOnly() ) {
2334 return array( array( 'readonlytext' ) );
2337 # Get the last editor
2338 $current = Revision
::newFromTitle( $this->mTitle
);
2339 if( is_null( $current ) ) {
2340 # Something wrong... no page?
2341 return array(array('notanarticle'));
2344 $from = str_replace( '_', ' ', $fromP );
2345 if( $from != $current->getUserText() ) {
2346 $resultDetails = array( 'current' => $current );
2347 return array(array('alreadyrolled',
2348 htmlspecialchars($this->mTitle
->getPrefixedText()),
2349 htmlspecialchars($fromP),
2350 htmlspecialchars($current->getUserText())
2354 # Get the last edit not by this guy
2355 $user = intval( $current->getUser() );
2356 $user_text = $dbw->addQuotes( $current->getUserText() );
2357 $s = $dbw->selectRow( 'revision',
2358 array( 'rev_id', 'rev_timestamp' ),
2359 array( 'rev_page' => $current->getPage(),
2360 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2362 array( 'USE INDEX' => 'page_timestamp',
2363 'ORDER BY' => 'rev_timestamp DESC' )
2365 if( $s === false ) {
2366 # No one else ever edited this page
2367 return array(array('cantrollback'));
2371 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2372 # Mark all reverted edits as bot
2375 if ( $wgUseRCPatrol ) {
2376 # Mark all reverted edits as patrolled
2377 $set['rc_patrolled'] = 1;
2381 $dbw->update( 'recentchanges', $set,
2383 'rc_cur_id' => $current->getPage(),
2384 'rc_user_text' => $current->getUserText(),
2385 "rc_timestamp > '{$s->rev_timestamp}'",
2390 # Generate the edit summary if necessary
2391 $target = Revision
::newFromId( $s->rev_id
);
2392 if( empty( $summary ) )
2395 $summary = wfMsgForContent( 'revertpage',
2396 $target->getUserText(), $from,
2397 $s->rev_id
, $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2398 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2403 $flags = EDIT_UPDATE
;
2405 if ($wgUser->isAllowed('minoredit'))
2406 $flags |
= EDIT_MINOR
;
2408 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2409 $flags |
= EDIT_FORCE_BOT
;
2410 $this->doEdit( $target->getText(), $summary, $flags );
2412 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2414 $resultDetails = array(
2415 'summary' => $summary,
2416 'current' => $current,
2417 'target' => $target,
2423 * User interface for rollback operations
2425 function rollback() {
2426 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2429 $result = $this->doRollback(
2430 $wgRequest->getVal( 'from' ),
2431 $wgRequest->getText( 'summary' ),
2432 $wgRequest->getVal( 'token' ),
2433 $wgRequest->getBool( 'bot' ),
2437 if( in_array( array( 'blocked' ), $result ) ) {
2438 $wgOut->blockedPage();
2441 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2442 $wgOut->rateLimited();
2445 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2446 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2447 $errArray = $result[0];
2448 $errMsg = array_shift( $errArray );
2449 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2450 if( isset( $details['current'] ) ){
2451 $current = $details['current'];
2452 if( $current->getComment() != '' ) {
2453 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2458 # Display permissions errors before read-only message -- there's no
2459 # point in misleading the user into thinking the inability to rollback
2460 # is only temporary.
2461 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2462 # array_diff is completely broken for arrays of arrays, sigh. Re-
2463 # move any 'readonlytext' error manually.
2465 foreach( $result as $error ) {
2466 if( $error != array( 'readonlytext' ) ) {
2470 $wgOut->showPermissionsErrorPage( $out );
2473 if( $result == array( array('readonlytext') ) ) {
2474 $wgOut->readOnlyPage();
2478 $current = $details['current'];
2479 $target = $details['target'];
2480 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2481 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2482 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2483 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2484 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2485 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2486 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2487 $wgOut->returnToMain( false, $this->mTitle
);
2492 * Do standard deferred updates after page view
2495 function viewUpdates() {
2496 global $wgDeferredUpdateList;
2498 if ( 0 != $this->getID() ) {
2499 global $wgDisableCounters;
2500 if( !$wgDisableCounters ) {
2501 Article
::incViewCount( $this->getID() );
2502 $u = new SiteStatsUpdate( 1, 0, 0 );
2503 array_push( $wgDeferredUpdateList, $u );
2507 # Update newtalk / watchlist notification status
2509 $wgUser->clearNotification( $this->mTitle
);
2513 * Prepare text which is about to be saved.
2514 * Returns a stdclass with source, pst and output members
2516 function prepareTextForEdit( $text, $revid=null ) {
2517 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2519 return $this->mPreparedEdit
;
2522 $edit = (object)array();
2523 $edit->revid
= $revid;
2524 $edit->newText
= $text;
2525 $edit->pst
= $this->preSaveTransform( $text );
2526 $options = new ParserOptions
;
2527 $options->setTidy( true );
2528 $options->enableLimitReport();
2529 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2530 $edit->oldText
= $this->getContent();
2531 $this->mPreparedEdit
= $edit;
2536 * Do standard deferred updates after page edit.
2537 * Update links tables, site stats, search index and message cache.
2538 * Every 100th edit, prune the recent changes table.
2541 * @param $text New text of the article
2542 * @param $summary Edit summary
2543 * @param $minoredit Minor edit
2544 * @param $timestamp_of_pagechange Timestamp associated with the page change
2545 * @param $newid rev_id value of the new revision
2546 * @param $changed Whether or not the content actually changed
2548 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2549 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2551 wfProfileIn( __METHOD__
);
2554 # Be careful not to double-PST: $text is usually already PST-ed once
2555 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2556 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2557 $editInfo = $this->prepareTextForEdit( $text, $newid );
2559 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2560 $editInfo = $this->mPreparedEdit
;
2563 # Save it to the parser cache
2564 if ( $wgEnableParserCache ) {
2565 $parserCache =& ParserCache
::singleton();
2566 $parserCache->save( $editInfo->output
, $this, $wgUser );
2569 # Update the links tables
2570 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2573 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2574 if ( 0 == mt_rand( 0, 99 ) ) {
2575 // Flush old entries from the `recentchanges` table; we do this on
2576 // random requests so as to avoid an increase in writes for no good reason
2578 $dbw = wfGetDB( DB_MASTER
);
2579 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2580 $recentchanges = $dbw->tableName( 'recentchanges' );
2581 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2582 $dbw->query( $sql );
2586 $id = $this->getID();
2587 $title = $this->mTitle
->getPrefixedDBkey();
2588 $shortTitle = $this->mTitle
->getDBkey();
2591 wfProfileOut( __METHOD__
);
2595 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2596 array_push( $wgDeferredUpdateList, $u );
2597 $u = new SearchUpdate( $id, $title, $text );
2598 array_push( $wgDeferredUpdateList, $u );
2600 # If this is another user's talk page, update newtalk
2601 # Don't do this if $changed = false otherwise some idiot can null-edit a
2602 # load of user talk pages and piss people off, nor if it's a minor edit
2603 # by a properly-flagged bot.
2604 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2605 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2606 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2607 $other = User
::newFromName( $shortTitle );
2608 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2609 // An anonymous user
2610 $other = new User();
2611 $other->setName( $shortTitle );
2614 $other->setNewtalk( true );
2619 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2620 $wgMessageCache->replace( $shortTitle, $text );
2623 wfProfileOut( __METHOD__
);
2627 * Perform article updates on a special page creation.
2629 * @param Revision $rev
2631 * @todo This is a shitty interface function. Kill it and replace the
2632 * other shitty functions like editUpdates and such so it's not needed
2635 function createUpdates( $rev ) {
2636 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2637 $this->mTotalAdjustment
= 1;
2638 $this->editUpdates( $rev->getText(), $rev->getComment(),
2639 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2643 * Generate the navigation links when browsing through an article revisions
2644 * It shows the information as:
2645 * Revision as of \<date\>; view current revision
2646 * \<- Previous version | Next Version -\>
2649 * @param string $oldid Revision ID of this article revision
2651 function setOldSubtitle( $oldid=0 ) {
2652 global $wgLang, $wgOut, $wgUser;
2654 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2658 $revision = Revision
::newFromId( $oldid );
2660 $current = ( $oldid == $this->mLatest
);
2661 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2662 $sk = $wgUser->getSkin();
2664 ?
wfMsg( 'currentrevisionlink' )
2665 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2668 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2669 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2671 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2672 : wfMsg( 'previousrevision' );
2674 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2676 $nextlink = $current
2677 ?
wfMsg( 'nextrevision' )
2678 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2679 $nextdiff = $current
2681 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2683 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2684 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2686 $m = wfMsg( 'revision-info-current' );
2687 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2688 ?
'revision-info-current'
2691 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2692 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2693 $wgOut->setSubtitle( $r );
2697 * This function is called right before saving the wikitext,
2698 * so we can do things like signatures and links-in-context.
2700 * @param string $text
2702 function preSaveTransform( $text ) {
2703 global $wgParser, $wgUser;
2704 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2707 /* Caching functions */
2710 * checkLastModified returns true if it has taken care of all
2711 * output to the client that is necessary for this request.
2712 * (that is, it has sent a cached version of the page)
2714 function tryFileCache() {
2715 static $called = false;
2717 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2721 if($this->isFileCacheable()) {
2722 $touched = $this->mTouched
;
2723 $cache = new HTMLFileCache( $this->mTitle
);
2724 if($cache->isFileCacheGood( $touched )) {
2725 wfDebug( "Article::tryFileCache(): about to load file\n" );
2726 $cache->loadFromFileCache();
2729 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2730 ob_start( array(&$cache, 'saveToFileCache' ) );
2733 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2738 * Check if the page can be cached
2741 function isFileCacheable() {
2742 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2743 $action = $wgRequest->getVal( 'action' );
2744 $oldid = $wgRequest->getVal( 'oldid' );
2745 $diff = $wgRequest->getVal( 'diff' );
2746 $redirect = $wgRequest->getVal( 'redirect' );
2747 $printable = $wgRequest->getVal( 'printable' );
2748 $page = $wgRequest->getVal( 'page' );
2750 //check for non-standard user language; this covers uselang,
2751 //and extensions for auto-detecting user language.
2752 $ulang = $wgLang->getCode();
2753 $clang = $wgContLang->getCode();
2755 $cacheable = $wgUseFileCache
2756 && (!$wgShowIPinHeader)
2757 && ($this->getID() != 0)
2758 && ($wgUser->isAnon())
2759 && (!$wgUser->getNewtalk())
2760 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2761 && (empty( $action ) ||
$action == 'view')
2764 && (!isset($redirect))
2765 && (!isset($printable))
2767 && (!$this->mRedirectedFrom
)
2768 && ($ulang === $clang);
2771 //extension may have reason to disable file caching on some pages.
2772 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2779 * Loads page_touched and returns a value indicating if it should be used
2782 function checkTouched() {
2783 if( !$this->mDataLoaded
) {
2784 $this->loadPageData();
2786 return !$this->mIsRedirect
;
2790 * Get the page_touched field
2792 function getTouched() {
2793 # Ensure that page data has been loaded
2794 if( !$this->mDataLoaded
) {
2795 $this->loadPageData();
2797 return $this->mTouched
;
2801 * Get the page_latest field
2803 function getLatest() {
2804 if ( !$this->mDataLoaded
) {
2805 $this->loadPageData();
2807 return $this->mLatest
;
2811 * Edit an article without doing all that other stuff
2812 * The article must already exist; link tables etc
2813 * are not updated, caches are not flushed.
2815 * @param string $text text submitted
2816 * @param string $comment comment submitted
2817 * @param bool $minor whereas it's a minor modification
2819 function quickEdit( $text, $comment = '', $minor = 0 ) {
2820 wfProfileIn( __METHOD__
);
2822 $dbw = wfGetDB( DB_MASTER
);
2824 $revision = new Revision( array(
2825 'page' => $this->getId(),
2827 'comment' => $comment,
2828 'minor_edit' => $minor ?
1 : 0,
2830 $revision->insertOn( $dbw );
2831 $this->updateRevisionOn( $dbw, $revision );
2834 wfProfileOut( __METHOD__
);
2838 * Used to increment the view counter
2841 * @param integer $id article id
2843 function incViewCount( $id ) {
2844 $id = intval( $id );
2845 global $wgHitcounterUpdateFreq, $wgDBtype;
2847 $dbw = wfGetDB( DB_MASTER
);
2848 $pageTable = $dbw->tableName( 'page' );
2849 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2850 $acchitsTable = $dbw->tableName( 'acchits' );
2852 if( $wgHitcounterUpdateFreq <= 1 ) {
2853 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2857 # Not important enough to warrant an error page in case of failure
2858 $oldignore = $dbw->ignoreErrors( true );
2860 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2862 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2863 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2864 # Most of the time (or on SQL errors), skip row count check
2865 $dbw->ignoreErrors( $oldignore );
2869 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2870 $row = $dbw->fetchObject( $res );
2871 $rown = intval( $row->n
);
2872 if( $rown >= $wgHitcounterUpdateFreq ){
2873 wfProfileIn( 'Article::incViewCount-collect' );
2874 $old_user_abort = ignore_user_abort( true );
2876 if ($wgDBtype == 'mysql')
2877 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2878 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2879 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2880 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2882 $dbw->query("DELETE FROM $hitcounterTable");
2883 if ($wgDBtype == 'mysql') {
2884 $dbw->query('UNLOCK TABLES');
2885 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2886 'WHERE page_id = hc_id');
2889 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2890 "FROM $acchitsTable WHERE page_id = hc_id");
2892 $dbw->query("DROP TABLE $acchitsTable");
2894 ignore_user_abort( $old_user_abort );
2895 wfProfileOut( 'Article::incViewCount-collect' );
2897 $dbw->ignoreErrors( $oldignore );
2901 * The onArticle*() functions are supposed to be a kind of hooks
2902 * which should be called whenever any of the specified actions
2905 * This is a good place to put code to clear caches, for instance.
2907 * This is called on page move and undelete, as well as edit
2909 * @param $title_obj a title object
2912 static function onArticleCreate($title) {
2913 # The talk page isn't in the regular link tables, so we need to update manually:
2914 if ( $title->isTalkPage() ) {
2915 $other = $title->getSubjectPage();
2917 $other = $title->getTalkPage();
2919 $other->invalidateCache();
2920 $other->purgeSquid();
2922 $title->touchLinks();
2923 $title->purgeSquid();
2924 $title->deleteTitleProtection();
2927 static function onArticleDelete( $title ) {
2928 global $wgUseFileCache, $wgMessageCache;
2930 $title->touchLinks();
2931 $title->purgeSquid();
2934 if ( $wgUseFileCache ) {
2935 $cm = new HTMLFileCache( $title );
2936 @unlink
( $cm->fileCacheName() );
2939 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2940 $wgMessageCache->replace( $title->getDBkey(), false );
2942 if( $title->getNamespace() == NS_IMAGE
) {
2943 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2944 $update->doUpdate();
2949 * Purge caches on page update etc
2951 static function onArticleEdit( $title ) {
2952 global $wgDeferredUpdateList, $wgUseFileCache;
2954 // Invalidate caches of articles which include this page
2955 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
2957 // Invalidate the caches of all pages which redirect here
2958 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
2960 # Purge squid for this page only
2961 $title->purgeSquid();
2964 if ( $wgUseFileCache ) {
2965 $cm = new HTMLFileCache( $title );
2966 @unlink
( $cm->fileCacheName() );
2973 * Overriden by ImagePage class, only present here to avoid a fatal error
2974 * Called for ?action=revert
2976 public function revert(){
2978 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2982 * Info about this page
2983 * Called for ?action=info when $wgAllowPageInfo is on.
2988 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2990 if ( !$wgAllowPageInfo ) {
2991 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2995 $page = $this->mTitle
->getSubjectPage();
2997 $wgOut->setPagetitle( $page->getPrefixedText() );
2998 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2999 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3001 if( !$this->mTitle
->exists() ) {
3002 $wgOut->addHtml( '<div class="noarticletext">' );
3003 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3004 // This doesn't quite make sense; the user is asking for
3005 // information about the _page_, not the message... -- RC
3006 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3008 $msg = $wgUser->isLoggedIn()
3010 : 'noarticletextanon';
3011 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3013 $wgOut->addHtml( '</div>' );
3015 $dbr = wfGetDB( DB_SLAVE
);
3017 'wl_title' => $page->getDBkey(),
3018 'wl_namespace' => $page->getNamespace() );
3019 $numwatchers = $dbr->selectField(
3024 $this->getSelectOptions() );
3026 $pageInfo = $this->pageCountInfo( $page );
3027 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3029 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3030 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3032 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3034 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3036 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3038 $wgOut->addHTML( '</ul>' );
3044 * Return the total number of edits and number of unique editors
3045 * on a given page. If page does not exist, returns false.
3047 * @param Title $title
3051 function pageCountInfo( $title ) {
3052 $id = $title->getArticleId();
3057 $dbr = wfGetDB( DB_SLAVE
);
3059 $rev_clause = array( 'rev_page' => $id );
3061 $edits = $dbr->selectField(
3066 $this->getSelectOptions() );
3068 $authors = $dbr->selectField(
3070 'COUNT(DISTINCT rev_user_text)',
3073 $this->getSelectOptions() );
3075 return array( 'edits' => $edits, 'authors' => $authors );
3079 * Return a list of templates used by this article.
3080 * Uses the templatelinks table
3082 * @return array Array of Title objects
3084 function getUsedTemplates() {
3086 $id = $this->mTitle
->getArticleID();
3091 $dbr = wfGetDB( DB_SLAVE
);
3092 $res = $dbr->select( array( 'templatelinks' ),
3093 array( 'tl_namespace', 'tl_title' ),
3094 array( 'tl_from' => $id ),
3095 'Article:getUsedTemplates' );
3096 if ( false !== $res ) {
3097 if ( $dbr->numRows( $res ) ) {
3098 while ( $row = $dbr->fetchObject( $res ) ) {
3099 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3103 $dbr->freeResult( $res );
3108 * Returns a list of hidden categories this page is a member of.
3109 * Uses the page_props and categorylinks tables.
3111 * @return array Array of Title objects
3113 function getHiddenCategories() {
3115 $id = $this->mTitle
->getArticleID();
3120 $dbr = wfGetDB( DB_SLAVE
);
3121 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3123 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3124 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3125 'Article:getHiddenCategories' );
3126 if ( false !== $res ) {
3127 if ( $dbr->numRows( $res ) ) {
3128 while ( $row = $dbr->fetchObject( $res ) ) {
3129 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3133 $dbr->freeResult( $res );
3138 * Return an auto-generated summary if the text provided is a redirect.
3140 * @param string $text The wikitext to check
3141 * @return string '' or an appropriate summary
3143 public static function getRedirectAutosummary( $text ) {
3144 $rt = Title
::newFromRedirect( $text );
3145 if( is_object( $rt ) )
3146 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3152 * Return an auto-generated summary if the new text is much shorter than
3155 * @param string $oldtext The previous text of the page
3156 * @param string $text The submitted text of the page
3157 * @return string An appropriate autosummary, or an empty string.
3159 public static function getBlankingAutosummary( $oldtext, $text ) {
3160 if ($oldtext!='' && $text=='') {
3161 return wfMsgForContent('autosumm-blank');
3162 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3163 #Removing more than 90% of the article
3165 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3166 return wfMsgForContent('autosumm-replace', $truncatedtext);
3173 * Return an applicable autosummary if one exists for the given edit.
3174 * @param string $oldtext The previous text of the page.
3175 * @param string $newtext The submitted text of the page.
3176 * @param bitmask $flags A bitmask of flags submitted for the edit.
3177 * @return string An appropriate autosummary, or an empty string.
3179 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3181 # This code is UGLY UGLY UGLY.
3182 # Somebody PLEASE come up with a more elegant way to do it.
3184 #Redirect autosummaries
3185 $summary = self
::getRedirectAutosummary( $newtext );
3190 #Blanking autosummaries
3191 if (!($flags & EDIT_NEW
))
3192 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3197 #New page autosummaries
3198 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3199 #If they're making a new article, give its text, truncated, in the summary.
3201 $truncatedtext = $wgContLang->truncate(
3202 str_replace("\n", ' ', $newtext),
3203 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3205 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3215 * Add the primary page-view wikitext to the output buffer
3216 * Saves the text into the parser cache if possible.
3217 * Updates templatelinks if it is out of date.
3219 * @param string $text
3220 * @param bool $cache
3222 public function outputWikiText( $text, $cache = true ) {
3223 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3225 $popts = $wgOut->parserOptions();
3226 $popts->setTidy(true);
3227 $popts->enableLimitReport();
3228 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3229 $popts, true, true, $this->getRevIdFetched() );
3230 $popts->setTidy(false);
3231 $popts->enableLimitReport( false );
3232 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3233 $parserCache =& ParserCache
::singleton();
3234 $parserCache->save( $parserOutput, $this, $wgUser );
3237 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3238 // templatelinks table may have become out of sync,
3239 // especially if using variable-based transclusions.
3240 // For paranoia, check if things have changed and if
3241 // so apply updates to the database. This will ensure
3242 // that cascaded protections apply as soon as the changes
3245 # Get templates from templatelinks
3246 $id = $this->mTitle
->getArticleID();
3248 $tlTemplates = array();
3250 $dbr = wfGetDB( DB_SLAVE
);
3251 $res = $dbr->select( array( 'templatelinks' ),
3252 array( 'tl_namespace', 'tl_title' ),
3253 array( 'tl_from' => $id ),
3254 'Article:getUsedTemplates' );
3258 if ( false !== $res ) {
3259 if ( $dbr->numRows( $res ) ) {
3260 while ( $row = $dbr->fetchObject( $res ) ) {
3261 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3266 # Get templates from parser output.
3267 $poTemplates_allns = $parserOutput->getTemplates();
3269 $poTemplates = array ();
3270 foreach ( $poTemplates_allns as $ns_templates ) {
3271 $poTemplates = array_merge( $poTemplates, $ns_templates );
3275 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3277 if ( count( $templates_diff ) > 0 ) {
3278 # Whee, link updates time.
3279 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3281 $dbw = wfGetDb( DB_MASTER
);
3290 $wgOut->addParserOutput( $parserOutput );