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 = wfGetDB( DB_MASTER
);
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 = wfGetDB( DB_MASTER
);
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();
398 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
399 $this->mContent
= wfMsg( 'missing-article', $t, $d ) ;
402 $revision = Revision
::newFromId( $oldid );
403 if( is_null( $revision ) ) {
404 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
407 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
409 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
412 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
413 $this->loadPageData( $data );
415 if( !$this->mDataLoaded
) {
416 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
418 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
421 $this->loadPageData( $data );
423 $revision = Revision
::newFromId( $this->mLatest
);
424 if( is_null( $revision ) ) {
425 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
430 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
431 // We should instead work with the Revision object when we need it...
432 $this->mContent
= $revision->revText(); // Loads if user is allowed
434 $this->mUser
= $revision->getUser();
435 $this->mUserText
= $revision->getUserText();
436 $this->mComment
= $revision->getComment();
437 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
439 $this->mRevIdFetched
= $revision->getId();
440 $this->mContentLoaded
= true;
441 $this->mRevision
=& $revision;
443 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
445 return $this->mContent
;
449 * Read/write accessor to select FOR UPDATE
451 * @param $x Mixed: FIXME
453 function forUpdate( $x = NULL ) {
454 return wfSetVar( $this->mForUpdate
, $x );
458 * Get the database which should be used for reads
461 * @deprecated - just call wfGetDB( DB_MASTER ) instead
464 wfDeprecated( __METHOD__
);
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( wfGetDB( DB_MASTER
), $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 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
807 $text = wfMsg( 'missing-article', $t, $d );
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 # Only restrictions with the 'protect' right can cascade...
1839 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1840 foreach( $limit as $action => $restriction ) {
1841 # FIXME: can $restriction be an array or what? (same as fixme above)
1842 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1848 $cascade_description = '';
1850 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1854 $comment .= ": $reason";
1856 $comment .= " [$updated]";
1857 if ( $expiry_description && $protect )
1858 $comment .= "$expiry_description";
1860 $comment .= "$cascade_description";
1862 # Update restrictions table
1863 foreach( $limit as $action => $restrictions ) {
1864 if ($restrictions != '' ) {
1865 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1866 array( 'pr_page' => $id, 'pr_type' => $action
1867 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1868 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1870 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1871 'pr_type' => $action ), __METHOD__
);
1875 # Insert a null revision
1876 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1877 $nullRevId = $nullRevision->insertOn( $dbw );
1879 # Update page record
1880 $dbw->update( 'page',
1882 'page_touched' => $dbw->timestamp(),
1883 'page_restrictions' => '',
1884 'page_latest' => $nullRevId
1885 ), array( /* WHERE */
1887 ), 'Article::protect'
1890 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, false) );
1891 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1893 # Update the protection log
1894 $log = new LogPage( 'protect' );
1896 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
,
1897 trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1899 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1903 } # End "changed" check
1909 * Take an array of page restrictions and flatten it to a string
1910 * suitable for insertion into the page_restrictions field.
1911 * @param array $limit
1915 function flattenRestrictions( $limit ) {
1916 if( !is_array( $limit ) ) {
1917 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1921 foreach( $limit as $action => $restrictions ) {
1922 if( $restrictions != '' ) {
1923 $bits[] = "$action=$restrictions";
1926 return implode( ':', $bits );
1930 * Auto-generates a deletion reason
1931 * @param bool &$hasHistory Whether the page has a history
1933 public function generateReason(&$hasHistory)
1936 $dbw = wfGetDB(DB_MASTER
);
1937 // Get the last revision
1938 $rev = Revision
::newFromTitle($this->mTitle
);
1941 // Get the article's contents
1942 $contents = $rev->getText();
1944 // If the page is blank, use the text from the previous revision,
1945 // which can only be blank if there's a move/import/protect dummy revision involved
1948 $prev = $rev->getPrevious();
1951 $contents = $prev->getText();
1956 // Find out if there was only one contributor
1957 // Only scan the last 20 revisions
1959 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1960 array('LIMIT' => $limit));
1962 // This page has no revisions, which is very weird
1964 if($res->numRows() > 1)
1967 $hasHistory = false;
1968 $row = $dbw->fetchObject($res);
1969 $onlyAuthor = $row->rev_user_text
;
1970 // Try to find a second contributor
1971 while( $row = $dbw->fetchObject($res) ) {
1972 if($row->rev_user_text
!= $onlyAuthor) {
1973 $onlyAuthor = false;
1977 $dbw->freeResult($res);
1979 // Generate the summary with a '$1' placeholder
1981 // The current revision is blank and the one before is also
1982 // blank. It's just not our lucky day
1983 $reason = wfMsgForContent('exbeforeblank', '$1');
1986 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1988 $reason = wfMsgForContent('excontent', '$1');
1991 // Replace newlines with spaces to prevent uglyness
1992 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1993 // Calculate the maximum amount of chars to get
1994 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1995 $maxLength = 255 - (strlen($reason) - 2) - 3;
1996 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1997 // Remove possible unfinished links
1998 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1999 // Now replace the '$1' placeholder
2000 $reason = str_replace( '$1', $contents, $reason );
2006 * UI entry point for page deletion
2009 global $wgUser, $wgOut, $wgRequest;
2011 $confirm = $wgRequest->wasPosted() &&
2012 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2014 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2015 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2017 $reason = $this->DeleteReasonList
;
2019 if ( $reason != 'other' && $this->DeleteReason
!= '') {
2020 // Entry from drop down menu + additional comment
2021 $reason .= ': ' . $this->DeleteReason
;
2022 } elseif ( $reason == 'other' ) {
2023 $reason = $this->DeleteReason
;
2025 # Flag to hide all contents of the archived revisions
2026 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2028 # This code desperately needs to be totally rewritten
2030 # Read-only check...
2031 if ( wfReadOnly() ) {
2032 $wgOut->readOnlyPage();
2037 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2039 if (count($permission_errors)>0) {
2040 $wgOut->showPermissionsErrorPage( $permission_errors );
2044 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2046 # Better double-check that it hasn't been deleted yet!
2047 $dbw = wfGetDB( DB_MASTER
);
2048 $conds = $this->mTitle
->pageCond();
2049 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2050 if ( $latest === false ) {
2051 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2055 # Hack for big sites
2056 $bigHistory = $this->isBigDeletion();
2057 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2058 global $wgLang, $wgDeleteRevisionsLimit;
2059 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2060 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2065 $this->doDelete( $reason, $suppress );
2066 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2068 } elseif( $this->mTitle
->userIsWatching() ) {
2074 // Generate deletion reason
2075 $hasHistory = false;
2076 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2078 // If the page has a history, insert a warning
2079 if( $hasHistory && !$confirm ) {
2080 $skin=$wgUser->getSkin();
2081 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2083 global $wgLang, $wgDeleteRevisionsLimit;
2084 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2085 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2089 return $this->confirmDelete( '', $reason );
2093 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2095 function isBigDeletion() {
2096 global $wgDeleteRevisionsLimit;
2097 if( $wgDeleteRevisionsLimit ) {
2098 $revCount = $this->estimateRevisionCount();
2099 return $revCount > $wgDeleteRevisionsLimit;
2105 * @return int approximate revision count
2107 function estimateRevisionCount() {
2109 // For an exact count...
2110 //return $dbr->selectField( 'revision', 'COUNT(*)',
2111 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2112 return $dbr->estimateRowCount( 'revision', '*',
2113 array( 'rev_page' => $this->getId() ), __METHOD__
);
2117 * Get the last N authors
2118 * @param int $num Number of revisions to get
2119 * @param string $revLatest The latest rev_id, selected from the master (optional)
2120 * @return array Array of authors, duplicates not removed
2122 function getLastNAuthors( $num, $revLatest = 0 ) {
2123 wfProfileIn( __METHOD__
);
2125 // First try the slave
2126 // If that doesn't have the latest revision, try the master
2128 $db = wfGetDB( DB_SLAVE
);
2130 $res = $db->select( array( 'page', 'revision' ),
2131 array( 'rev_id', 'rev_user_text' ),
2133 'page_namespace' => $this->mTitle
->getNamespace(),
2134 'page_title' => $this->mTitle
->getDBkey(),
2135 'rev_page = page_id'
2136 ), __METHOD__
, $this->getSelectOptions( array(
2137 'ORDER BY' => 'rev_timestamp DESC',
2142 wfProfileOut( __METHOD__
);
2145 $row = $db->fetchObject( $res );
2146 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2147 $db = wfGetDB( DB_MASTER
);
2152 } while ( $continue );
2154 $authors = array( $row->rev_user_text
);
2155 while ( $row = $db->fetchObject( $res ) ) {
2156 $authors[] = $row->rev_user_text
;
2158 wfProfileOut( __METHOD__
);
2163 * Output deletion confirmation dialog
2164 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2165 * @param $reason string Prefilled reason
2167 function confirmDelete( $par, $reason ) {
2168 global $wgOut, $wgUser, $wgContLang;
2169 $align = $wgContLang->isRtl() ?
'left' : 'right';
2171 wfDebug( "Article::confirmDelete\n" );
2173 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2174 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2175 $wgOut->addWikiMsg( 'confirmdeletetext' );
2177 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2178 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2179 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2180 $suppress .= "</td></tr>";
2185 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2186 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2187 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2188 Xml
::openElement( 'table' ) .
2189 "<tr id=\"wpDeleteReasonListRow\">
2190 <td align='$align'>" .
2191 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2194 Xml
::listDropDown( 'wpDeleteReasonList',
2195 wfMsgForContent( 'deletereason-dropdown' ),
2196 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2199 <tr id=\"wpDeleteReasonRow\">
2200 <td align='$align'>" .
2201 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2204 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2210 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2217 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2220 Xml
::closeElement( 'table' ) .
2221 Xml
::closeElement( 'fieldset' ) .
2222 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2223 Xml
::closeElement( 'form' );
2225 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2226 $skin = $wgUser->getSkin();
2227 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2228 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2231 $wgOut->addHTML( $form );
2232 $this->showLogExtract( $wgOut );
2237 * Show relevant lines from the deletion log
2239 function showLogExtract( $out ) {
2240 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2241 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2246 * Perform a deletion and output success or failure messages
2248 function doDelete( $reason, $suppress = false ) {
2249 global $wgOut, $wgUser;
2250 wfDebug( __METHOD__
."\n" );
2252 $id = $this->getId();
2254 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2255 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2256 $deleted = $this->mTitle
->getPrefixedText();
2258 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2259 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2261 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2263 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2264 $wgOut->returnToMain( false );
2265 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2267 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2273 * Back-end article deletion
2274 * Deletes the article with database consistency, writes logs, purges caches
2277 function doDeleteArticle( $reason, $suppress = false ) {
2278 global $wgUseSquid, $wgDeferredUpdateList;
2279 global $wgUseTrackbacks;
2281 wfDebug( __METHOD__
."\n" );
2283 $dbw = wfGetDB( DB_MASTER
);
2284 $ns = $this->mTitle
->getNamespace();
2285 $t = $this->mTitle
->getDBkey();
2286 $id = $this->mTitle
->getArticleID();
2288 if ( $t == '' ||
$id == 0 ) {
2292 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2293 array_push( $wgDeferredUpdateList, $u );
2295 // Bitfields to further suppress the content
2298 // This should be 15...
2299 $bitfield |
= Revision
::DELETED_TEXT
;
2300 $bitfield |
= Revision
::DELETED_COMMENT
;
2301 $bitfield |
= Revision
::DELETED_USER
;
2302 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2304 $bitfield = 'rev_deleted';
2308 // For now, shunt the revision data into the archive table.
2309 // Text is *not* removed from the text table; bulk storage
2310 // is left intact to avoid breaking block-compression or
2311 // immutable storage schemes.
2313 // For backwards compatibility, note that some older archive
2314 // table entries will have ar_text and ar_flags fields still.
2316 // In the future, we may keep revisions and mark them with
2317 // the rev_deleted field, which is reserved for this purpose.
2318 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2320 'ar_namespace' => 'page_namespace',
2321 'ar_title' => 'page_title',
2322 'ar_comment' => 'rev_comment',
2323 'ar_user' => 'rev_user',
2324 'ar_user_text' => 'rev_user_text',
2325 'ar_timestamp' => 'rev_timestamp',
2326 'ar_minor_edit' => 'rev_minor_edit',
2327 'ar_rev_id' => 'rev_id',
2328 'ar_text_id' => 'rev_text_id',
2329 'ar_text' => '\'\'', // Be explicit to appease
2330 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2331 'ar_len' => 'rev_len',
2332 'ar_page_id' => 'page_id',
2333 'ar_deleted' => $bitfield
2336 'page_id = rev_page'
2340 # Delete restrictions for it
2341 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2343 # Fix category table counts
2345 $res = $dbw->select( 'categorylinks', 'cl_to',
2346 array( 'cl_from' => $id ), __METHOD__
);
2347 foreach( $res as $row ) {
2348 $cats []= $row->cl_to
;
2350 $this->updateCategoryCounts( array(), $cats );
2352 # Now that it's safely backed up, delete it
2353 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2354 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2360 # If using cascading deletes, we can skip some explicit deletes
2361 if ( !$dbw->cascadingDeletes() ) {
2362 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2364 if ($wgUseTrackbacks)
2365 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2367 # Delete outgoing links
2368 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2369 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2370 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2371 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2372 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2373 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2374 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2377 # If using cleanup triggers, we can skip some manual deletes
2378 if ( !$dbw->cleanupTriggers() ) {
2380 # Clean up recentchanges entries...
2381 $dbw->delete( 'recentchanges',
2382 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2388 Article
::onArticleDelete( $this->mTitle
);
2390 # Clear the cached article id so the interface doesn't act like we exist
2391 $this->mTitle
->resetArticleID( 0 );
2392 $this->mTitle
->mArticleID
= 0;
2394 # Log the deletion, if the page was suppressed, log it at Oversight instead
2395 $logtype = $suppress ?
'suppress' : 'delete';
2396 $log = new LogPage( $logtype );
2398 # Make sure logging got through
2399 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2405 * Roll back the most recent consecutive set of edits to a page
2406 * from the same user; fails if there are no eligible edits to
2407 * roll back to, e.g. user is the sole contributor. This function
2408 * performs permissions checks on $wgUser, then calls commitRollback()
2409 * to do the dirty work
2411 * @param string $fromP - Name of the user whose edits to rollback.
2412 * @param string $summary - Custom summary. Set to default summary if empty.
2413 * @param string $token - Rollback token.
2414 * @param bool $bot - If true, mark all reverted edits as bot.
2416 * @param array $resultDetails contains result-specific array of additional values
2417 * 'alreadyrolled' : 'current' (rev)
2418 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2420 * @return array of errors, each error formatted as
2421 * array(messagekey, param1, param2, ...).
2422 * On success, the array is empty. This array can also be passed to
2423 * OutputPage::showPermissionsErrorPage().
2425 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2427 $resultDetails = null;
2430 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2431 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2432 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2433 $errors[] = array( 'sessionfailure' );
2435 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2436 $errors[] = array( 'actionthrottledtext' );
2438 # If there were errors, bail out now
2442 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2446 * Backend implementation of doRollback(), please refer there for parameter
2447 * and return value documentation
2449 * NOTE: This function does NOT check ANY permissions, it just commits the
2450 * rollback to the DB Therefore, you should only call this function direct-
2451 * ly if you want to use custom permissions checks. If you don't, use
2452 * doRollback() instead.
2454 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2455 global $wgUseRCPatrol, $wgUser, $wgLang;
2456 $dbw = wfGetDB( DB_MASTER
);
2458 if( wfReadOnly() ) {
2459 return array( array( 'readonlytext' ) );
2462 # Get the last editor
2463 $current = Revision
::newFromTitle( $this->mTitle
);
2464 if( is_null( $current ) ) {
2465 # Something wrong... no page?
2466 return array(array('notanarticle'));
2469 $from = str_replace( '_', ' ', $fromP );
2470 if( $from != $current->getUserText() ) {
2471 $resultDetails = array( 'current' => $current );
2472 return array(array('alreadyrolled',
2473 htmlspecialchars($this->mTitle
->getPrefixedText()),
2474 htmlspecialchars($fromP),
2475 htmlspecialchars($current->getUserText())
2479 # Get the last edit not by this guy
2480 $user = intval( $current->getUser() );
2481 $user_text = $dbw->addQuotes( $current->getUserText() );
2482 $s = $dbw->selectRow( 'revision',
2483 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2484 array( 'rev_page' => $current->getPage(),
2485 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2487 array( 'USE INDEX' => 'page_timestamp',
2488 'ORDER BY' => 'rev_timestamp DESC' )
2490 if( $s === false ) {
2491 # No one else ever edited this page
2492 return array(array('cantrollback'));
2493 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2494 # Only admins can see this text
2495 return array(array('notvisiblerev'));
2499 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2500 # Mark all reverted edits as bot
2503 if ( $wgUseRCPatrol ) {
2504 # Mark all reverted edits as patrolled
2505 $set['rc_patrolled'] = 1;
2509 $dbw->update( 'recentchanges', $set,
2511 'rc_cur_id' => $current->getPage(),
2512 'rc_user_text' => $current->getUserText(),
2513 "rc_timestamp > '{$s->rev_timestamp}'",
2518 # Generate the edit summary if necessary
2519 $target = Revision
::newFromId( $s->rev_id
);
2520 if( empty( $summary ) ){
2521 $summary = wfMsgForContent( 'revertpage' );
2524 # Allow the custom summary to use the same args as the default message
2526 $target->getUserText(), $from, $s->rev_id
,
2527 $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2528 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2530 $summary = wfMsgReplaceArgs( $summary, $args );
2533 $flags = EDIT_UPDATE
;
2535 if ($wgUser->isAllowed('minoredit'))
2536 $flags |
= EDIT_MINOR
;
2538 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2539 $flags |
= EDIT_FORCE_BOT
;
2540 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2542 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2544 $resultDetails = array(
2545 'summary' => $summary,
2546 'current' => $current,
2547 'target' => $target,
2553 * User interface for rollback operations
2555 function rollback() {
2556 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2559 $result = $this->doRollback(
2560 $wgRequest->getVal( 'from' ),
2561 $wgRequest->getText( 'summary' ),
2562 $wgRequest->getVal( 'token' ),
2563 $wgRequest->getBool( 'bot' ),
2567 if( in_array( array( 'blocked' ), $result ) ) {
2568 $wgOut->blockedPage();
2571 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2572 $wgOut->rateLimited();
2575 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2576 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2577 $errArray = $result[0];
2578 $errMsg = array_shift( $errArray );
2579 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2580 if( isset( $details['current'] ) ){
2581 $current = $details['current'];
2582 if( $current->getComment() != '' ) {
2583 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2588 # Display permissions errors before read-only message -- there's no
2589 # point in misleading the user into thinking the inability to rollback
2590 # is only temporary.
2591 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2592 # array_diff is completely broken for arrays of arrays, sigh. Re-
2593 # move any 'readonlytext' error manually.
2595 foreach( $result as $error ) {
2596 if( $error != array( 'readonlytext' ) ) {
2600 $wgOut->showPermissionsErrorPage( $out );
2603 if( $result == array( array('readonlytext') ) ) {
2604 $wgOut->readOnlyPage();
2608 $current = $details['current'];
2609 $target = $details['target'];
2610 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2611 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2612 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2613 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2614 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2615 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2616 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2617 $wgOut->returnToMain( false, $this->mTitle
);
2619 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2620 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), 'next', false, true );
2621 $de->showDiff( '', '' );
2627 * Do standard deferred updates after page view
2630 function viewUpdates() {
2631 global $wgDeferredUpdateList, $wgUser;
2633 if ( 0 != $this->getID() ) {
2634 # Don't update page view counters on views from bot users (bug 14044)
2635 global $wgDisableCounters;
2636 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2637 Article
::incViewCount( $this->getID() );
2638 $u = new SiteStatsUpdate( 1, 0, 0 );
2639 array_push( $wgDeferredUpdateList, $u );
2643 # Update newtalk / watchlist notification status
2644 $wgUser->clearNotification( $this->mTitle
);
2648 * Prepare text which is about to be saved.
2649 * Returns a stdclass with source, pst and output members
2651 function prepareTextForEdit( $text, $revid=null ) {
2652 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2654 return $this->mPreparedEdit
;
2657 $edit = (object)array();
2658 $edit->revid
= $revid;
2659 $edit->newText
= $text;
2660 $edit->pst
= $this->preSaveTransform( $text );
2661 $options = new ParserOptions
;
2662 $options->setTidy( true );
2663 $options->enableLimitReport();
2664 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2665 $edit->oldText
= $this->getContent();
2666 $this->mPreparedEdit
= $edit;
2671 * Do standard deferred updates after page edit.
2672 * Update links tables, site stats, search index and message cache.
2673 * Every 100th edit, prune the recent changes table.
2676 * @param $text New text of the article
2677 * @param $summary Edit summary
2678 * @param $minoredit Minor edit
2679 * @param $timestamp_of_pagechange Timestamp associated with the page change
2680 * @param $newid rev_id value of the new revision
2681 * @param $changed Whether or not the content actually changed
2683 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2684 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2686 wfProfileIn( __METHOD__
);
2689 # Be careful not to double-PST: $text is usually already PST-ed once
2690 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2691 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2692 $editInfo = $this->prepareTextForEdit( $text, $newid );
2694 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2695 $editInfo = $this->mPreparedEdit
;
2698 # Save it to the parser cache
2699 if ( $wgEnableParserCache ) {
2700 $parserCache = ParserCache
::singleton();
2701 $parserCache->save( $editInfo->output
, $this, $wgUser );
2704 # Update the links tables
2705 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2708 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2709 if ( 0 == mt_rand( 0, 99 ) ) {
2710 // Flush old entries from the `recentchanges` table; we do this on
2711 // random requests so as to avoid an increase in writes for no good reason
2713 $dbw = wfGetDB( DB_MASTER
);
2714 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2715 $recentchanges = $dbw->tableName( 'recentchanges' );
2716 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2717 $dbw->query( $sql );
2721 $id = $this->getID();
2722 $title = $this->mTitle
->getPrefixedDBkey();
2723 $shortTitle = $this->mTitle
->getDBkey();
2726 wfProfileOut( __METHOD__
);
2730 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2731 array_push( $wgDeferredUpdateList, $u );
2732 $u = new SearchUpdate( $id, $title, $text );
2733 array_push( $wgDeferredUpdateList, $u );
2735 # If this is another user's talk page, update newtalk
2736 # Don't do this if $changed = false otherwise some idiot can null-edit a
2737 # load of user talk pages and piss people off, nor if it's a minor edit
2738 # by a properly-flagged bot.
2739 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2740 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2741 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2742 $other = User
::newFromName( $shortTitle );
2743 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2744 // An anonymous user
2745 $other = new User();
2746 $other->setName( $shortTitle );
2749 $other->setNewtalk( true );
2754 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2755 $wgMessageCache->replace( $shortTitle, $text );
2758 wfProfileOut( __METHOD__
);
2762 * Perform article updates on a special page creation.
2764 * @param Revision $rev
2766 * @todo This is a shitty interface function. Kill it and replace the
2767 * other shitty functions like editUpdates and such so it's not needed
2770 function createUpdates( $rev ) {
2771 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2772 $this->mTotalAdjustment
= 1;
2773 $this->editUpdates( $rev->getText(), $rev->getComment(),
2774 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2778 * Generate the navigation links when browsing through an article revisions
2779 * It shows the information as:
2780 * Revision as of \<date\>; view current revision
2781 * \<- Previous version | Next Version -\>
2784 * @param string $oldid Revision ID of this article revision
2786 function setOldSubtitle( $oldid=0 ) {
2787 global $wgLang, $wgOut, $wgUser;
2789 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2793 $revision = Revision
::newFromId( $oldid );
2795 $current = ( $oldid == $this->mLatest
);
2796 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2797 $sk = $wgUser->getSkin();
2799 ?
wfMsg( 'currentrevisionlink' )
2800 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2803 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2804 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2806 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2807 : wfMsg( 'previousrevision' );
2809 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2811 $nextlink = $current
2812 ?
wfMsg( 'nextrevision' )
2813 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2814 $nextdiff = $current
2816 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2819 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2820 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2821 if( $revision->isCurrent() ) {
2822 // We don't handle top deleted edits too well
2823 $cdel = wfMsgHtml('rev-delundel');
2824 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2825 // If revision was hidden from sysops
2826 $cdel = wfMsgHtml('rev-delundel');
2828 $cdel = $sk->makeKnownLinkObj( $revdel,
2829 wfMsgHtml('rev-delundel'),
2830 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2831 '&oldid=' . urlencode( $oldid ) );
2832 // Bolden oversighted content
2833 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2834 $cdel = "<strong>$cdel</strong>";
2836 $cdel = "(<small>$cdel</small>) ";
2838 # Show user links if allowed to see them. Normally they
2839 # are hidden regardless, but since we can already see the text here...
2840 $userlinks = $sk->revUserTools( $revision, false );
2842 $m = wfMsg( 'revision-info-current' );
2843 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2844 ?
'revision-info-current'
2847 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2849 "\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";
2850 $wgOut->setSubtitle( $r );
2854 * This function is called right before saving the wikitext,
2855 * so we can do things like signatures and links-in-context.
2857 * @param string $text
2859 function preSaveTransform( $text ) {
2860 global $wgParser, $wgUser;
2861 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2864 /* Caching functions */
2867 * checkLastModified returns true if it has taken care of all
2868 * output to the client that is necessary for this request.
2869 * (that is, it has sent a cached version of the page)
2871 function tryFileCache() {
2872 static $called = false;
2874 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2878 if($this->isFileCacheable()) {
2879 $touched = $this->mTouched
;
2880 $cache = new HTMLFileCache( $this->mTitle
);
2881 if($cache->isFileCacheGood( $touched )) {
2882 wfDebug( "Article::tryFileCache(): about to load file\n" );
2883 $cache->loadFromFileCache();
2886 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2887 ob_start( array(&$cache, 'saveToFileCache' ) );
2890 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2895 * Check if the page can be cached
2898 function isFileCacheable() {
2899 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2900 $action = $wgRequest->getVal( 'action' );
2901 $oldid = $wgRequest->getVal( 'oldid' );
2902 $diff = $wgRequest->getVal( 'diff' );
2903 $redirect = $wgRequest->getVal( 'redirect' );
2904 $printable = $wgRequest->getVal( 'printable' );
2905 $page = $wgRequest->getVal( 'page' );
2907 //check for non-standard user language; this covers uselang,
2908 //and extensions for auto-detecting user language.
2909 $ulang = $wgLang->getCode();
2910 $clang = $wgContLang->getCode();
2912 $cacheable = $wgUseFileCache
2913 && (!$wgShowIPinHeader)
2914 && ($this->getID() != 0)
2915 && ($wgUser->isAnon())
2916 && (!$wgUser->getNewtalk())
2917 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2918 && (empty( $action ) ||
$action == 'view')
2921 && (!isset($redirect))
2922 && (!isset($printable))
2924 && (!$this->mRedirectedFrom
)
2925 && ($ulang === $clang);
2928 //extension may have reason to disable file caching on some pages.
2929 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2936 * Loads page_touched and returns a value indicating if it should be used
2939 function checkTouched() {
2940 if( !$this->mDataLoaded
) {
2941 $this->loadPageData();
2943 return !$this->mIsRedirect
;
2947 * Get the page_touched field
2949 function getTouched() {
2950 # Ensure that page data has been loaded
2951 if( !$this->mDataLoaded
) {
2952 $this->loadPageData();
2954 return $this->mTouched
;
2958 * Get the page_latest field
2960 function getLatest() {
2961 if ( !$this->mDataLoaded
) {
2962 $this->loadPageData();
2964 return $this->mLatest
;
2968 * Edit an article without doing all that other stuff
2969 * The article must already exist; link tables etc
2970 * are not updated, caches are not flushed.
2972 * @param string $text text submitted
2973 * @param string $comment comment submitted
2974 * @param bool $minor whereas it's a minor modification
2976 function quickEdit( $text, $comment = '', $minor = 0 ) {
2977 wfProfileIn( __METHOD__
);
2979 $dbw = wfGetDB( DB_MASTER
);
2981 $revision = new Revision( array(
2982 'page' => $this->getId(),
2984 'comment' => $comment,
2985 'minor_edit' => $minor ?
1 : 0,
2987 $revision->insertOn( $dbw );
2988 $this->updateRevisionOn( $dbw, $revision );
2991 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
2993 wfProfileOut( __METHOD__
);
2997 * Used to increment the view counter
3000 * @param integer $id article id
3002 function incViewCount( $id ) {
3003 $id = intval( $id );
3004 global $wgHitcounterUpdateFreq, $wgDBtype;
3006 $dbw = wfGetDB( DB_MASTER
);
3007 $pageTable = $dbw->tableName( 'page' );
3008 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3009 $acchitsTable = $dbw->tableName( 'acchits' );
3011 if( $wgHitcounterUpdateFreq <= 1 ) {
3012 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3016 # Not important enough to warrant an error page in case of failure
3017 $oldignore = $dbw->ignoreErrors( true );
3019 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3021 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
3022 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3023 # Most of the time (or on SQL errors), skip row count check
3024 $dbw->ignoreErrors( $oldignore );
3028 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3029 $row = $dbw->fetchObject( $res );
3030 $rown = intval( $row->n
);
3031 if( $rown >= $wgHitcounterUpdateFreq ){
3032 wfProfileIn( 'Article::incViewCount-collect' );
3033 $old_user_abort = ignore_user_abort( true );
3035 if ($wgDBtype == 'mysql')
3036 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3037 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
3038 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3039 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3041 $dbw->query("DELETE FROM $hitcounterTable");
3042 if ($wgDBtype == 'mysql') {
3043 $dbw->query('UNLOCK TABLES');
3044 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3045 'WHERE page_id = hc_id');
3048 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3049 "FROM $acchitsTable WHERE page_id = hc_id");
3051 $dbw->query("DROP TABLE $acchitsTable");
3053 ignore_user_abort( $old_user_abort );
3054 wfProfileOut( 'Article::incViewCount-collect' );
3056 $dbw->ignoreErrors( $oldignore );
3060 * The onArticle*() functions are supposed to be a kind of hooks
3061 * which should be called whenever any of the specified actions
3064 * This is a good place to put code to clear caches, for instance.
3066 * This is called on page move and undelete, as well as edit
3068 * @param $title_obj a title object
3071 static function onArticleCreate($title) {
3072 # The talk page isn't in the regular link tables, so we need to update manually:
3073 if ( $title->isTalkPage() ) {
3074 $other = $title->getSubjectPage();
3076 $other = $title->getTalkPage();
3078 $other->invalidateCache();
3079 $other->purgeSquid();
3081 $title->touchLinks();
3082 $title->purgeSquid();
3083 $title->deleteTitleProtection();
3086 static function onArticleDelete( $title ) {
3087 global $wgUseFileCache, $wgMessageCache;
3089 // Update existence markers on article/talk tabs...
3090 if( $title->isTalkPage() ) {
3091 $other = $title->getSubjectPage();
3093 $other = $title->getTalkPage();
3095 $other->invalidateCache();
3096 $other->purgeSquid();
3098 $title->touchLinks();
3099 $title->purgeSquid();
3102 if ( $wgUseFileCache ) {
3103 $cm = new HTMLFileCache( $title );
3104 @unlink
( $cm->fileCacheName() );
3108 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3109 $wgMessageCache->replace( $title->getDBkey(), false );
3112 if( $title->getNamespace() == NS_IMAGE
) {
3113 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3114 $update->doUpdate();
3117 if( $title->getNamespace() == NS_USER_TALK
) {
3118 $user = User
::newFromName( $title->getText(), false );
3119 $user->setNewtalk( false );
3124 * Purge caches on page update etc
3126 static function onArticleEdit( $title ) {
3127 global $wgDeferredUpdateList, $wgUseFileCache;
3129 // Invalidate caches of articles which include this page
3130 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3132 // Invalidate the caches of all pages which redirect here
3133 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3135 # Purge squid for this page only
3136 $title->purgeSquid();
3139 if ( $wgUseFileCache ) {
3140 $cm = new HTMLFileCache( $title );
3141 @unlink
( $cm->fileCacheName() );
3148 * Overriden by ImagePage class, only present here to avoid a fatal error
3149 * Called for ?action=revert
3151 public function revert(){
3153 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3157 * Info about this page
3158 * Called for ?action=info when $wgAllowPageInfo is on.
3163 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3165 if ( !$wgAllowPageInfo ) {
3166 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3170 $page = $this->mTitle
->getSubjectPage();
3172 $wgOut->setPagetitle( $page->getPrefixedText() );
3173 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3174 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3176 if( !$this->mTitle
->exists() ) {
3177 $wgOut->addHtml( '<div class="noarticletext">' );
3178 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3179 // This doesn't quite make sense; the user is asking for
3180 // information about the _page_, not the message... -- RC
3181 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3183 $msg = $wgUser->isLoggedIn()
3185 : 'noarticletextanon';
3186 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3188 $wgOut->addHtml( '</div>' );
3190 $dbr = wfGetDB( DB_SLAVE
);
3192 'wl_title' => $page->getDBkey(),
3193 'wl_namespace' => $page->getNamespace() );
3194 $numwatchers = $dbr->selectField(
3199 $this->getSelectOptions() );
3201 $pageInfo = $this->pageCountInfo( $page );
3202 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3204 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3205 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3207 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3209 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3211 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3213 $wgOut->addHTML( '</ul>' );
3219 * Return the total number of edits and number of unique editors
3220 * on a given page. If page does not exist, returns false.
3222 * @param Title $title
3226 function pageCountInfo( $title ) {
3227 $id = $title->getArticleId();
3232 $dbr = wfGetDB( DB_SLAVE
);
3234 $rev_clause = array( 'rev_page' => $id );
3236 $edits = $dbr->selectField(
3241 $this->getSelectOptions() );
3243 $authors = $dbr->selectField(
3245 'COUNT(DISTINCT rev_user_text)',
3248 $this->getSelectOptions() );
3250 return array( 'edits' => $edits, 'authors' => $authors );
3254 * Return a list of templates used by this article.
3255 * Uses the templatelinks table
3257 * @return array Array of Title objects
3259 function getUsedTemplates() {
3261 $id = $this->mTitle
->getArticleID();
3266 $dbr = wfGetDB( DB_SLAVE
);
3267 $res = $dbr->select( array( 'templatelinks' ),
3268 array( 'tl_namespace', 'tl_title' ),
3269 array( 'tl_from' => $id ),
3270 'Article:getUsedTemplates' );
3271 if ( false !== $res ) {
3272 if ( $dbr->numRows( $res ) ) {
3273 while ( $row = $dbr->fetchObject( $res ) ) {
3274 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3278 $dbr->freeResult( $res );
3283 * Returns a list of hidden categories this page is a member of.
3284 * Uses the page_props and categorylinks tables.
3286 * @return array Array of Title objects
3288 function getHiddenCategories() {
3290 $id = $this->mTitle
->getArticleID();
3295 $dbr = wfGetDB( DB_SLAVE
);
3296 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3298 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3299 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3300 'Article:getHiddenCategories' );
3301 if ( false !== $res ) {
3302 if ( $dbr->numRows( $res ) ) {
3303 while ( $row = $dbr->fetchObject( $res ) ) {
3304 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3308 $dbr->freeResult( $res );
3313 * Return an applicable autosummary if one exists for the given edit.
3314 * @param string $oldtext The previous text of the page.
3315 * @param string $newtext The submitted text of the page.
3316 * @param bitmask $flags A bitmask of flags submitted for the edit.
3317 * @return string An appropriate autosummary, or an empty string.
3319 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3320 # Decide what kind of autosummary is needed.
3322 # Redirect autosummaries
3323 $rt = Title
::newFromRedirect( $newtext );
3324 if( is_object( $rt ) ) {
3325 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3328 # New page autosummaries
3329 if( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3330 # If they're making a new article, give its text, truncated, in the summary.
3332 $truncatedtext = $wgContLang->truncate(
3333 str_replace("\n", ' ', $newtext),
3334 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3336 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3339 # Blanking autosummaries
3340 if( $oldtext != '' && $newtext == '' ) {
3341 return wfMsgForContent('autosumm-blank');
3342 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3343 # Removing more than 90% of the article
3345 $truncatedtext = $wgContLang->truncate(
3347 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3350 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3353 # If we reach this point, there's no applicable autosummary for our case, so our
3354 # autosummary is empty.
3359 * Add the primary page-view wikitext to the output buffer
3360 * Saves the text into the parser cache if possible.
3361 * Updates templatelinks if it is out of date.
3363 * @param string $text
3364 * @param bool $cache
3366 public function outputWikiText( $text, $cache = true ) {
3367 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3369 $popts = $wgOut->parserOptions();
3370 $popts->setTidy(true);
3371 $popts->enableLimitReport();
3372 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3373 $popts, true, true, $this->getRevIdFetched() );
3374 $popts->setTidy(false);
3375 $popts->enableLimitReport( false );
3376 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3377 $parserCache = ParserCache
::singleton();
3378 $parserCache->save( $parserOutput, $this, $wgUser );
3381 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3382 // templatelinks table may have become out of sync,
3383 // especially if using variable-based transclusions.
3384 // For paranoia, check if things have changed and if
3385 // so apply updates to the database. This will ensure
3386 // that cascaded protections apply as soon as the changes
3389 # Get templates from templatelinks
3390 $id = $this->mTitle
->getArticleID();
3392 $tlTemplates = array();
3394 $dbr = wfGetDB( DB_SLAVE
);
3395 $res = $dbr->select( array( 'templatelinks' ),
3396 array( 'tl_namespace', 'tl_title' ),
3397 array( 'tl_from' => $id ),
3398 'Article:getUsedTemplates' );
3402 if ( false !== $res ) {
3403 if ( $dbr->numRows( $res ) ) {
3404 while ( $row = $dbr->fetchObject( $res ) ) {
3405 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3410 # Get templates from parser output.
3411 $poTemplates_allns = $parserOutput->getTemplates();
3413 $poTemplates = array ();
3414 foreach ( $poTemplates_allns as $ns_templates ) {
3415 $poTemplates = array_merge( $poTemplates, $ns_templates );
3419 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3421 if ( count( $templates_diff ) > 0 ) {
3422 # Whee, link updates time.
3423 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3425 $dbw = wfGetDb( DB_MASTER
);
3434 $wgOut->addParserOutput( $parserOutput );
3438 * Update all the appropriate counts in the category table, given that
3439 * we've added the categories $added and deleted the categories $deleted.
3441 * @param $added array The names of categories that were added
3442 * @param $deleted array The names of categories that were deleted
3445 public function updateCategoryCounts( $added, $deleted ) {
3446 $ns = $this->mTitle
->getNamespace();
3447 $dbw = wfGetDB( DB_MASTER
);
3449 # First make sure the rows exist. If one of the "deleted" ones didn't
3450 # exist, we might legitimately not create it, but it's simpler to just
3451 # create it and then give it a negative value, since the value is bogus
3454 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3455 $insertCats = array_merge( $added, $deleted );
3456 if( !$insertCats ) {
3457 # Okay, nothing to do
3460 $insertRows = array();
3461 foreach( $insertCats as $cat ) {
3462 $insertRows[] = array( 'cat_title' => $cat );
3464 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3466 $addFields = array( 'cat_pages = cat_pages + 1' );
3467 $removeFields = array( 'cat_pages = cat_pages - 1' );
3468 if( $ns == NS_CATEGORY
) {
3469 $addFields[] = 'cat_subcats = cat_subcats + 1';
3470 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3471 } elseif( $ns == NS_IMAGE
) {
3472 $addFields[] = 'cat_files = cat_files + 1';
3473 $removeFields[] = 'cat_files = cat_files - 1';
3480 array( 'cat_title' => $added ),
3488 array( 'cat_title' => $deleted ),