8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
21 var $mContentLoaded; //!<
24 var $mGoodAdjustment; //!<
28 var $mRedirectedFrom; //!<
29 var $mRedirectUrl; //!<
30 var $mRevIdFetched; //!<
34 var $mTotalAdjustment; //!<
38 var $mRedirectTarget; //!<
43 * Constructor and clear the article
44 * @param $title Reference to a Title object.
45 * @param $oldId Integer revision ID, null to fetch from request, zero for current
47 function __construct( Title
$title, $oldId = null ) {
48 $this->mTitle
=& $title;
49 $this->mOldId
= $oldId;
54 * Tell the page view functions that this view was redirected
55 * from another page on the wiki.
56 * @param $from Title object.
58 function setRedirectedFrom( $from ) {
59 $this->mRedirectedFrom
= $from;
63 * If this page is a redirect, get its target
65 * The target will be fetched from the redirect table if possible.
66 * If this page doesn't have an entry there, call insertRedirect()
67 * @return mixed Title object, or null if this page is not a redirect
69 public function getRedirectTarget() {
70 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
72 if(!is_null($this->mRedirectTarget
))
73 return $this->mRedirectTarget
;
75 # Query the redirect table
76 $dbr = wfGetDB(DB_SLAVE
);
77 $res = $dbr->select('redirect',
78 array('rd_namespace', 'rd_title'),
79 array('rd_from' => $this->getID()),
82 $row = $dbr->fetchObject($res);
84 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
86 # This page doesn't have an entry in the redirect table
87 return $this->mRedirectTarget
= $this->insertRedirect();
91 * Insert an entry for this page into the redirect table.
93 * Don't call this function directly unless you know what you're doing.
94 * @return Title object
96 public function insertRedirect() {
97 $retval = Title
::newFromRedirect($this->getContent());
100 $dbw = wfGetDB(DB_MASTER
);
101 $dbw->replace('redirect', array('rd_from'), array(
102 'rd_from' => $this->getID(),
103 'rd_namespace' => $retval->getNamespace(),
104 'rd_title' => $retval->getDBKey()
110 * Get the Title object this page redirects to
112 * @return mixed false, Title of in-wiki target, or string with URL
114 function followRedirect() {
115 $text = $this->getContent();
116 $rt = Title
::newFromRedirect( $text );
118 # process if title object is valid and not special:userlogout
120 if( $rt->getInterwiki() != '' ) {
121 if( $rt->isLocal() ) {
122 // Offsite wikis need an HTTP redirect.
124 // This can be hard to reverse and may produce loops,
125 // so they may be disabled in the site configuration.
127 $source = $this->mTitle
->getFullURL( 'redirect=no' );
128 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
131 if( $rt->getNamespace() == NS_SPECIAL
) {
132 // Gotta handle redirects to special pages differently:
133 // Fill the HTTP response "Location" header and ignore
134 // the rest of the page we're on.
136 // This can be hard to reverse, so they may be disabled.
138 if( $rt->isSpecial( 'Userlogout' ) ) {
141 return $rt->getFullURL();
148 // No or invalid redirect
153 * get the title object of the article
155 function getTitle() {
156 return $this->mTitle
;
164 $this->mDataLoaded
= false;
165 $this->mContentLoaded
= false;
167 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
168 $this->mRedirectedFrom
= null; # Title object if set
169 $this->mRedirectTarget
= null; # Title object if set
171 $this->mTimestamp
= $this->mComment
= '';
172 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
173 $this->mTouched
= '19700101000000';
174 $this->mForUpdate
= false;
175 $this->mIsRedirect
= false;
176 $this->mRevIdFetched
= 0;
177 $this->mRedirectUrl
= false;
178 $this->mLatest
= false;
179 $this->mPreparedEdit
= false;
183 * Note that getContent/loadContent do not follow redirects anymore.
184 * If you need to fetch redirectable content easily, try
185 * the shortcut in Article::followContent()
187 * @todo There are still side-effects in this!
188 * In general, you should use the Revision class, not Article,
189 * to fetch text for purposes other than page views.
191 * @return Return the text of this revision
193 function getContent() {
194 global $wgUser, $wgOut, $wgMessageCache;
196 wfProfileIn( __METHOD__
);
198 if ( 0 == $this->getID() ) {
199 wfProfileOut( __METHOD__
);
200 $wgOut->setRobotpolicy( 'noindex,nofollow' );
202 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
203 $wgMessageCache->loadAllMessages();
204 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
206 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
209 return "<div class='noarticletext'>\n$ret\n</div>";
211 $this->loadContent();
212 wfProfileOut( __METHOD__
);
213 return $this->mContent
;
218 * This function returns the text of a section, specified by a number ($section).
219 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
220 * the first section before any such heading (section 0).
222 * If a section contains subsections, these are also returned.
224 * @param $text String: text to look in
225 * @param $section Integer: section number
226 * @return string text of the requested section
229 function getSection($text,$section) {
231 return $wgParser->getSection( $text, $section );
235 * @return int The oldid of the article that is to be shown, 0 for the
238 function getOldID() {
239 if ( is_null( $this->mOldId
) ) {
240 $this->mOldId
= $this->getOldIDFromRequest();
242 return $this->mOldId
;
246 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
248 * @return int The old id for the request
250 function getOldIDFromRequest() {
252 $this->mRedirectUrl
= false;
253 $oldid = $wgRequest->getVal( 'oldid' );
254 if ( isset( $oldid ) ) {
255 $oldid = intval( $oldid );
256 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
257 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
261 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
263 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
264 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
282 * Load the revision (including text) into this object
284 function loadContent() {
285 if ( $this->mContentLoaded
) return;
288 $oldid = $this->getOldID();
290 # Pre-fill content with error message so that if something
291 # fails we'll have something telling us what we intended.
292 $this->mOldId
= $oldid;
293 $this->fetchContent( $oldid );
298 * Fetch a page record with the given conditions
299 * @param Database $dbr
300 * @param array $conditions
303 function pageData( $dbr, $conditions ) {
317 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
318 $row = $dbr->selectRow(
324 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
329 * @param Database $dbr
330 * @param Title $title
332 function pageDataFromTitle( $dbr, $title ) {
333 return $this->pageData( $dbr, array(
334 'page_namespace' => $title->getNamespace(),
335 'page_title' => $title->getDBkey() ) );
339 * @param Database $dbr
342 function pageDataFromId( $dbr, $id ) {
343 return $this->pageData( $dbr, array( 'page_id' => $id ) );
347 * Set the general counter, title etc data loaded from
350 * @param object $data
353 function loadPageData( $data = 'fromdb' ) {
354 if ( $data === 'fromdb' ) {
355 $dbr = $this->getDB();
356 $data = $this->pageDataFromId( $dbr, $this->getId() );
359 $lc = LinkCache
::singleton();
361 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
363 $this->mTitle
->mArticleID
= $data->page_id
;
365 # Old-fashioned restrictions.
366 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
368 $this->mCounter
= $data->page_counter
;
369 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
370 $this->mIsRedirect
= $data->page_is_redirect
;
371 $this->mLatest
= $data->page_latest
;
373 if ( is_object( $this->mTitle
) ) {
374 $lc->addBadLinkObj( $this->mTitle
);
376 $this->mTitle
->mArticleID
= 0;
379 $this->mDataLoaded
= true;
383 * Get text of an article from database
384 * Does *NOT* follow redirects.
385 * @param int $oldid 0 for whatever the latest revision is
388 function fetchContent( $oldid = 0 ) {
389 if ( $this->mContentLoaded
) {
390 return $this->mContent
;
393 $dbr = $this->getDB();
395 # Pre-fill content with error message so that if something
396 # fails we'll have something telling us what we intended.
397 $t = $this->mTitle
->getPrefixedText();
399 $t .= ' ' . wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
401 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
404 $revision = Revision
::newFromId( $oldid );
405 if( is_null( $revision ) ) {
406 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
409 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
411 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
414 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
415 $this->loadPageData( $data );
417 if( !$this->mDataLoaded
) {
418 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
420 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
423 $this->loadPageData( $data );
425 $revision = Revision
::newFromId( $this->mLatest
);
426 if( is_null( $revision ) ) {
427 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
432 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
433 // We should instead work with the Revision object when we need it...
434 $this->mContent
= $revision->revText(); // Loads if user is allowed
436 $this->mUser
= $revision->getUser();
437 $this->mUserText
= $revision->getUserText();
438 $this->mComment
= $revision->getComment();
439 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
441 $this->mRevIdFetched
= $revision->getId();
442 $this->mContentLoaded
= true;
443 $this->mRevision
=& $revision;
445 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
447 return $this->mContent
;
451 * Read/write accessor to select FOR UPDATE
453 * @param $x Mixed: FIXME
455 function forUpdate( $x = NULL ) {
456 return wfSetVar( $this->mForUpdate
, $x );
460 * Get the database which should be used for reads
465 return wfGetDB( DB_MASTER
);
469 * Get options for all SELECT statements
471 * @param $options Array: an optional options array which'll be appended to
473 * @return Array: options
475 function getSelectOptions( $options = '' ) {
476 if ( $this->mForUpdate
) {
477 if ( is_array( $options ) ) {
478 $options[] = 'FOR UPDATE';
480 $options = 'FOR UPDATE';
487 * @return int Page ID
490 if( $this->mTitle
) {
491 return $this->mTitle
->getArticleID();
498 * @return bool Whether or not the page exists in the database
501 return $this->getId() != 0;
505 * @return int The view count for the page
507 function getCount() {
508 if ( -1 == $this->mCounter
) {
509 $id = $this->getID();
513 $dbr = wfGetDB( DB_SLAVE
);
514 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
515 'Article::getCount', $this->getSelectOptions() );
518 return $this->mCounter
;
522 * Determine whether a page would be suitable for being counted as an
523 * article in the site_stats table based on the title & its content
525 * @param $text String: text to analyze
528 function isCountable( $text ) {
529 global $wgUseCommaCount;
531 $token = $wgUseCommaCount ?
',' : '[[';
533 $this->mTitle
->isContentPage()
534 && !$this->isRedirect( $text )
535 && in_string( $token, $text );
539 * Tests if the article text represents a redirect
541 * @param $text String: FIXME
544 function isRedirect( $text = false ) {
545 if ( $text === false ) {
546 if ( $this->mDataLoaded
)
547 return $this->mIsRedirect
;
549 // Apparently loadPageData was never called
550 $this->loadContent();
551 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
553 $titleObj = Title
::newFromRedirect( $text );
555 return $titleObj !== NULL;
559 * Returns true if the currently-referenced revision is the current edit
560 * to this page (and it exists).
563 function isCurrent() {
564 # If no oldid, this is the current version.
565 if ($this->getOldID() == 0)
568 return $this->exists() &&
569 isset( $this->mRevision
) &&
570 $this->mRevision
->isCurrent();
574 * Loads everything except the text
575 * This isn't necessary for all uses, so it's only done if needed.
578 function loadLastEdit() {
579 if ( -1 != $this->mUser
)
582 # New or non-existent articles have no user information
583 $id = $this->getID();
584 if ( 0 == $id ) return;
586 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
587 if( !is_null( $this->mLastRevision
) ) {
588 $this->mUser
= $this->mLastRevision
->getUser();
589 $this->mUserText
= $this->mLastRevision
->getUserText();
590 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
591 $this->mComment
= $this->mLastRevision
->getComment();
592 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
593 $this->mRevIdFetched
= $this->mLastRevision
->getId();
597 function getTimestamp() {
598 // Check if the field has been filled by ParserCache::get()
599 if ( !$this->mTimestamp
) {
600 $this->loadLastEdit();
602 return wfTimestamp(TS_MW
, $this->mTimestamp
);
606 $this->loadLastEdit();
610 function getUserText() {
611 $this->loadLastEdit();
612 return $this->mUserText
;
615 function getComment() {
616 $this->loadLastEdit();
617 return $this->mComment
;
620 function getMinorEdit() {
621 $this->loadLastEdit();
622 return $this->mMinorEdit
;
625 function getRevIdFetched() {
626 $this->loadLastEdit();
627 return $this->mRevIdFetched
;
631 * @todo Document, fixme $offset never used.
632 * @param $limit Integer: default 0.
633 * @param $offset Integer: default 0.
635 function getContributors($limit = 0, $offset = 0) {
636 # XXX: this is expensive; cache this info somewhere.
639 $dbr = wfGetDB( DB_SLAVE
);
640 $revTable = $dbr->tableName( 'revision' );
641 $userTable = $dbr->tableName( 'user' );
642 $user = $this->getUser();
643 $pageId = $this->getId();
645 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
646 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
647 WHERE rev_page = $pageId
648 AND rev_user != $user
649 GROUP BY rev_user, rev_user_text, user_real_name
650 ORDER BY timestamp DESC";
652 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
653 $sql .= ' '. $this->getSelectOptions();
655 $res = $dbr->query($sql, __METHOD__
);
657 while ( $line = $dbr->fetchObject( $res ) ) {
658 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
661 $dbr->freeResult($res);
666 * This is the default action of the script: just view the page of
670 global $wgUser, $wgOut, $wgRequest, $wgContLang;
671 global $wgEnableParserCache, $wgStylePath, $wgParser;
672 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
673 global $wgDefaultRobotPolicy;
674 $sk = $wgUser->getSkin();
676 wfProfileIn( __METHOD__
);
678 $parserCache = ParserCache
::singleton();
679 $ns = $this->mTitle
->getNamespace(); # shortcut
681 # Get variables from query string
682 $oldid = $this->getOldID();
684 # getOldID may want us to redirect somewhere else
685 if ( $this->mRedirectUrl
) {
686 $wgOut->redirect( $this->mRedirectUrl
);
687 wfProfileOut( __METHOD__
);
691 $diff = $wgRequest->getVal( 'diff' );
692 $rcid = $wgRequest->getVal( 'rcid' );
693 $rdfrom = $wgRequest->getVal( 'rdfrom' );
694 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
695 $purge = $wgRequest->getVal( 'action' ) == 'purge';
697 $wgOut->setArticleFlag( true );
699 # Discourage indexing of printable versions, but encourage following
700 if( $wgOut->isPrintable() ) {
701 $policy = 'noindex,follow';
702 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
703 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
704 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
705 # Honour customised robot policies for this namespace
706 $policy = $wgNamespaceRobotPolicies[$ns];
708 $policy = $wgDefaultRobotPolicy;
710 $wgOut->setRobotPolicy( $policy );
712 # If we got diff and oldid in the query, we want to see a
713 # diff page instead of the article.
715 if ( !is_null( $diff ) ) {
716 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
718 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
719 // DifferenceEngine directly fetched the revision:
720 $this->mRevIdFetched
= $de->mNewid
;
721 $de->showDiffPage( $diffOnly );
723 // Needed to get the page's current revision
724 $this->loadPageData();
725 if( $diff == 0 ||
$diff == $this->mLatest
) {
726 # Run view updates for current revision only
727 $this->viewUpdates();
729 wfProfileOut( __METHOD__
);
733 if ( empty( $oldid ) && $this->checkTouched() ) {
734 $wgOut->setETag($parserCache->getETag($this, $wgUser));
736 if( $wgOut->checkLastModified( $this->mTouched
) ){
737 wfProfileOut( __METHOD__
);
739 } else if ( $this->tryFileCache() ) {
740 # tell wgOut that output is taken care of
742 $this->viewUpdates();
743 wfProfileOut( __METHOD__
);
748 # Should the parser cache be used?
749 $pcache = $wgEnableParserCache
750 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
753 && !$this->mTitle
->isCssOrJsPage()
754 && !$this->mTitle
->isCssJsSubpage();
755 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
756 if ( $wgUser->getOption( 'stubthreshold' ) ) {
757 wfIncrStats( 'pcache_miss_stub' );
760 $wasRedirected = false;
761 if ( isset( $this->mRedirectedFrom
) ) {
762 // This is an internally redirected page view.
763 // We'll need a backlink to the source page for navigation.
764 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
765 $sk = $wgUser->getSkin();
766 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
767 $s = wfMsg( 'redirectedfrom', $redir );
768 $wgOut->setSubtitle( $s );
770 // Set the fragment if one was specified in the redirect
771 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
772 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
773 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
775 $wasRedirected = true;
777 } elseif ( !empty( $rdfrom ) ) {
778 // This is an externally redirected view, from some other wiki.
779 // If it was reported from a trusted site, supply a backlink.
780 global $wgRedirectSources;
781 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
782 $sk = $wgUser->getSkin();
783 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
784 $s = wfMsg( 'redirectedfrom', $redir );
785 $wgOut->setSubtitle( $s );
786 $wasRedirected = true;
791 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
793 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
794 // Ensure that UI elements requiring revision ID have
795 // the correct version information.
796 $wgOut->setRevisionId( $this->mLatest
);
800 if ( !$outputDone ) {
801 $text = $this->getContent();
802 if ( $text === false ) {
803 # Failed to load, replace text with error message
804 $t = $this->mTitle
->getPrefixedText();
806 $t .= ' ' . wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
807 $text = wfMsg( 'missingarticle', $t );
809 $text = wfMsg( 'noarticletext' );
813 # Another whitelist check in case oldid is altering the title
814 if ( !$this->mTitle
->userCanRead() ) {
815 $wgOut->loginToUse();
817 wfProfileOut( __METHOD__
);
821 # We're looking at an old revision
823 if ( !empty( $oldid ) ) {
824 $wgOut->setRobotpolicy( 'noindex,nofollow' );
825 if( is_null( $this->mRevision
) ) {
826 // FIXME: This would be a nice place to load the 'no such page' text.
828 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
829 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
830 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
831 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
832 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
833 wfProfileOut( __METHOD__
);
836 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
837 // and we are allowed to see...
845 $wgOut->setRevisionId( $this->getRevIdFetched() );
847 // Pages containing custom CSS or JavaScript get special treatment
848 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
849 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
851 // Give hooks a chance to customise the output
852 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
853 // Wrap the whole lot in a <pre> and don't parse
855 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
856 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
857 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
858 $wgOut->addHtml( "\n</pre>\n" );
863 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
864 # Don't overwrite the subtitle if this was an old revision
865 $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() );
866 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
867 $wgOut->addParserOutputNoText( $parseout );
868 } else if ( $pcache ) {
869 # Display content and save to parser cache
870 $this->outputWikiText( $text );
872 # Display content, don't attempt to save to parser cache
873 # Don't show section-edit links on old revisions... this way lies madness.
874 if( !$this->isCurrent() ) {
875 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
877 # Display content and don't save to parser cache
878 # With timing hack -- TS 2006-07-26
880 $this->outputWikiText( $text, false );
885 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
886 $this->mTitle
->getPrefixedDBkey()));
889 if( !$this->isCurrent() ) {
890 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
895 /* title may have been set from the cache */
896 $t = $wgOut->getPageTitle();
898 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
901 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
902 if( $ns == NS_USER_TALK
&&
903 IP
::isValid( $this->mTitle
->getText() ) ) {
904 $wgOut->addWikiMsg('anontalkpagetext');
907 # If we have been passed an &rcid= parameter, we want to give the user a
908 # chance to mark this new article as patrolled.
909 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
911 "<div class='patrollink'>" .
912 wfMsgHtml( 'markaspatrolledlink',
913 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
914 "action=markpatrolled&rcid=$rcid" )
921 if ($wgUseTrackbacks)
922 $this->addTrackbacks();
924 $this->viewUpdates();
925 wfProfileOut( __METHOD__
);
928 protected function viewRedirect( $target, $overwriteSubtitle = true, $forceKnown = false ) {
929 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
932 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
933 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
935 if( $overwriteSubtitle ) {
936 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
938 $sk = $wgUser->getSkin();
940 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
942 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
944 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
945 '<span class="redirectText">'.$link.'</span>' );
949 function addTrackbacks() {
950 global $wgOut, $wgUser;
952 $dbr = wfGetDB(DB_SLAVE
);
954 /* FROM */ 'trackbacks',
955 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
956 /* WHERE */ array('tb_page' => $this->getID())
959 if (!$dbr->numrows($tbs))
963 while ($o = $dbr->fetchObject($tbs)) {
965 if ($wgUser->isAllowed( 'trackback' )) {
966 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
967 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
968 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
971 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
978 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
981 function deletetrackback() {
982 global $wgUser, $wgRequest, $wgOut, $wgTitle;
984 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
985 $wgOut->addWikiMsg( 'sessionfailure' );
989 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
991 if (count($permission_errors)>0)
993 $wgOut->showPermissionsErrorPage( $permission_errors );
997 $db = wfGetDB(DB_MASTER
);
998 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
999 $wgTitle->invalidateCache();
1000 $wgOut->addWikiMsg('trackbackdeleteok');
1006 $wgOut->setArticleBodyOnly(true);
1011 * Handle action=purge
1014 global $wgUser, $wgRequest, $wgOut;
1016 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1017 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1021 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1022 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1023 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1024 $msg = str_replace( '$1',
1025 "<form method=\"post\" action=\"$action\">\n" .
1026 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1027 "</form>\n", $msg );
1029 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1030 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1031 $wgOut->addHTML( $msg );
1036 * Perform the actions of a page purging
1038 function doPurge() {
1040 // Invalidate the cache
1041 $this->mTitle
->invalidateCache();
1043 if ( $wgUseSquid ) {
1044 // Commit the transaction before the purge is sent
1045 $dbw = wfGetDB( DB_MASTER
);
1046 $dbw->immediateCommit();
1049 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1050 $update->doUpdate();
1052 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1053 global $wgMessageCache;
1054 if ( $this->getID() == 0 ) {
1057 $text = $this->getContent();
1059 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1065 * Insert a new empty page record for this article.
1066 * This *must* be followed up by creating a revision
1067 * and running $this->updateToLatest( $rev_id );
1068 * or else the record will be left in a funky state.
1069 * Best if all done inside a transaction.
1071 * @param Database $dbw
1072 * @return int The newly created page_id key
1075 function insertOn( $dbw ) {
1076 wfProfileIn( __METHOD__
);
1078 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1079 $dbw->insert( 'page', array(
1080 'page_id' => $page_id,
1081 'page_namespace' => $this->mTitle
->getNamespace(),
1082 'page_title' => $this->mTitle
->getDBkey(),
1083 'page_counter' => 0,
1084 'page_restrictions' => '',
1085 'page_is_redirect' => 0, # Will set this shortly...
1087 'page_random' => wfRandom(),
1088 'page_touched' => $dbw->timestamp(),
1089 'page_latest' => 0, # Fill this in shortly...
1090 'page_len' => 0, # Fill this in shortly...
1092 $newid = $dbw->insertId();
1094 $this->mTitle
->resetArticleId( $newid );
1096 wfProfileOut( __METHOD__
);
1101 * Update the page record to point to a newly saved revision.
1103 * @param Database $dbw
1104 * @param Revision $revision For ID number, and text used to set
1105 length and redirect status fields
1106 * @param int $lastRevision If given, will not overwrite the page field
1107 * when different from the currently set value.
1108 * Giving 0 indicates the new page flag should
1110 * @param bool $lastRevIsRedirect If given, will optimize adding and
1111 * removing rows in redirect table.
1112 * @return bool true on success, false on failure
1115 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1116 wfProfileIn( __METHOD__
);
1118 $text = $revision->getText();
1119 $rt = Title
::newFromRedirect( $text );
1121 $conditions = array( 'page_id' => $this->getId() );
1122 if( !is_null( $lastRevision ) ) {
1123 # An extra check against threads stepping on each other
1124 $conditions['page_latest'] = $lastRevision;
1127 $dbw->update( 'page',
1129 'page_latest' => $revision->getId(),
1130 'page_touched' => $dbw->timestamp(),
1131 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1132 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1133 'page_len' => strlen( $text ),
1138 $result = $dbw->affectedRows() != 0;
1141 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1144 wfProfileOut( __METHOD__
);
1149 * Add row to the redirect table if this is a redirect, remove otherwise.
1151 * @param Database $dbw
1152 * @param $redirectTitle a title object pointing to the redirect target,
1153 * or NULL if this is not a redirect
1154 * @param bool $lastRevIsRedirect If given, will optimize adding and
1155 * removing rows in redirect table.
1156 * @return bool true on success, false on failure
1159 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1161 // Always update redirects (target link might have changed)
1162 // Update/Insert if we don't know if the last revision was a redirect or not
1163 // Delete if changing from redirect to non-redirect
1164 $isRedirect = !is_null($redirectTitle);
1165 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1167 wfProfileIn( __METHOD__
);
1171 // This title is a redirect, Add/Update row in the redirect table
1172 $set = array( /* SET */
1173 'rd_namespace' => $redirectTitle->getNamespace(),
1174 'rd_title' => $redirectTitle->getDBkey(),
1175 'rd_from' => $this->getId(),
1178 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1180 // This is not a redirect, remove row from redirect table
1181 $where = array( 'rd_from' => $this->getId() );
1182 $dbw->delete( 'redirect', $where, __METHOD__
);
1185 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1186 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1187 wfProfileOut( __METHOD__
);
1188 return ( $dbw->affectedRows() != 0 );
1195 * If the given revision is newer than the currently set page_latest,
1196 * update the page record. Otherwise, do nothing.
1198 * @param Database $dbw
1199 * @param Revision $revision
1201 function updateIfNewerOn( &$dbw, $revision ) {
1202 wfProfileIn( __METHOD__
);
1204 $row = $dbw->selectRow(
1205 array( 'revision', 'page' ),
1206 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1208 'page_id' => $this->getId(),
1209 'page_latest=rev_id' ),
1212 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1213 wfProfileOut( __METHOD__
);
1216 $prev = $row->rev_id
;
1217 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1219 # No or missing previous revision; mark the page as new
1221 $lastRevIsRedirect = null;
1224 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1225 wfProfileOut( __METHOD__
);
1230 * @return string Complete article text, or null if error
1232 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1233 wfProfileIn( __METHOD__
);
1235 if( $section == '' ) {
1236 // Whole-page edit; let the text through unmolested.
1238 if( is_null( $edittime ) ) {
1239 $rev = Revision
::newFromTitle( $this->mTitle
);
1241 $dbw = wfGetDB( DB_MASTER
);
1242 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1244 if( is_null( $rev ) ) {
1245 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1246 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1249 $oldtext = $rev->getText();
1251 if( $section == 'new' ) {
1252 # Inserting a new section
1253 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1254 $text = strlen( trim( $oldtext ) ) > 0
1255 ?
"{$oldtext}\n\n{$subject}{$text}"
1256 : "{$subject}{$text}";
1258 # Replacing an existing section; roll out the big guns
1260 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1265 wfProfileOut( __METHOD__
);
1270 * @deprecated use Article::doEdit()
1272 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1273 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1274 ( $isminor ? EDIT_MINOR
: 0 ) |
1275 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1276 ( $bot ? EDIT_FORCE_BOT
: 0 );
1278 # If this is a comment, add the summary as headline
1279 if ( $comment && $summary != "" ) {
1280 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1283 $this->doEdit( $text, $summary, $flags );
1285 $dbw = wfGetDB( DB_MASTER
);
1287 if (!$this->mTitle
->userIsWatching()) {
1293 if ( $this->mTitle
->userIsWatching() ) {
1299 $this->doRedirect( $this->isRedirect( $text ) );
1303 * @deprecated use Article::doEdit()
1305 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1306 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1307 ( $minor ? EDIT_MINOR
: 0 ) |
1308 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1310 $good = $this->doEdit( $text, $summary, $flags );
1312 $dbw = wfGetDB( DB_MASTER
);
1314 if (!$this->mTitle
->userIsWatching()) {
1320 if ( $this->mTitle
->userIsWatching() ) {
1327 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1328 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1330 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1338 * Change an existing article or create a new article. Updates RC and all necessary caches,
1339 * optionally via the deferred update array.
1341 * $wgUser must be set before calling this function.
1343 * @param string $text New text
1344 * @param string $summary Edit summary
1345 * @param integer $flags bitfield:
1347 * Article is known or assumed to be non-existent, create a new one
1349 * Article is known or assumed to be pre-existing, update it
1351 * Mark this edit minor, if the user is allowed to do so
1353 * Do not log the change in recentchanges
1355 * Mark the edit a "bot" edit regardless of user rights
1356 * EDIT_DEFER_UPDATES
1357 * Defer some of the updates until the end of index.php
1359 * Fill in blank summaries with generated text where possible
1361 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1362 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1363 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1364 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1365 * to MediaWiki's performance-optimised locking strategy.
1366 * @param $baseRevId, the revision ID this edit was based off, if any
1368 * @return bool success
1370 function doEdit( $text, $summary, $flags = 0, $baseRevId = false ) {
1371 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1373 wfProfileIn( __METHOD__
);
1376 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1377 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1379 $flags |
= EDIT_UPDATE
;
1385 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1386 &$summary, $flags & EDIT_MINOR
,
1387 null, null, &$flags ) ) )
1389 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1390 wfProfileOut( __METHOD__
);
1394 # Silently ignore EDIT_MINOR if not allowed
1395 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1396 $bot = $flags & EDIT_FORCE_BOT
;
1398 $oldtext = $this->getContent();
1399 $oldsize = strlen( $oldtext );
1401 # Provide autosummaries if one is not provided and autosummaries are enabled.
1402 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1403 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1406 $editInfo = $this->prepareTextForEdit( $text );
1407 $text = $editInfo->pst
;
1408 $newsize = strlen( $text );
1410 $dbw = wfGetDB( DB_MASTER
);
1411 $now = wfTimestampNow();
1413 if ( $flags & EDIT_UPDATE
) {
1414 # Update article, but only if changed.
1416 # Make sure the revision is either completely inserted or not inserted at all
1417 if( !$wgDBtransactions ) {
1418 $userAbort = ignore_user_abort( true );
1424 $changed = ( strcmp( $text, $oldtext ) != 0 );
1427 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1428 - (int)$this->isCountable( $oldtext );
1429 $this->mTotalAdjustment
= 0;
1431 $lastRevision = $dbw->selectField(
1432 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1434 if ( !$lastRevision ) {
1435 # Article gone missing
1436 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1437 wfProfileOut( __METHOD__
);
1441 $revision = new Revision( array(
1442 'page' => $this->getId(),
1443 'comment' => $summary,
1444 'minor_edit' => $isminor,
1446 'parent_id' => $lastRevision
1450 $revisionId = $revision->insertOn( $dbw );
1453 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1455 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId) );
1458 /* Belated edit conflict! Run away!! */
1462 # Update recentchanges
1463 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1464 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1465 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1468 # Mark as patrolled if the user can do so
1469 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1470 RecentChange
::markPatrolled( $rcid );
1471 PatrolLog
::record( $rcid, true );
1474 $wgUser->incEditCount();
1479 // Keep the same revision ID, but do some updates on it
1480 $revisionId = $this->getRevIdFetched();
1481 // Update page_touched, this is usually implicit in the page update
1482 // Other cache updates are done in onArticleEdit()
1483 $this->mTitle
->invalidateCache();
1486 if( !$wgDBtransactions ) {
1487 ignore_user_abort( $userAbort );
1491 # Invalidate cache of this article and all pages using this article
1492 # as a template. Partly deferred.
1493 Article
::onArticleEdit( $this->mTitle
);
1495 # Update links tables, site stats, etc.
1496 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1499 # Create new article
1501 # Set statistics members
1502 # We work out if it's countable after PST to avoid counter drift
1503 # when articles are created with {{subst:}}
1504 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1505 $this->mTotalAdjustment
= 1;
1509 # Add the page record; stake our claim on this title!
1510 # This will fail with a database query exception if the article already exists
1511 $newid = $this->insertOn( $dbw );
1513 # Save the revision text...
1514 $revision = new Revision( array(
1516 'comment' => $summary,
1517 'minor_edit' => $isminor,
1520 $revisionId = $revision->insertOn( $dbw );
1522 $this->mTitle
->resetArticleID( $newid );
1524 # Update the page record with revision data
1525 $this->updateRevisionOn( $dbw, $revision, 0 );
1527 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1529 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1530 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1531 '', strlen( $text ), $revisionId );
1532 # Mark as patrolled if the user can
1533 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1534 RecentChange
::markPatrolled( $rcid );
1535 PatrolLog
::record( $rcid, true );
1538 $wgUser->incEditCount();
1541 # Update links, etc.
1542 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1545 Article
::onArticleCreate( $this->mTitle
);
1547 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1548 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1551 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1556 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1557 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1560 wfProfileOut( __METHOD__
);
1565 * @deprecated wrapper for doRedirect
1567 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1568 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1572 * Output a redirect back to the article.
1573 * This is typically used after an edit.
1575 * @param boolean $noRedir Add redirect=no
1576 * @param string $sectionAnchor section to redirect to, including "#"
1577 * @param string $extraQuery, extra query params
1579 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1582 $query = 'redirect=no';
1584 $query .= "&$query";
1586 $query = $extraQuery;
1588 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1592 * Mark this particular edit/page as patrolled
1594 function markpatrolled() {
1595 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1596 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1598 # Check patrol config options
1600 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1601 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1605 # If we haven't been given an rc_id value, we can't do anything
1606 $rcid = (int) $wgRequest->getVal('rcid');
1607 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1608 if ( is_null ( $rc ) )
1610 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1614 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1615 // Only new pages can be patrolled if the general patrolling is off....???
1616 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1618 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1623 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1625 if (count($permission_errors)>0)
1627 $wgOut->showPermissionsErrorPage( $permission_errors );
1631 # Handle the 'MarkPatrolled' hook
1632 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1636 #It would be nice to see where the user had actually come from, but for now just guess
1637 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1638 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1640 # If it's left up to us, check that the user is allowed to patrol this edit
1641 # If the user has the "autopatrol" right, then we'll assume there are no
1642 # other conditions stopping them doing so
1643 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1644 $rc = RecentChange
::newFromId( $rcid );
1645 # Graceful error handling, as we've done before here...
1646 # (If the recent change doesn't exist, then it doesn't matter whether
1647 # the user is allowed to patrol it or not; nothing is going to happen
1648 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1649 # The user made this edit, and can't patrol it
1650 # Tell them so, and then back off
1651 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1652 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1653 $wgOut->returnToMain( false, $return );
1658 # Check that the revision isn't patrolled already
1659 # Prevents duplicate log entries
1660 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1661 # Mark the edit as patrolled
1662 RecentChange
::markPatrolled( $rcid );
1663 PatrolLog
::record( $rcid );
1664 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1668 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1669 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1670 $wgOut->returnToMain( false, $return );
1674 * User-interface handler for the "watch" action
1679 global $wgUser, $wgOut;
1681 if ( $wgUser->isAnon() ) {
1682 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1685 if ( wfReadOnly() ) {
1686 $wgOut->readOnlyPage();
1690 if( $this->doWatch() ) {
1691 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1692 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1694 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1697 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1701 * Add this page to $wgUser's watchlist
1702 * @return bool true on successful watch operation
1704 function doWatch() {
1706 if( $wgUser->isAnon() ) {
1710 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1711 $wgUser->addWatch( $this->mTitle
);
1713 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1720 * User interface handler for the "unwatch" action.
1722 function unwatch() {
1724 global $wgUser, $wgOut;
1726 if ( $wgUser->isAnon() ) {
1727 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1730 if ( wfReadOnly() ) {
1731 $wgOut->readOnlyPage();
1735 if( $this->doUnwatch() ) {
1736 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1737 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1739 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1742 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1746 * Stop watching a page
1747 * @return bool true on successful unwatch
1749 function doUnwatch() {
1751 if( $wgUser->isAnon() ) {
1755 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1756 $wgUser->removeWatch( $this->mTitle
);
1758 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1765 * action=protect handler
1767 function protect() {
1768 $form = new ProtectionForm( $this );
1773 * action=unprotect handler (alias)
1775 function unprotect() {
1780 * Update the article's restriction field, and leave a log entry.
1782 * @param array $limit set of restriction keys
1783 * @param string $reason
1784 * @return bool true on success
1786 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1787 global $wgUser, $wgRestrictionTypes, $wgContLang;
1789 $id = $this->mTitle
->getArticleID();
1790 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1798 // Take this opportunity to purge out expired restrictions
1799 Title
::purgeExpiredRestrictions();
1801 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1802 # we expect a single selection, but the schema allows otherwise.
1804 foreach( $wgRestrictionTypes as $action )
1805 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1807 $current = Article
::flattenRestrictions( $current );
1808 $updated = Article
::flattenRestrictions( $limit );
1810 $changed = ( $current != $updated );
1811 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1812 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1813 $protect = ( $updated != '' );
1815 # If nothing's changed, do nothing
1817 global $wgGroupPermissions;
1818 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1820 $dbw = wfGetDB( DB_MASTER
);
1822 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1824 $expiry_description = '';
1825 if ( $encodedExpiry != 'infinity' ) {
1826 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1829 # Prepare a null revision to be added to the history
1830 $modified = $current != '' && $protect;
1832 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1834 $comment_type = 'unprotectedarticle';
1836 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1838 foreach( $limit as $action => $restrictions ) {
1839 # Check if the group level required to edit also can protect pages
1840 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1841 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1842 $wgGroupPermissions[$restrictions]['protect'] );
1845 $cascade_description = '';
1847 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1851 $comment .= ": $reason";
1853 $comment .= " [$updated]";
1854 if ( $expiry_description && $protect )
1855 $comment .= "$expiry_description";
1857 $comment .= "$cascade_description";
1859 # Update restrictions table
1860 foreach( $limit as $action => $restrictions ) {
1861 if ($restrictions != '' ) {
1862 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1863 array( 'pr_page' => $id, 'pr_type' => $action
1864 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1865 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1867 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1868 'pr_type' => $action ), __METHOD__
);
1872 # Insert a null revision
1873 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1874 $nullRevId = $nullRevision->insertOn( $dbw );
1876 # Update page record
1877 $dbw->update( 'page',
1879 'page_touched' => $dbw->timestamp(),
1880 'page_restrictions' => '',
1881 'page_latest' => $nullRevId
1882 ), array( /* WHERE */
1884 ), 'Article::protect'
1887 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, false) );
1888 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1890 # Update the protection log
1891 $log = new LogPage( 'protect' );
1893 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1895 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1899 } # End "changed" check
1905 * Take an array of page restrictions and flatten it to a string
1906 * suitable for insertion into the page_restrictions field.
1907 * @param array $limit
1911 function flattenRestrictions( $limit ) {
1912 if( !is_array( $limit ) ) {
1913 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1917 foreach( $limit as $action => $restrictions ) {
1918 if( $restrictions != '' ) {
1919 $bits[] = "$action=$restrictions";
1922 return implode( ':', $bits );
1926 * Auto-generates a deletion reason
1927 * @param bool &$hasHistory Whether the page has a history
1929 public function generateReason(&$hasHistory)
1932 $dbw = wfGetDB(DB_MASTER
);
1933 // Get the last revision
1934 $rev = Revision
::newFromTitle($this->mTitle
);
1937 // Get the article's contents
1938 $contents = $rev->getText();
1940 // If the page is blank, use the text from the previous revision,
1941 // which can only be blank if there's a move/import/protect dummy revision involved
1944 $prev = $rev->getPrevious();
1947 $contents = $prev->getText();
1952 // Find out if there was only one contributor
1953 // Only scan the last 20 revisions
1955 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1956 array('LIMIT' => $limit));
1958 // This page has no revisions, which is very weird
1960 if($res->numRows() > 1)
1963 $hasHistory = false;
1964 $row = $dbw->fetchObject($res);
1965 $onlyAuthor = $row->rev_user_text
;
1966 // Try to find a second contributor
1967 while( $row = $dbw->fetchObject($res) ) {
1968 if($row->rev_user_text
!= $onlyAuthor) {
1969 $onlyAuthor = false;
1973 $dbw->freeResult($res);
1975 // Generate the summary with a '$1' placeholder
1977 // The current revision is blank and the one before is also
1978 // blank. It's just not our lucky day
1979 $reason = wfMsgForContent('exbeforeblank', '$1');
1982 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1984 $reason = wfMsgForContent('excontent', '$1');
1987 // Replace newlines with spaces to prevent uglyness
1988 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1989 // Calculate the maximum amount of chars to get
1990 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1991 $maxLength = 255 - (strlen($reason) - 2) - 3;
1992 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1993 // Remove possible unfinished links
1994 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1995 // Now replace the '$1' placeholder
1996 $reason = str_replace( '$1', $contents, $reason );
2002 * UI entry point for page deletion
2005 global $wgUser, $wgOut, $wgRequest;
2007 $confirm = $wgRequest->wasPosted() &&
2008 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2010 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2011 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2013 $reason = $this->DeleteReasonList
;
2015 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2016 // Entry from drop down menu + additional comment
2017 $reason .= ': ' . $this->DeleteReason
;
2018 } elseif ( $reason == 'other' ) {
2019 $reason = $this->DeleteReason
;
2021 # Flag to hide all contents of the archived revisions
2022 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2024 # This code desperately needs to be totally rewritten
2026 # Read-only check...
2027 if ( wfReadOnly() ) {
2028 $wgOut->readOnlyPage();
2033 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2035 if (count($permission_errors)>0) {
2036 $wgOut->showPermissionsErrorPage( $permission_errors );
2040 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2042 # Better double-check that it hasn't been deleted yet!
2043 $dbw = wfGetDB( DB_MASTER
);
2044 $conds = $this->mTitle
->pageCond();
2045 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2046 if ( $latest === false ) {
2047 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2051 # Hack for big sites
2052 $bigHistory = $this->isBigDeletion();
2053 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2054 global $wgLang, $wgDeleteRevisionsLimit;
2055 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2056 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2061 $this->doDelete( $reason, $suppress );
2062 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2064 } elseif( $this->mTitle
->userIsWatching() ) {
2070 // Generate deletion reason
2071 $hasHistory = false;
2072 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2074 // If the page has a history, insert a warning
2075 if( $hasHistory && !$confirm ) {
2076 $skin=$wgUser->getSkin();
2077 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2079 global $wgLang, $wgDeleteRevisionsLimit;
2080 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2081 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2085 return $this->confirmDelete( '', $reason );
2089 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2091 function isBigDeletion() {
2092 global $wgDeleteRevisionsLimit;
2093 if( $wgDeleteRevisionsLimit ) {
2094 $revCount = $this->estimateRevisionCount();
2095 return $revCount > $wgDeleteRevisionsLimit;
2101 * @return int approximate revision count
2103 function estimateRevisionCount() {
2105 // For an exact count...
2106 //return $dbr->selectField( 'revision', 'COUNT(*)',
2107 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2108 return $dbr->estimateRowCount( 'revision', '*',
2109 array( 'rev_page' => $this->getId() ), __METHOD__
);
2113 * Get the last N authors
2114 * @param int $num Number of revisions to get
2115 * @param string $revLatest The latest rev_id, selected from the master (optional)
2116 * @return array Array of authors, duplicates not removed
2118 function getLastNAuthors( $num, $revLatest = 0 ) {
2119 wfProfileIn( __METHOD__
);
2121 // First try the slave
2122 // If that doesn't have the latest revision, try the master
2124 $db = wfGetDB( DB_SLAVE
);
2126 $res = $db->select( array( 'page', 'revision' ),
2127 array( 'rev_id', 'rev_user_text' ),
2129 'page_namespace' => $this->mTitle
->getNamespace(),
2130 'page_title' => $this->mTitle
->getDBkey(),
2131 'rev_page = page_id'
2132 ), __METHOD__
, $this->getSelectOptions( array(
2133 'ORDER BY' => 'rev_timestamp DESC',
2138 wfProfileOut( __METHOD__
);
2141 $row = $db->fetchObject( $res );
2142 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2143 $db = wfGetDB( DB_MASTER
);
2148 } while ( $continue );
2150 $authors = array( $row->rev_user_text
);
2151 while ( $row = $db->fetchObject( $res ) ) {
2152 $authors[] = $row->rev_user_text
;
2154 wfProfileOut( __METHOD__
);
2159 * Output deletion confirmation dialog
2160 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2161 * @param $reason string Prefilled reason
2163 function confirmDelete( $par, $reason ) {
2164 global $wgOut, $wgUser, $wgContLang;
2165 $align = $wgContLang->isRtl() ?
'left' : 'right';
2167 wfDebug( "Article::confirmDelete\n" );
2169 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2170 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2171 $wgOut->addWikiMsg( 'confirmdeletetext' );
2173 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2174 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2175 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2176 $suppress .= "</td></tr>";
2181 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2182 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2183 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2184 Xml
::openElement( 'table' ) .
2185 "<tr id=\"wpDeleteReasonListRow\">
2186 <td align='$align'>" .
2187 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2190 Xml
::listDropDown( 'wpDeleteReasonList',
2191 wfMsgForContent( 'deletereason-dropdown' ),
2192 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2195 <tr id=\"wpDeleteReasonRow\">
2196 <td align='$align'>" .
2197 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2200 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2206 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2213 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2216 Xml
::closeElement( 'table' ) .
2217 Xml
::closeElement( 'fieldset' ) .
2218 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2219 Xml
::closeElement( 'form' );
2221 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2222 $skin = $wgUser->getSkin();
2223 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2224 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2227 $wgOut->addHTML( $form );
2228 $this->showLogExtract( $wgOut );
2233 * Show relevant lines from the deletion log
2235 function showLogExtract( $out ) {
2236 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2237 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2242 * Perform a deletion and output success or failure messages
2244 function doDelete( $reason, $suppress = false ) {
2245 global $wgOut, $wgUser;
2246 wfDebug( __METHOD__
."\n" );
2248 $id = $this->getId();
2250 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2251 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2252 $deleted = $this->mTitle
->getPrefixedText();
2254 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2255 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2257 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2259 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2260 $wgOut->returnToMain( false );
2261 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2263 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2269 * Back-end article deletion
2270 * Deletes the article with database consistency, writes logs, purges caches
2273 function doDeleteArticle( $reason, $suppress = false ) {
2274 global $wgUseSquid, $wgDeferredUpdateList;
2275 global $wgUseTrackbacks;
2277 wfDebug( __METHOD__
."\n" );
2279 $dbw = wfGetDB( DB_MASTER
);
2280 $ns = $this->mTitle
->getNamespace();
2281 $t = $this->mTitle
->getDBkey();
2282 $id = $this->mTitle
->getArticleID();
2284 if ( $t == '' ||
$id == 0 ) {
2288 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2289 array_push( $wgDeferredUpdateList, $u );
2291 // Bitfields to further suppress the content
2294 // This should be 15...
2295 $bitfield |
= Revision
::DELETED_TEXT
;
2296 $bitfield |
= Revision
::DELETED_COMMENT
;
2297 $bitfield |
= Revision
::DELETED_USER
;
2298 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2300 $bitfield = 'rev_deleted';
2304 // For now, shunt the revision data into the archive table.
2305 // Text is *not* removed from the text table; bulk storage
2306 // is left intact to avoid breaking block-compression or
2307 // immutable storage schemes.
2309 // For backwards compatibility, note that some older archive
2310 // table entries will have ar_text and ar_flags fields still.
2312 // In the future, we may keep revisions and mark them with
2313 // the rev_deleted field, which is reserved for this purpose.
2314 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2316 'ar_namespace' => 'page_namespace',
2317 'ar_title' => 'page_title',
2318 'ar_comment' => 'rev_comment',
2319 'ar_user' => 'rev_user',
2320 'ar_user_text' => 'rev_user_text',
2321 'ar_timestamp' => 'rev_timestamp',
2322 'ar_minor_edit' => 'rev_minor_edit',
2323 'ar_rev_id' => 'rev_id',
2324 'ar_text_id' => 'rev_text_id',
2325 'ar_text' => '\'\'', // Be explicit to appease
2326 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2327 'ar_len' => 'rev_len',
2328 'ar_page_id' => 'page_id',
2329 'ar_deleted' => $bitfield
2332 'page_id = rev_page'
2336 # Delete restrictions for it
2337 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2339 # Fix category table counts
2341 $res = $dbw->select( 'categorylinks', 'cl_to',
2342 array( 'cl_from' => $id ), __METHOD__
);
2343 foreach( $res as $row ) {
2344 $cats []= $row->cl_to
;
2346 $this->updateCategoryCounts( array(), $cats );
2348 # Now that it's safely backed up, delete it
2349 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2350 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2356 # If using cascading deletes, we can skip some explicit deletes
2357 if ( !$dbw->cascadingDeletes() ) {
2358 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2360 if ($wgUseTrackbacks)
2361 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2363 # Delete outgoing links
2364 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2365 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2366 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2367 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2368 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2369 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2370 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2373 # If using cleanup triggers, we can skip some manual deletes
2374 if ( !$dbw->cleanupTriggers() ) {
2376 # Clean up recentchanges entries...
2377 $dbw->delete( 'recentchanges',
2378 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2384 Article
::onArticleDelete( $this->mTitle
);
2386 # Clear the cached article id so the interface doesn't act like we exist
2387 $this->mTitle
->resetArticleID( 0 );
2388 $this->mTitle
->mArticleID
= 0;
2390 # Log the deletion, if the page was suppressed, log it at Oversight instead
2391 $logtype = $suppress ?
'suppress' : 'delete';
2392 $log = new LogPage( $logtype );
2394 # Make sure logging got through
2395 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2401 * Roll back the most recent consecutive set of edits to a page
2402 * from the same user; fails if there are no eligible edits to
2403 * roll back to, e.g. user is the sole contributor. This function
2404 * performs permissions checks on $wgUser, then calls commitRollback()
2405 * to do the dirty work
2407 * @param string $fromP - Name of the user whose edits to rollback.
2408 * @param string $summary - Custom summary. Set to default summary if empty.
2409 * @param string $token - Rollback token.
2410 * @param bool $bot - If true, mark all reverted edits as bot.
2412 * @param array $resultDetails contains result-specific array of additional values
2413 * 'alreadyrolled' : 'current' (rev)
2414 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2416 * @return array of errors, each error formatted as
2417 * array(messagekey, param1, param2, ...).
2418 * On success, the array is empty. This array can also be passed to
2419 * OutputPage::showPermissionsErrorPage().
2421 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2423 $resultDetails = null;
2426 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2427 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2428 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2429 $errors[] = array( 'sessionfailure' );
2431 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2432 $errors[] = array( 'actionthrottledtext' );
2434 # If there were errors, bail out now
2438 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2442 * Backend implementation of doRollback(), please refer there for parameter
2443 * and return value documentation
2445 * NOTE: This function does NOT check ANY permissions, it just commits the
2446 * rollback to the DB Therefore, you should only call this function direct-
2447 * ly if you want to use custom permissions checks. If you don't, use
2448 * doRollback() instead.
2450 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2451 global $wgUseRCPatrol, $wgUser, $wgLang;
2452 $dbw = wfGetDB( DB_MASTER
);
2454 if( wfReadOnly() ) {
2455 return array( array( 'readonlytext' ) );
2458 # Get the last editor
2459 $current = Revision
::newFromTitle( $this->mTitle
);
2460 if( is_null( $current ) ) {
2461 # Something wrong... no page?
2462 return array(array('notanarticle'));
2465 $from = str_replace( '_', ' ', $fromP );
2466 if( $from != $current->getUserText() ) {
2467 $resultDetails = array( 'current' => $current );
2468 return array(array('alreadyrolled',
2469 htmlspecialchars($this->mTitle
->getPrefixedText()),
2470 htmlspecialchars($fromP),
2471 htmlspecialchars($current->getUserText())
2475 # Get the last edit not by this guy
2476 $user = intval( $current->getUser() );
2477 $user_text = $dbw->addQuotes( $current->getUserText() );
2478 $s = $dbw->selectRow( 'revision',
2479 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2480 array( 'rev_page' => $current->getPage(),
2481 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2483 array( 'USE INDEX' => 'page_timestamp',
2484 'ORDER BY' => 'rev_timestamp DESC' )
2486 if( $s === false ) {
2487 # No one else ever edited this page
2488 return array(array('cantrollback'));
2489 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2490 # Only admins can see this text
2491 return array(array('notvisiblerev'));
2495 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2496 # Mark all reverted edits as bot
2499 if ( $wgUseRCPatrol ) {
2500 # Mark all reverted edits as patrolled
2501 $set['rc_patrolled'] = 1;
2505 $dbw->update( 'recentchanges', $set,
2507 'rc_cur_id' => $current->getPage(),
2508 'rc_user_text' => $current->getUserText(),
2509 "rc_timestamp > '{$s->rev_timestamp}'",
2514 # Generate the edit summary if necessary
2515 $target = Revision
::newFromId( $s->rev_id
);
2516 if( empty( $summary ) ){
2517 $summary = wfMsgForContent( 'revertpage' );
2520 # Allow the custom summary to use the same args as the default message
2522 $target->getUserText(), $from, $s->rev_id
,
2523 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2524 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2526 $summary = wfMsgReplaceArgs( $summary, $args );
2529 $flags = EDIT_UPDATE
;
2531 if ($wgUser->isAllowed('minoredit'))
2532 $flags |
= EDIT_MINOR
;
2534 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2535 $flags |
= EDIT_FORCE_BOT
;
2536 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2538 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2540 $resultDetails = array(
2541 'summary' => $summary,
2542 'current' => $current,
2543 'target' => $target,
2549 * User interface for rollback operations
2551 function rollback() {
2552 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2555 $result = $this->doRollback(
2556 $wgRequest->getVal( 'from' ),
2557 $wgRequest->getText( 'summary' ),
2558 $wgRequest->getVal( 'token' ),
2559 $wgRequest->getBool( 'bot' ),
2563 if( in_array( array( 'blocked' ), $result ) ) {
2564 $wgOut->blockedPage();
2567 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2568 $wgOut->rateLimited();
2571 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2572 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2573 $errArray = $result[0];
2574 $errMsg = array_shift( $errArray );
2575 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2576 if( isset( $details['current'] ) ){
2577 $current = $details['current'];
2578 if( $current->getComment() != '' ) {
2579 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2584 # Display permissions errors before read-only message -- there's no
2585 # point in misleading the user into thinking the inability to rollback
2586 # is only temporary.
2587 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2588 # array_diff is completely broken for arrays of arrays, sigh. Re-
2589 # move any 'readonlytext' error manually.
2591 foreach( $result as $error ) {
2592 if( $error != array( 'readonlytext' ) ) {
2596 $wgOut->showPermissionsErrorPage( $out );
2599 if( $result == array( array('readonlytext') ) ) {
2600 $wgOut->readOnlyPage();
2604 $current = $details['current'];
2605 $target = $details['target'];
2606 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2607 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2608 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2609 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2610 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2611 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2612 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2613 $wgOut->returnToMain( false, $this->mTitle
);
2618 * Do standard deferred updates after page view
2621 function viewUpdates() {
2622 global $wgDeferredUpdateList, $wgUser;
2624 if ( 0 != $this->getID() ) {
2625 # Don't update page view counters on views from bot users (bug 14044)
2626 global $wgDisableCounters;
2627 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2628 Article
::incViewCount( $this->getID() );
2629 $u = new SiteStatsUpdate( 1, 0, 0 );
2630 array_push( $wgDeferredUpdateList, $u );
2634 # Update newtalk / watchlist notification status
2635 $wgUser->clearNotification( $this->mTitle
);
2639 * Prepare text which is about to be saved.
2640 * Returns a stdclass with source, pst and output members
2642 function prepareTextForEdit( $text, $revid=null ) {
2643 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2645 return $this->mPreparedEdit
;
2648 $edit = (object)array();
2649 $edit->revid
= $revid;
2650 $edit->newText
= $text;
2651 $edit->pst
= $this->preSaveTransform( $text );
2652 $options = new ParserOptions
;
2653 $options->setTidy( true );
2654 $options->enableLimitReport();
2655 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2656 $edit->oldText
= $this->getContent();
2657 $this->mPreparedEdit
= $edit;
2662 * Do standard deferred updates after page edit.
2663 * Update links tables, site stats, search index and message cache.
2664 * Every 100th edit, prune the recent changes table.
2667 * @param $text New text of the article
2668 * @param $summary Edit summary
2669 * @param $minoredit Minor edit
2670 * @param $timestamp_of_pagechange Timestamp associated with the page change
2671 * @param $newid rev_id value of the new revision
2672 * @param $changed Whether or not the content actually changed
2674 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2675 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2677 wfProfileIn( __METHOD__
);
2680 # Be careful not to double-PST: $text is usually already PST-ed once
2681 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2682 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2683 $editInfo = $this->prepareTextForEdit( $text, $newid );
2685 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2686 $editInfo = $this->mPreparedEdit
;
2689 # Save it to the parser cache
2690 if ( $wgEnableParserCache ) {
2691 $parserCache = ParserCache
::singleton();
2692 $parserCache->save( $editInfo->output
, $this, $wgUser );
2695 # Update the links tables
2696 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2699 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2700 if ( 0 == mt_rand( 0, 99 ) ) {
2701 // Flush old entries from the `recentchanges` table; we do this on
2702 // random requests so as to avoid an increase in writes for no good reason
2704 $dbw = wfGetDB( DB_MASTER
);
2705 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2706 $recentchanges = $dbw->tableName( 'recentchanges' );
2707 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2708 $dbw->query( $sql );
2712 $id = $this->getID();
2713 $title = $this->mTitle
->getPrefixedDBkey();
2714 $shortTitle = $this->mTitle
->getDBkey();
2717 wfProfileOut( __METHOD__
);
2721 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2722 array_push( $wgDeferredUpdateList, $u );
2723 $u = new SearchUpdate( $id, $title, $text );
2724 array_push( $wgDeferredUpdateList, $u );
2726 # If this is another user's talk page, update newtalk
2727 # Don't do this if $changed = false otherwise some idiot can null-edit a
2728 # load of user talk pages and piss people off, nor if it's a minor edit
2729 # by a properly-flagged bot.
2730 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2731 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2732 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2733 $other = User
::newFromName( $shortTitle );
2734 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2735 // An anonymous user
2736 $other = new User();
2737 $other->setName( $shortTitle );
2740 $other->setNewtalk( true );
2745 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2746 $wgMessageCache->replace( $shortTitle, $text );
2749 wfProfileOut( __METHOD__
);
2753 * Perform article updates on a special page creation.
2755 * @param Revision $rev
2757 * @todo This is a shitty interface function. Kill it and replace the
2758 * other shitty functions like editUpdates and such so it's not needed
2761 function createUpdates( $rev ) {
2762 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2763 $this->mTotalAdjustment
= 1;
2764 $this->editUpdates( $rev->getText(), $rev->getComment(),
2765 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2769 * Generate the navigation links when browsing through an article revisions
2770 * It shows the information as:
2771 * Revision as of \<date\>; view current revision
2772 * \<- Previous version | Next Version -\>
2775 * @param string $oldid Revision ID of this article revision
2777 function setOldSubtitle( $oldid=0 ) {
2778 global $wgLang, $wgOut, $wgUser;
2780 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2784 $revision = Revision
::newFromId( $oldid );
2786 $current = ( $oldid == $this->mLatest
);
2787 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2788 $sk = $wgUser->getSkin();
2790 ?
wfMsg( 'currentrevisionlink' )
2791 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2794 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2795 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2797 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2798 : wfMsg( 'previousrevision' );
2800 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2802 $nextlink = $current
2803 ?
wfMsg( 'nextrevision' )
2804 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2805 $nextdiff = $current
2807 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2810 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2811 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2812 if( $revision->isCurrent() ) {
2813 // We don't handle top deleted edits too well
2814 $cdel = wfMsgHtml('rev-delundel');
2815 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2816 // If revision was hidden from sysops
2817 $cdel = wfMsgHtml('rev-delundel');
2819 $cdel = $sk->makeKnownLinkObj( $revdel,
2820 wfMsgHtml('rev-delundel'),
2821 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2822 '&oldid=' . urlencode( $oldid ) );
2823 // Bolden oversighted content
2824 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2825 $cdel = "<strong>$cdel</strong>";
2827 $cdel = "(<small>$cdel</small>) ";
2829 # Show user links if allowed to see them. Normally they
2830 # are hidden regardless, but since we can already see the text here...
2831 $userlinks = $sk->revUserTools( $revision, false );
2833 $m = wfMsg( 'revision-info-current' );
2834 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2835 ?
'revision-info-current'
2838 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2840 "\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";
2841 $wgOut->setSubtitle( $r );
2845 * This function is called right before saving the wikitext,
2846 * so we can do things like signatures and links-in-context.
2848 * @param string $text
2850 function preSaveTransform( $text ) {
2851 global $wgParser, $wgUser;
2852 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2855 /* Caching functions */
2858 * checkLastModified returns true if it has taken care of all
2859 * output to the client that is necessary for this request.
2860 * (that is, it has sent a cached version of the page)
2862 function tryFileCache() {
2863 static $called = false;
2865 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2869 if($this->isFileCacheable()) {
2870 $touched = $this->mTouched
;
2871 $cache = new HTMLFileCache( $this->mTitle
);
2872 if($cache->isFileCacheGood( $touched )) {
2873 wfDebug( "Article::tryFileCache(): about to load file\n" );
2874 $cache->loadFromFileCache();
2877 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2878 ob_start( array(&$cache, 'saveToFileCache' ) );
2881 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2886 * Check if the page can be cached
2889 function isFileCacheable() {
2890 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2891 $action = $wgRequest->getVal( 'action' );
2892 $oldid = $wgRequest->getVal( 'oldid' );
2893 $diff = $wgRequest->getVal( 'diff' );
2894 $redirect = $wgRequest->getVal( 'redirect' );
2895 $printable = $wgRequest->getVal( 'printable' );
2896 $page = $wgRequest->getVal( 'page' );
2898 //check for non-standard user language; this covers uselang,
2899 //and extensions for auto-detecting user language.
2900 $ulang = $wgLang->getCode();
2901 $clang = $wgContLang->getCode();
2903 $cacheable = $wgUseFileCache
2904 && (!$wgShowIPinHeader)
2905 && ($this->getID() != 0)
2906 && ($wgUser->isAnon())
2907 && (!$wgUser->getNewtalk())
2908 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2909 && (empty( $action ) ||
$action == 'view')
2912 && (!isset($redirect))
2913 && (!isset($printable))
2915 && (!$this->mRedirectedFrom
)
2916 && ($ulang === $clang);
2919 //extension may have reason to disable file caching on some pages.
2920 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2927 * Loads page_touched and returns a value indicating if it should be used
2930 function checkTouched() {
2931 if( !$this->mDataLoaded
) {
2932 $this->loadPageData();
2934 return !$this->mIsRedirect
;
2938 * Get the page_touched field
2940 function getTouched() {
2941 # Ensure that page data has been loaded
2942 if( !$this->mDataLoaded
) {
2943 $this->loadPageData();
2945 return $this->mTouched
;
2949 * Get the page_latest field
2951 function getLatest() {
2952 if ( !$this->mDataLoaded
) {
2953 $this->loadPageData();
2955 return $this->mLatest
;
2959 * Edit an article without doing all that other stuff
2960 * The article must already exist; link tables etc
2961 * are not updated, caches are not flushed.
2963 * @param string $text text submitted
2964 * @param string $comment comment submitted
2965 * @param bool $minor whereas it's a minor modification
2967 function quickEdit( $text, $comment = '', $minor = 0 ) {
2968 wfProfileIn( __METHOD__
);
2970 $dbw = wfGetDB( DB_MASTER
);
2972 $revision = new Revision( array(
2973 'page' => $this->getId(),
2975 'comment' => $comment,
2976 'minor_edit' => $minor ?
1 : 0,
2978 $revision->insertOn( $dbw );
2979 $this->updateRevisionOn( $dbw, $revision );
2982 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
2984 wfProfileOut( __METHOD__
);
2988 * Used to increment the view counter
2991 * @param integer $id article id
2993 function incViewCount( $id ) {
2994 $id = intval( $id );
2995 global $wgHitcounterUpdateFreq, $wgDBtype;
2997 $dbw = wfGetDB( DB_MASTER
);
2998 $pageTable = $dbw->tableName( 'page' );
2999 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3000 $acchitsTable = $dbw->tableName( 'acchits' );
3002 if( $wgHitcounterUpdateFreq <= 1 ) {
3003 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3007 # Not important enough to warrant an error page in case of failure
3008 $oldignore = $dbw->ignoreErrors( true );
3010 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3012 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3013 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3014 # Most of the time (or on SQL errors), skip row count check
3015 $dbw->ignoreErrors( $oldignore );
3019 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3020 $row = $dbw->fetchObject( $res );
3021 $rown = intval( $row->n
);
3022 if( $rown >= $wgHitcounterUpdateFreq ){
3023 wfProfileIn( 'Article::incViewCount-collect' );
3024 $old_user_abort = ignore_user_abort( true );
3026 if ($wgDBtype == 'mysql')
3027 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3028 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3029 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3030 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3032 $dbw->query("DELETE FROM $hitcounterTable");
3033 if ($wgDBtype == 'mysql') {
3034 $dbw->query('UNLOCK TABLES');
3035 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3036 'WHERE page_id = hc_id');
3039 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3040 "FROM $acchitsTable WHERE page_id = hc_id");
3042 $dbw->query("DROP TABLE $acchitsTable");
3044 ignore_user_abort( $old_user_abort );
3045 wfProfileOut( 'Article::incViewCount-collect' );
3047 $dbw->ignoreErrors( $oldignore );
3051 * The onArticle*() functions are supposed to be a kind of hooks
3052 * which should be called whenever any of the specified actions
3055 * This is a good place to put code to clear caches, for instance.
3057 * This is called on page move and undelete, as well as edit
3059 * @param $title_obj a title object
3062 static function onArticleCreate($title) {
3063 # The talk page isn't in the regular link tables, so we need to update manually:
3064 if ( $title->isTalkPage() ) {
3065 $other = $title->getSubjectPage();
3067 $other = $title->getTalkPage();
3069 $other->invalidateCache();
3070 $other->purgeSquid();
3072 $title->touchLinks();
3073 $title->purgeSquid();
3074 $title->deleteTitleProtection();
3077 static function onArticleDelete( $title ) {
3078 global $wgUseFileCache, $wgMessageCache;
3080 // Update existence markers on article/talk tabs...
3081 if( $title->isTalkPage() ) {
3082 $other = $title->getSubjectPage();
3084 $other = $title->getTalkPage();
3086 $other->invalidateCache();
3087 $other->purgeSquid();
3089 $title->touchLinks();
3090 $title->purgeSquid();
3093 if ( $wgUseFileCache ) {
3094 $cm = new HTMLFileCache( $title );
3095 @unlink
( $cm->fileCacheName() );
3099 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3100 $wgMessageCache->replace( $title->getDBkey(), false );
3103 if( $title->getNamespace() == NS_IMAGE
) {
3104 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3105 $update->doUpdate();
3108 if( $title->getNamespace() == NS_USER_TALK
) {
3109 $user = User
::newFromName( $title->getText(), false );
3110 $user->setNewtalk( false );
3115 * Purge caches on page update etc
3117 static function onArticleEdit( $title ) {
3118 global $wgDeferredUpdateList, $wgUseFileCache;
3120 // Invalidate caches of articles which include this page
3121 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3123 // Invalidate the caches of all pages which redirect here
3124 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3126 # Purge squid for this page only
3127 $title->purgeSquid();
3130 if ( $wgUseFileCache ) {
3131 $cm = new HTMLFileCache( $title );
3132 @unlink
( $cm->fileCacheName() );
3139 * Overriden by ImagePage class, only present here to avoid a fatal error
3140 * Called for ?action=revert
3142 public function revert(){
3144 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3148 * Info about this page
3149 * Called for ?action=info when $wgAllowPageInfo is on.
3154 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3156 if ( !$wgAllowPageInfo ) {
3157 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3161 $page = $this->mTitle
->getSubjectPage();
3163 $wgOut->setPagetitle( $page->getPrefixedText() );
3164 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3165 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3167 if( !$this->mTitle
->exists() ) {
3168 $wgOut->addHtml( '<div class="noarticletext">' );
3169 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3170 // This doesn't quite make sense; the user is asking for
3171 // information about the _page_, not the message... -- RC
3172 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3174 $msg = $wgUser->isLoggedIn()
3176 : 'noarticletextanon';
3177 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3179 $wgOut->addHtml( '</div>' );
3181 $dbr = wfGetDB( DB_SLAVE
);
3183 'wl_title' => $page->getDBkey(),
3184 'wl_namespace' => $page->getNamespace() );
3185 $numwatchers = $dbr->selectField(
3190 $this->getSelectOptions() );
3192 $pageInfo = $this->pageCountInfo( $page );
3193 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3195 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3196 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3198 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3200 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3202 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3204 $wgOut->addHTML( '</ul>' );
3210 * Return the total number of edits and number of unique editors
3211 * on a given page. If page does not exist, returns false.
3213 * @param Title $title
3217 function pageCountInfo( $title ) {
3218 $id = $title->getArticleId();
3223 $dbr = wfGetDB( DB_SLAVE
);
3225 $rev_clause = array( 'rev_page' => $id );
3227 $edits = $dbr->selectField(
3232 $this->getSelectOptions() );
3234 $authors = $dbr->selectField(
3236 'COUNT(DISTINCT rev_user_text)',
3239 $this->getSelectOptions() );
3241 return array( 'edits' => $edits, 'authors' => $authors );
3245 * Return a list of templates used by this article.
3246 * Uses the templatelinks table
3248 * @return array Array of Title objects
3250 function getUsedTemplates() {
3252 $id = $this->mTitle
->getArticleID();
3257 $dbr = wfGetDB( DB_SLAVE
);
3258 $res = $dbr->select( array( 'templatelinks' ),
3259 array( 'tl_namespace', 'tl_title' ),
3260 array( 'tl_from' => $id ),
3261 'Article:getUsedTemplates' );
3262 if ( false !== $res ) {
3263 if ( $dbr->numRows( $res ) ) {
3264 while ( $row = $dbr->fetchObject( $res ) ) {
3265 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3269 $dbr->freeResult( $res );
3274 * Returns a list of hidden categories this page is a member of.
3275 * Uses the page_props and categorylinks tables.
3277 * @return array Array of Title objects
3279 function getHiddenCategories() {
3281 $id = $this->mTitle
->getArticleID();
3286 $dbr = wfGetDB( DB_SLAVE
);
3287 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3289 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3290 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3291 'Article:getHiddenCategories' );
3292 if ( false !== $res ) {
3293 if ( $dbr->numRows( $res ) ) {
3294 while ( $row = $dbr->fetchObject( $res ) ) {
3295 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3299 $dbr->freeResult( $res );
3304 * Return an applicable autosummary if one exists for the given edit.
3305 * @param string $oldtext The previous text of the page.
3306 * @param string $newtext The submitted text of the page.
3307 * @param bitmask $flags A bitmask of flags submitted for the edit.
3308 * @return string An appropriate autosummary, or an empty string.
3310 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3311 # Decide what kind of autosummary is needed.
3313 # Redirect autosummaries
3314 $rt = Title
::newFromRedirect( $newtext );
3315 if( is_object( $rt ) ) {
3316 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3319 # New page autosummaries
3320 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3321 # If they're making a new article, give its text, truncated, in the summary.
3323 $truncatedtext = $wgContLang->truncate(
3324 str_replace("\n", ' ', $newtext),
3325 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3327 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3330 # Blanking autosummaries
3331 if( $oldtext != '' && $newtext == '' ) {
3332 return wfMsgForContent('autosumm-blank');
3333 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3334 # Removing more than 90% of the article
3336 $truncatedtext = $wgContLang->truncate(
3338 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3341 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3344 # If we reach this point, there's no applicable autosummary for our case, so our
3345 # autosummary is empty.
3350 * Add the primary page-view wikitext to the output buffer
3351 * Saves the text into the parser cache if possible.
3352 * Updates templatelinks if it is out of date.
3354 * @param string $text
3355 * @param bool $cache
3357 public function outputWikiText( $text, $cache = true ) {
3358 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3360 $popts = $wgOut->parserOptions();
3361 $popts->setTidy(true);
3362 $popts->enableLimitReport();
3363 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3364 $popts, true, true, $this->getRevIdFetched() );
3365 $popts->setTidy(false);
3366 $popts->enableLimitReport( false );
3367 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3368 $parserCache = ParserCache
::singleton();
3369 $parserCache->save( $parserOutput, $this, $wgUser );
3372 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3373 // templatelinks table may have become out of sync,
3374 // especially if using variable-based transclusions.
3375 // For paranoia, check if things have changed and if
3376 // so apply updates to the database. This will ensure
3377 // that cascaded protections apply as soon as the changes
3380 # Get templates from templatelinks
3381 $id = $this->mTitle
->getArticleID();
3383 $tlTemplates = array();
3385 $dbr = wfGetDB( DB_SLAVE
);
3386 $res = $dbr->select( array( 'templatelinks' ),
3387 array( 'tl_namespace', 'tl_title' ),
3388 array( 'tl_from' => $id ),
3389 'Article:getUsedTemplates' );
3393 if ( false !== $res ) {
3394 if ( $dbr->numRows( $res ) ) {
3395 while ( $row = $dbr->fetchObject( $res ) ) {
3396 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3401 # Get templates from parser output.
3402 $poTemplates_allns = $parserOutput->getTemplates();
3404 $poTemplates = array ();
3405 foreach ( $poTemplates_allns as $ns_templates ) {
3406 $poTemplates = array_merge( $poTemplates, $ns_templates );
3410 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3412 if ( count( $templates_diff ) > 0 ) {
3413 # Whee, link updates time.
3414 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3416 $dbw = wfGetDb( DB_MASTER
);
3425 $wgOut->addParserOutput( $parserOutput );
3429 * Update all the appropriate counts in the category table, given that
3430 * we've added the categories $added and deleted the categories $deleted.
3432 * @param $added array The names of categories that were added
3433 * @param $deleted array The names of categories that were deleted
3436 public function updateCategoryCounts( $added, $deleted ) {
3437 $ns = $this->mTitle
->getNamespace();
3438 $dbw = wfGetDB( DB_MASTER
);
3440 # First make sure the rows exist. If one of the "deleted" ones didn't
3441 # exist, we might legitimately not create it, but it's simpler to just
3442 # create it and then give it a negative value, since the value is bogus
3445 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3446 $insertCats = array_merge( $added, $deleted );
3447 if( !$insertCats ) {
3448 # Okay, nothing to do
3451 $insertRows = array();
3452 foreach( $insertCats as $cat ) {
3453 $insertRows[] = array( 'cat_title' => $cat );
3455 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3457 $addFields = array( 'cat_pages = cat_pages + 1' );
3458 $removeFields = array( 'cat_pages = cat_pages - 1' );
3459 if( $ns == NS_CATEGORY
) {
3460 $addFields[] = 'cat_subcats = cat_subcats + 1';
3461 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3462 } elseif( $ns == NS_IMAGE
) {
3463 $addFields[] = 'cat_files = cat_files + 1';
3464 $removeFields[] = 'cat_files = cat_files - 1';
3471 array( 'cat_title' => $added ),
3479 array( 'cat_title' => $deleted ),