7 * Class representing a MediaWiki article and history.
9 * See design.txt for an overview.
10 * Note: edit user interface and cache support functions have been
11 * moved to separate EditPage and HTMLFileCache classes.
20 var $mContentLoaded; //!<
23 var $mGoodAdjustment; //!<
27 var $mRedirectedFrom; //!<
28 var $mRedirectUrl; //!<
29 var $mRevIdFetched; //!<
33 var $mTotalAdjustment; //!<
37 var $mRedirectTarget; //!<
41 * Constructor and clear the article
42 * @param $title Reference to a Title object.
43 * @param $oldId Integer revision ID, null to fetch from request, zero for current
45 function __construct( Title
$title, $oldId = null ) {
46 $this->mTitle
=& $title;
47 $this->mOldId
= $oldId;
52 * Tell the page view functions that this view was redirected
53 * from another page on the wiki.
54 * @param $from Title object.
56 function setRedirectedFrom( $from ) {
57 $this->mRedirectedFrom
= $from;
61 * If this page is a redirect, get its target
63 * The target will be fetched from the redirect table if possible.
64 * If this page doesn't have an entry there, call insertRedirect()
65 * @return mixed Title object, or null if this page is not a redirect
67 public function getRedirectTarget() {
68 if(!$this->mTitle ||
!$this->mTitle
->isRedirect())
70 if(!is_null($this->mRedirectTarget
))
71 return $this->mRedirectTarget
;
73 # Query the redirect table
74 $dbr = wfGetDb(DB_SLAVE
);
75 $res = $dbr->select('redirect',
76 array('rd_namespace', 'rd_title'),
77 array('rd_from' => $this->getID()),
80 $row = $dbr->fetchObject($res);
82 return $this->mRedirectTarget
= Title
::makeTitle($row->rd_namespace
, $row->rd_title
);
84 # This page doesn't have an entry in the redirect table
85 return $this->mRedirectTarget
= $this->insertRedirect();
89 * Insert an entry for this page into the redirect table.
91 * Don't call this function directly unless you know what you're doing.
92 * @return Title object
94 public function insertRedirect() {
95 $retval = Title
::newFromRedirect($this->getContent());
98 $dbw = wfGetDb(DB_MASTER
);
99 $dbw->insert('redirect', array(
100 'rd_from' => $this->getID(),
101 'rd_namespace' => $retval->getNamespace(),
102 'rd_title' => $retval->getDBKey()
108 * @return mixed false, Title of in-wiki target, or string with URL
110 function followRedirect() {
111 $rt = $this->getRedirectTarget();
113 # process if title object is valid and not special:userlogout
115 if( $rt->getInterwiki() != '' ) {
116 if( $rt->isLocal() ) {
117 // Offsite wikis need an HTTP redirect.
119 // This can be hard to reverse and may produce loops,
120 // so they may be disabled in the site configuration.
122 $source = $this->mTitle
->getFullURL( 'redirect=no' );
123 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
126 if( $rt->getNamespace() == NS_SPECIAL
) {
127 // Gotta handle redirects to special pages differently:
128 // Fill the HTTP response "Location" header and ignore
129 // the rest of the page we're on.
131 // This can be hard to reverse, so they may be disabled.
133 if( $rt->isSpecial( 'Userlogout' ) ) {
136 return $rt->getFullURL();
143 // No or invalid redirect
148 * get the title object of the article
150 function getTitle() {
151 return $this->mTitle
;
159 $this->mDataLoaded
= false;
160 $this->mContentLoaded
= false;
162 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
163 $this->mRedirectedFrom
= null; # Title object if set
164 $this->mRedirectTarget
= null; # Title object if set
166 $this->mTimestamp
= $this->mComment
= '';
167 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
168 $this->mTouched
= '19700101000000';
169 $this->mForUpdate
= false;
170 $this->mIsRedirect
= false;
171 $this->mRevIdFetched
= 0;
172 $this->mRedirectUrl
= false;
173 $this->mLatest
= false;
174 $this->mPreparedEdit
= false;
178 * Note that getContent/loadContent do not follow redirects anymore.
179 * If you need to fetch redirectable content easily, try
180 * the shortcut in Article::followContent()
182 * @todo There are still side-effects in this!
183 * In general, you should use the Revision class, not Article,
184 * to fetch text for purposes other than page views.
186 * @return Return the text of this revision
188 function getContent() {
189 global $wgUser, $wgOut, $wgMessageCache;
191 wfProfileIn( __METHOD__
);
193 if ( 0 == $this->getID() ) {
194 wfProfileOut( __METHOD__
);
195 $wgOut->setRobotpolicy( 'noindex,nofollow' );
197 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
198 $wgMessageCache->loadAllMessages();
199 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
201 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
204 return "<div class='noarticletext'>\n$ret\n</div>";
206 $this->loadContent();
207 wfProfileOut( __METHOD__
);
208 return $this->mContent
;
213 * This function returns the text of a section, specified by a number ($section).
214 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
215 * the first section before any such heading (section 0).
217 * If a section contains subsections, these are also returned.
219 * @param $text String: text to look in
220 * @param $section Integer: section number
221 * @return string text of the requested section
224 function getSection($text,$section) {
226 return $wgParser->getSection( $text, $section );
230 * @return int The oldid of the article that is to be shown, 0 for the
233 function getOldID() {
234 if ( is_null( $this->mOldId
) ) {
235 $this->mOldId
= $this->getOldIDFromRequest();
237 return $this->mOldId
;
241 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
243 * @return int The old id for the request
245 function getOldIDFromRequest() {
247 $this->mRedirectUrl
= false;
248 $oldid = $wgRequest->getVal( 'oldid' );
249 if ( isset( $oldid ) ) {
250 $oldid = intval( $oldid );
251 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
252 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
256 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
258 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
259 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
277 * Load the revision (including text) into this object
279 function loadContent() {
280 if ( $this->mContentLoaded
) return;
283 $oldid = $this->getOldID();
285 # Pre-fill content with error message so that if something
286 # fails we'll have something telling us what we intended.
287 $this->mOldId
= $oldid;
288 $this->fetchContent( $oldid );
293 * Fetch a page record with the given conditions
294 * @param Database $dbr
295 * @param array $conditions
298 function pageData( $dbr, $conditions ) {
312 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
313 $row = $dbr->selectRow(
319 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
324 * @param Database $dbr
325 * @param Title $title
327 function pageDataFromTitle( $dbr, $title ) {
328 return $this->pageData( $dbr, array(
329 'page_namespace' => $title->getNamespace(),
330 'page_title' => $title->getDBkey() ) );
334 * @param Database $dbr
337 function pageDataFromId( $dbr, $id ) {
338 return $this->pageData( $dbr, array( 'page_id' => $id ) );
342 * Set the general counter, title etc data loaded from
345 * @param object $data
348 function loadPageData( $data = 'fromdb' ) {
349 if ( $data === 'fromdb' ) {
350 $dbr = $this->getDB();
351 $data = $this->pageDataFromId( $dbr, $this->getId() );
354 $lc = LinkCache
::singleton();
356 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
358 $this->mTitle
->mArticleID
= $data->page_id
;
360 # Old-fashioned restrictions.
361 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
363 $this->mCounter
= $data->page_counter
;
364 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
365 $this->mIsRedirect
= $data->page_is_redirect
;
366 $this->mLatest
= $data->page_latest
;
368 if ( is_object( $this->mTitle
) ) {
369 $lc->addBadLinkObj( $this->mTitle
);
371 $this->mTitle
->mArticleID
= 0;
374 $this->mDataLoaded
= true;
378 * Get text of an article from database
379 * Does *NOT* follow redirects.
380 * @param int $oldid 0 for whatever the latest revision is
383 function fetchContent( $oldid = 0 ) {
384 if ( $this->mContentLoaded
) {
385 return $this->mContent
;
388 $dbr = $this->getDB();
390 # Pre-fill content with error message so that if something
391 # fails we'll have something telling us what we intended.
392 $t = $this->mTitle
->getPrefixedText();
394 $t .= ',oldid='.$oldid;
396 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
399 $revision = Revision
::newFromId( $oldid );
400 if( is_null( $revision ) ) {
401 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
404 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
406 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
409 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
410 $this->loadPageData( $data );
412 if( !$this->mDataLoaded
) {
413 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
415 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
418 $this->loadPageData( $data );
420 $revision = Revision
::newFromId( $this->mLatest
);
421 if( is_null( $revision ) ) {
422 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
427 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
428 // We should instead work with the Revision object when we need it...
429 $this->mContent
= $revision->revText(); // Loads if user is allowed
431 $this->mUser
= $revision->getUser();
432 $this->mUserText
= $revision->getUserText();
433 $this->mComment
= $revision->getComment();
434 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
436 $this->mRevIdFetched
= $revision->getID();
437 $this->mContentLoaded
= true;
438 $this->mRevision
=& $revision;
440 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
442 return $this->mContent
;
446 * Read/write accessor to select FOR UPDATE
448 * @param $x Mixed: FIXME
450 function forUpdate( $x = NULL ) {
451 return wfSetVar( $this->mForUpdate
, $x );
455 * Get the database which should be used for reads
460 return wfGetDB( DB_MASTER
);
464 * Get options for all SELECT statements
466 * @param $options Array: an optional options array which'll be appended to
468 * @return Array: options
470 function getSelectOptions( $options = '' ) {
471 if ( $this->mForUpdate
) {
472 if ( is_array( $options ) ) {
473 $options[] = 'FOR UPDATE';
475 $options = 'FOR UPDATE';
482 * @return int Page ID
485 if( $this->mTitle
) {
486 return $this->mTitle
->getArticleID();
493 * @return bool Whether or not the page exists in the database
496 return $this->getId() != 0;
500 * @return int The view count for the page
502 function getCount() {
503 if ( -1 == $this->mCounter
) {
504 $id = $this->getID();
508 $dbr = wfGetDB( DB_SLAVE
);
509 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
510 'Article::getCount', $this->getSelectOptions() );
513 return $this->mCounter
;
517 * Determine whether a page would be suitable for being counted as an
518 * article in the site_stats table based on the title & its content
520 * @param $text String: text to analyze
523 function isCountable( $text ) {
524 global $wgUseCommaCount;
526 $token = $wgUseCommaCount ?
',' : '[[';
528 $this->mTitle
->isContentPage()
529 && !$this->isRedirect( $text )
530 && in_string( $token, $text );
534 * Tests if the article text represents a redirect
536 * @param $text String: FIXME
539 function isRedirect( $text = false ) {
540 if ( $text === false ) {
541 $this->loadContent();
542 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
544 $titleObj = Title
::newFromRedirect( $text );
546 return $titleObj !== NULL;
550 * Returns true if the currently-referenced revision is the current edit
551 * to this page (and it exists).
554 function isCurrent() {
555 # If no oldid, this is the current version.
556 if ($this->getOldID() == 0)
559 return $this->exists() &&
560 isset( $this->mRevision
) &&
561 $this->mRevision
->isCurrent();
565 * Loads everything except the text
566 * This isn't necessary for all uses, so it's only done if needed.
569 function loadLastEdit() {
570 if ( -1 != $this->mUser
)
573 # New or non-existent articles have no user information
574 $id = $this->getID();
575 if ( 0 == $id ) return;
577 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
578 if( !is_null( $this->mLastRevision
) ) {
579 $this->mUser
= $this->mLastRevision
->getUser();
580 $this->mUserText
= $this->mLastRevision
->getUserText();
581 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
582 $this->mComment
= $this->mLastRevision
->getComment();
583 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
584 $this->mRevIdFetched
= $this->mLastRevision
->getID();
588 function getTimestamp() {
589 // Check if the field has been filled by ParserCache::get()
590 if ( !$this->mTimestamp
) {
591 $this->loadLastEdit();
593 return wfTimestamp(TS_MW
, $this->mTimestamp
);
597 $this->loadLastEdit();
601 function getUserText() {
602 $this->loadLastEdit();
603 return $this->mUserText
;
606 function getComment() {
607 $this->loadLastEdit();
608 return $this->mComment
;
611 function getMinorEdit() {
612 $this->loadLastEdit();
613 return $this->mMinorEdit
;
616 function getRevIdFetched() {
617 $this->loadLastEdit();
618 return $this->mRevIdFetched
;
622 * @todo Document, fixme $offset never used.
623 * @param $limit Integer: default 0.
624 * @param $offset Integer: default 0.
626 function getContributors($limit = 0, $offset = 0) {
627 # XXX: this is expensive; cache this info somewhere.
630 $dbr = wfGetDB( DB_SLAVE
);
631 $revTable = $dbr->tableName( 'revision' );
632 $userTable = $dbr->tableName( 'user' );
633 $user = $this->getUser();
634 $pageId = $this->getId();
636 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
637 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
638 WHERE rev_page = $pageId
639 AND rev_user != $user
640 GROUP BY rev_user, rev_user_text, user_real_name
641 ORDER BY timestamp DESC";
643 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
644 $sql .= ' '. $this->getSelectOptions();
646 $res = $dbr->query($sql, __METHOD__
);
648 while ( $line = $dbr->fetchObject( $res ) ) {
649 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
652 $dbr->freeResult($res);
657 * This is the default action of the script: just view the page of
661 global $wgUser, $wgOut, $wgRequest, $wgContLang;
662 global $wgEnableParserCache, $wgStylePath, $wgParser;
663 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
664 global $wgDefaultRobotPolicy;
665 $sk = $wgUser->getSkin();
667 wfProfileIn( __METHOD__
);
669 $parserCache = ParserCache
::singleton();
670 $ns = $this->mTitle
->getNamespace(); # shortcut
672 # Get variables from query string
673 $oldid = $this->getOldID();
675 # getOldID may want us to redirect somewhere else
676 if ( $this->mRedirectUrl
) {
677 $wgOut->redirect( $this->mRedirectUrl
);
678 wfProfileOut( __METHOD__
);
682 $diff = $wgRequest->getVal( 'diff' );
683 $rcid = $wgRequest->getVal( 'rcid' );
684 $rdfrom = $wgRequest->getVal( 'rdfrom' );
685 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
686 $purge = $wgRequest->getVal( 'action' ) == 'purge';
688 $wgOut->setArticleFlag( true );
690 # Discourage indexing of printable versions, but encourage following
691 if( $wgOut->isPrintable() ) {
692 $policy = 'noindex,follow';
693 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
694 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
695 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
696 # Honour customised robot policies for this namespace
697 $policy = $wgNamespaceRobotPolicies[$ns];
699 $policy = $wgDefaultRobotPolicy;
701 $wgOut->setRobotPolicy( $policy );
703 # If we got diff and oldid in the query, we want to see a
704 # diff page instead of the article.
706 if ( !is_null( $diff ) ) {
707 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
709 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
710 // DifferenceEngine directly fetched the revision:
711 $this->mRevIdFetched
= $de->mNewid
;
712 $de->showDiffPage( $diffOnly );
714 // Needed to get the page's current revision
715 $this->loadPageData();
716 if( $diff == 0 ||
$diff == $this->mLatest
) {
717 # Run view updates for current revision only
718 $this->viewUpdates();
720 wfProfileOut( __METHOD__
);
724 if ( empty( $oldid ) && $this->checkTouched() ) {
725 $wgOut->setETag($parserCache->getETag($this, $wgUser));
727 if( $wgOut->checkLastModified( $this->mTouched
) ){
728 wfProfileOut( __METHOD__
);
730 } else if ( $this->tryFileCache() ) {
731 # tell wgOut that output is taken care of
733 $this->viewUpdates();
734 wfProfileOut( __METHOD__
);
739 # Should the parser cache be used?
740 $pcache = $wgEnableParserCache
741 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
744 && !$this->mTitle
->isCssOrJsPage()
745 && !$this->mTitle
->isCssJsSubpage();
746 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
747 if ( $wgUser->getOption( 'stubthreshold' ) ) {
748 wfIncrStats( 'pcache_miss_stub' );
751 $wasRedirected = false;
752 if ( isset( $this->mRedirectedFrom
) ) {
753 // This is an internally redirected page view.
754 // We'll need a backlink to the source page for navigation.
755 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
756 $sk = $wgUser->getSkin();
757 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
758 $s = wfMsg( 'redirectedfrom', $redir );
759 $wgOut->setSubtitle( $s );
761 // Set the fragment if one was specified in the redirect
762 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
763 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
764 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
766 $wasRedirected = true;
768 } elseif ( !empty( $rdfrom ) ) {
769 // This is an externally redirected view, from some other wiki.
770 // If it was reported from a trusted site, supply a backlink.
771 global $wgRedirectSources;
772 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
773 $sk = $wgUser->getSkin();
774 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
775 $s = wfMsg( 'redirectedfrom', $redir );
776 $wgOut->setSubtitle( $s );
777 $wasRedirected = true;
782 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
784 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
785 // Ensure that UI elements requiring revision ID have
786 // the correct version information.
787 $wgOut->setRevisionId( $this->mLatest
);
791 if ( !$outputDone ) {
792 $text = $this->getContent();
793 if ( $text === false ) {
794 # Failed to load, replace text with error message
795 $t = $this->mTitle
->getPrefixedText();
797 $t .= ',oldid='.$oldid;
798 $text = wfMsg( 'missingarticle', $t );
800 $text = wfMsg( 'noarticletext', $t );
804 # Another whitelist check in case oldid is altering the title
805 if ( !$this->mTitle
->userCanRead() ) {
806 $wgOut->loginToUse();
811 # We're looking at an old revision
813 if ( !empty( $oldid ) ) {
814 $wgOut->setRobotpolicy( 'noindex,nofollow' );
815 if( is_null( $this->mRevision
) ) {
816 // FIXME: This would be a nice place to load the 'no such page' text.
818 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
819 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
820 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
821 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
822 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
825 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
826 // and we are allowed to see...
834 $wgOut->setRevisionId( $this->getRevIdFetched() );
836 // Pages containing custom CSS or JavaScript get special treatment
837 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
838 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
840 // Give hooks a chance to customise the output
841 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
842 // Wrap the whole lot in a <pre> and don't parse
844 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
845 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
846 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
847 $wgOut->addHtml( "\n</pre>\n" );
852 elseif ( $rt = $this->getRedirectTarget() ) {
854 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
855 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
856 # Don't overwrite the subtitle if this was an old revision
857 if( !$wasRedirected && $this->isCurrent() ) {
858 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
860 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
862 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
863 '<span class="redirectText">'.$link.'</span>' );
865 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
866 $wgOut->addParserOutputNoText( $parseout );
867 } else if ( $pcache ) {
868 # Display content and save to parser cache
869 $this->outputWikiText( $text );
871 # Display content, don't attempt to save to parser cache
872 # Don't show section-edit links on old revisions... this way lies madness.
873 if( !$this->isCurrent() ) {
874 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
876 # Display content and don't save to parser cache
877 # With timing hack -- TS 2006-07-26
879 $this->outputWikiText( $text, false );
884 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
885 $this->mTitle
->getPrefixedDBkey()));
888 if( !$this->isCurrent() ) {
889 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
894 /* title may have been set from the cache */
895 $t = $wgOut->getPageTitle();
897 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
900 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
901 if( $ns == NS_USER_TALK
&&
902 User
::isIP( $this->mTitle
->getText() ) ) {
903 $wgOut->addWikiMsg('anontalkpagetext');
906 # If we have been passed an &rcid= parameter, we want to give the user a
907 # chance to mark this new article as patrolled.
908 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
910 "<div class='patrollink'>" .
911 wfMsgHtml( 'markaspatrolledlink',
912 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
913 "action=markpatrolled&rcid=$rcid" )
920 if ($wgUseTrackbacks)
921 $this->addTrackbacks();
923 $this->viewUpdates();
924 wfProfileOut( __METHOD__
);
927 function addTrackbacks() {
928 global $wgOut, $wgUser;
930 $dbr = wfGetDB(DB_SLAVE
);
932 /* FROM */ 'trackbacks',
933 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
934 /* WHERE */ array('tb_page' => $this->getID())
937 if (!$dbr->numrows($tbs))
941 while ($o = $dbr->fetchObject($tbs)) {
943 if ($wgUser->isAllowed( 'trackback' )) {
944 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
945 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
946 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
949 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
956 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
959 function deletetrackback() {
960 global $wgUser, $wgRequest, $wgOut, $wgTitle;
962 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
963 $wgOut->addWikiMsg( 'sessionfailure' );
967 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
969 if (count($permission_errors)>0)
971 $wgOut->showPermissionsErrorPage( $permission_errors );
975 $db = wfGetDB(DB_MASTER
);
976 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
977 $wgTitle->invalidateCache();
978 $wgOut->addWikiMsg('trackbackdeleteok');
984 $wgOut->setArticleBodyOnly(true);
989 * Handle action=purge
992 global $wgUser, $wgRequest, $wgOut;
994 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
995 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
999 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1000 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1001 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1002 $msg = str_replace( '$1',
1003 "<form method=\"post\" action=\"$action\">\n" .
1004 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1005 "</form>\n", $msg );
1007 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1008 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1009 $wgOut->addHTML( $msg );
1014 * Perform the actions of a page purging
1016 function doPurge() {
1018 // Invalidate the cache
1019 $this->mTitle
->invalidateCache();
1021 if ( $wgUseSquid ) {
1022 // Commit the transaction before the purge is sent
1023 $dbw = wfGetDB( DB_MASTER
);
1024 $dbw->immediateCommit();
1027 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1028 $update->doUpdate();
1030 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1031 global $wgMessageCache;
1032 if ( $this->getID() == 0 ) {
1035 $text = $this->getContent();
1037 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1043 * Insert a new empty page record for this article.
1044 * This *must* be followed up by creating a revision
1045 * and running $this->updateToLatest( $rev_id );
1046 * or else the record will be left in a funky state.
1047 * Best if all done inside a transaction.
1049 * @param Database $dbw
1050 * @return int The newly created page_id key
1053 function insertOn( $dbw ) {
1054 wfProfileIn( __METHOD__
);
1056 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1057 $dbw->insert( 'page', array(
1058 'page_id' => $page_id,
1059 'page_namespace' => $this->mTitle
->getNamespace(),
1060 'page_title' => $this->mTitle
->getDBkey(),
1061 'page_counter' => 0,
1062 'page_restrictions' => '',
1063 'page_is_redirect' => 0, # Will set this shortly...
1065 'page_random' => wfRandom(),
1066 'page_touched' => $dbw->timestamp(),
1067 'page_latest' => 0, # Fill this in shortly...
1068 'page_len' => 0, # Fill this in shortly...
1070 $newid = $dbw->insertId();
1072 $this->mTitle
->resetArticleId( $newid );
1074 wfProfileOut( __METHOD__
);
1079 * Update the page record to point to a newly saved revision.
1081 * @param Database $dbw
1082 * @param Revision $revision For ID number, and text used to set
1083 length and redirect status fields
1084 * @param int $lastRevision If given, will not overwrite the page field
1085 * when different from the currently set value.
1086 * Giving 0 indicates the new page flag should
1088 * @param bool $lastRevIsRedirect If given, will optimize adding and
1089 * removing rows in redirect table.
1090 * @return bool true on success, false on failure
1093 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1094 wfProfileIn( __METHOD__
);
1096 $text = $revision->getText();
1097 $rt = Title
::newFromRedirect( $text );
1099 $conditions = array( 'page_id' => $this->getId() );
1100 if( !is_null( $lastRevision ) ) {
1101 # An extra check against threads stepping on each other
1102 $conditions['page_latest'] = $lastRevision;
1105 $dbw->update( 'page',
1107 'page_latest' => $revision->getId(),
1108 'page_touched' => $dbw->timestamp(),
1109 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1110 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1111 'page_len' => strlen( $text ),
1116 $result = $dbw->affectedRows() != 0;
1119 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1122 wfProfileOut( __METHOD__
);
1127 * Add row to the redirect table if this is a redirect, remove otherwise.
1129 * @param Database $dbw
1130 * @param $redirectTitle a title object pointing to the redirect target,
1131 * or NULL if this is not a redirect
1132 * @param bool $lastRevIsRedirect If given, will optimize adding and
1133 * removing rows in redirect table.
1134 * @return bool true on success, false on failure
1137 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1139 // Always update redirects (target link might have changed)
1140 // Update/Insert if we don't know if the last revision was a redirect or not
1141 // Delete if changing from redirect to non-redirect
1142 $isRedirect = !is_null($redirectTitle);
1143 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1145 wfProfileIn( __METHOD__
);
1149 // This title is a redirect, Add/Update row in the redirect table
1150 $set = array( /* SET */
1151 'rd_namespace' => $redirectTitle->getNamespace(),
1152 'rd_title' => $redirectTitle->getDBkey(),
1153 'rd_from' => $this->getId(),
1156 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1158 // This is not a redirect, remove row from redirect table
1159 $where = array( 'rd_from' => $this->getId() );
1160 $dbw->delete( 'redirect', $where, __METHOD__
);
1163 wfProfileOut( __METHOD__
);
1164 return ( $dbw->affectedRows() != 0 );
1171 * If the given revision is newer than the currently set page_latest,
1172 * update the page record. Otherwise, do nothing.
1174 * @param Database $dbw
1175 * @param Revision $revision
1177 function updateIfNewerOn( &$dbw, $revision ) {
1178 wfProfileIn( __METHOD__
);
1180 $row = $dbw->selectRow(
1181 array( 'revision', 'page' ),
1182 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1184 'page_id' => $this->getId(),
1185 'page_latest=rev_id' ),
1188 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1189 wfProfileOut( __METHOD__
);
1192 $prev = $row->rev_id
;
1193 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1195 # No or missing previous revision; mark the page as new
1197 $lastRevIsRedirect = null;
1200 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1201 wfProfileOut( __METHOD__
);
1206 * @return string Complete article text, or null if error
1208 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1209 wfProfileIn( __METHOD__
);
1211 if( $section == '' ) {
1212 // Whole-page edit; let the text through unmolested.
1214 if( is_null( $edittime ) ) {
1215 $rev = Revision
::newFromTitle( $this->mTitle
);
1217 $dbw = wfGetDB( DB_MASTER
);
1218 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1220 if( is_null( $rev ) ) {
1221 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1222 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1225 $oldtext = $rev->getText();
1227 if( $section == 'new' ) {
1228 # Inserting a new section
1229 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1230 $text = strlen( trim( $oldtext ) ) > 0
1231 ?
"{$oldtext}\n\n{$subject}{$text}"
1232 : "{$subject}{$text}";
1234 # Replacing an existing section; roll out the big guns
1236 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1241 wfProfileOut( __METHOD__
);
1246 * @deprecated use Article::doEdit()
1248 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1249 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1250 ( $isminor ? EDIT_MINOR
: 0 ) |
1251 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1252 ( $bot ? EDIT_FORCE_BOT
: 0 );
1254 # If this is a comment, add the summary as headline
1255 if ( $comment && $summary != "" ) {
1256 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1259 $this->doEdit( $text, $summary, $flags );
1261 $dbw = wfGetDB( DB_MASTER
);
1263 if (!$this->mTitle
->userIsWatching()) {
1269 if ( $this->mTitle
->userIsWatching() ) {
1275 $this->doRedirect( $this->isRedirect( $text ) );
1279 * @deprecated use Article::doEdit()
1281 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1282 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1283 ( $minor ? EDIT_MINOR
: 0 ) |
1284 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1286 $good = $this->doEdit( $text, $summary, $flags );
1288 $dbw = wfGetDB( DB_MASTER
);
1290 if (!$this->mTitle
->userIsWatching()) {
1296 if ( $this->mTitle
->userIsWatching() ) {
1303 $extraq = ''; // Give extensions a chance to modify URL query on update
1304 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1306 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1314 * Change an existing article or create a new article. Updates RC and all necessary caches,
1315 * optionally via the deferred update array.
1317 * $wgUser must be set before calling this function.
1319 * @param string $text New text
1320 * @param string $summary Edit summary
1321 * @param integer $flags bitfield:
1323 * Article is known or assumed to be non-existent, create a new one
1325 * Article is known or assumed to be pre-existing, update it
1327 * Mark this edit minor, if the user is allowed to do so
1329 * Do not log the change in recentchanges
1331 * Mark the edit a "bot" edit regardless of user rights
1332 * EDIT_DEFER_UPDATES
1333 * Defer some of the updates until the end of index.php
1335 * Fill in blank summaries with generated text where possible
1337 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1338 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1339 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1340 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1341 * to MediaWiki's performance-optimised locking strategy.
1343 * @return bool success
1345 function doEdit( $text, $summary, $flags = 0 ) {
1346 global $wgUser, $wgDBtransactions;
1348 wfProfileIn( __METHOD__
);
1351 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1352 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1354 $flags |
= EDIT_UPDATE
;
1360 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1361 &$summary, $flags & EDIT_MINOR
,
1362 null, null, &$flags ) ) )
1364 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1365 wfProfileOut( __METHOD__
);
1369 # Silently ignore EDIT_MINOR if not allowed
1370 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1371 $bot = $flags & EDIT_FORCE_BOT
;
1373 $oldtext = $this->getContent();
1374 $oldsize = strlen( $oldtext );
1376 # Provide autosummaries if one is not provided.
1377 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1378 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1380 $editInfo = $this->prepareTextForEdit( $text );
1381 $text = $editInfo->pst
;
1382 $newsize = strlen( $text );
1384 $dbw = wfGetDB( DB_MASTER
);
1385 $now = wfTimestampNow();
1387 if ( $flags & EDIT_UPDATE
) {
1388 # Update article, but only if changed.
1390 # Make sure the revision is either completely inserted or not inserted at all
1391 if( !$wgDBtransactions ) {
1392 $userAbort = ignore_user_abort( true );
1398 $changed = ( strcmp( $text, $oldtext ) != 0 );
1401 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1402 - (int)$this->isCountable( $oldtext );
1403 $this->mTotalAdjustment
= 0;
1405 $lastRevision = $dbw->selectField(
1406 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1408 if ( !$lastRevision ) {
1409 # Article gone missing
1410 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1411 wfProfileOut( __METHOD__
);
1415 $revision = new Revision( array(
1416 'page' => $this->getId(),
1417 'comment' => $summary,
1418 'minor_edit' => $isminor,
1420 'parent_id' => $lastRevision
1424 $revisionId = $revision->insertOn( $dbw );
1427 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1430 /* Belated edit conflict! Run away!! */
1434 # Update recentchanges
1435 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1436 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1437 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1440 # Mark as patrolled if the user can do so
1441 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1442 RecentChange
::markPatrolled( $rcid );
1443 PatrolLog
::record( $rcid, true );
1446 $wgUser->incEditCount();
1451 // Keep the same revision ID, but do some updates on it
1452 $revisionId = $this->getRevIdFetched();
1453 // Update page_touched, this is usually implicit in the page update
1454 // Other cache updates are done in onArticleEdit()
1455 $this->mTitle
->invalidateCache();
1458 if( !$wgDBtransactions ) {
1459 ignore_user_abort( $userAbort );
1463 # Invalidate cache of this article and all pages using this article
1464 # as a template. Partly deferred.
1465 Article
::onArticleEdit( $this->mTitle
);
1467 # Update links tables, site stats, etc.
1468 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1471 # Create new article
1473 # Set statistics members
1474 # We work out if it's countable after PST to avoid counter drift
1475 # when articles are created with {{subst:}}
1476 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1477 $this->mTotalAdjustment
= 1;
1481 # Add the page record; stake our claim on this title!
1482 # This will fail with a database query exception if the article already exists
1483 $newid = $this->insertOn( $dbw );
1485 # Save the revision text...
1486 $revision = new Revision( array(
1488 'comment' => $summary,
1489 'minor_edit' => $isminor,
1492 $revisionId = $revision->insertOn( $dbw );
1494 $this->mTitle
->resetArticleID( $newid );
1496 # Update the page record with revision data
1497 $this->updateRevisionOn( $dbw, $revision, 0 );
1499 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1500 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1501 '', strlen( $text ), $revisionId );
1502 # Mark as patrolled if the user can
1503 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1504 RecentChange
::markPatrolled( $rcid );
1505 PatrolLog
::record( $rcid, true );
1508 $wgUser->incEditCount();
1511 # Update links, etc.
1512 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1515 Article
::onArticleCreate( $this->mTitle
);
1517 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1518 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1521 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1526 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1527 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1530 wfProfileOut( __METHOD__
);
1535 * @deprecated wrapper for doRedirect
1537 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1538 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1542 * Output a redirect back to the article.
1543 * This is typically used after an edit.
1545 * @param boolean $noRedir Add redirect=no
1546 * @param string $sectionAnchor section to redirect to, including "#"
1547 * @param string $extraq, extra query params
1549 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1552 $query = 'redirect=no';
1554 $query .= "&$query";
1558 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1562 * Mark this particular edit/page as patrolled
1564 function markpatrolled() {
1565 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1566 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1568 # Check patrol config options
1570 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1571 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1575 # If we haven't been given an rc_id value, we can't do anything
1576 $rcid = (int) $wgRequest->getVal('rcid');
1577 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1578 if ( is_null ( $rc ) )
1580 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1584 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1585 // Only new pages can be patrolled if the general patrolling is off....???
1586 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1588 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1593 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1595 if (count($permission_errors)>0)
1597 $wgOut->showPermissionsErrorPage( $permission_errors );
1601 # Handle the 'MarkPatrolled' hook
1602 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1606 #It would be nice to see where the user had actually come from, but for now just guess
1607 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1608 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1610 # If it's left up to us, check that the user is allowed to patrol this edit
1611 # If the user has the "autopatrol" right, then we'll assume there are no
1612 # other conditions stopping them doing so
1613 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1614 $rc = RecentChange
::newFromId( $rcid );
1615 # Graceful error handling, as we've done before here...
1616 # (If the recent change doesn't exist, then it doesn't matter whether
1617 # the user is allowed to patrol it or not; nothing is going to happen
1618 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1619 # The user made this edit, and can't patrol it
1620 # Tell them so, and then back off
1621 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1622 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1623 $wgOut->returnToMain( false, $return );
1628 # Check that the revision isn't patrolled already
1629 # Prevents duplicate log entries
1630 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1631 # Mark the edit as patrolled
1632 RecentChange
::markPatrolled( $rcid );
1633 PatrolLog
::record( $rcid );
1634 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1638 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1639 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1640 $wgOut->returnToMain( false, $return );
1644 * User-interface handler for the "watch" action
1649 global $wgUser, $wgOut;
1651 if ( $wgUser->isAnon() ) {
1652 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1655 if ( wfReadOnly() ) {
1656 $wgOut->readOnlyPage();
1660 if( $this->doWatch() ) {
1661 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1662 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1664 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1667 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1671 * Add this page to $wgUser's watchlist
1672 * @return bool true on successful watch operation
1674 function doWatch() {
1676 if( $wgUser->isAnon() ) {
1680 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1681 $wgUser->addWatch( $this->mTitle
);
1683 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1690 * User interface handler for the "unwatch" action.
1692 function unwatch() {
1694 global $wgUser, $wgOut;
1696 if ( $wgUser->isAnon() ) {
1697 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1700 if ( wfReadOnly() ) {
1701 $wgOut->readOnlyPage();
1705 if( $this->doUnwatch() ) {
1706 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1707 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1709 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1712 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1716 * Stop watching a page
1717 * @return bool true on successful unwatch
1719 function doUnwatch() {
1721 if( $wgUser->isAnon() ) {
1725 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1726 $wgUser->removeWatch( $this->mTitle
);
1728 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1735 * action=protect handler
1737 function protect() {
1738 $form = new ProtectionForm( $this );
1743 * action=unprotect handler (alias)
1745 function unprotect() {
1750 * Update the article's restriction field, and leave a log entry.
1752 * @param array $limit set of restriction keys
1753 * @param string $reason
1754 * @return bool true on success
1756 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1757 global $wgUser, $wgRestrictionTypes, $wgContLang;
1759 $id = $this->mTitle
->getArticleID();
1760 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1768 // Take this opportunity to purge out expired restrictions
1769 Title
::purgeExpiredRestrictions();
1771 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1772 # we expect a single selection, but the schema allows otherwise.
1774 foreach( $wgRestrictionTypes as $action )
1775 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1777 $current = Article
::flattenRestrictions( $current );
1778 $updated = Article
::flattenRestrictions( $limit );
1780 $changed = ( $current != $updated );
1781 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1782 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1783 $protect = ( $updated != '' );
1785 # If nothing's changed, do nothing
1787 global $wgGroupPermissions;
1788 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1790 $dbw = wfGetDB( DB_MASTER
);
1792 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1794 $expiry_description = '';
1795 if ( $encodedExpiry != 'infinity' ) {
1796 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1799 # Prepare a null revision to be added to the history
1800 $modified = $current != '' && $protect;
1802 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1804 $comment_type = 'unprotectedarticle';
1806 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1808 foreach( $limit as $action => $restrictions ) {
1809 # Check if the group level required to edit also can protect pages
1810 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1811 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1812 $wgGroupPermissions[$restrictions]['protect'] );
1815 $cascade_description = '';
1817 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1821 $comment .= ": $reason";
1823 $comment .= " [$updated]";
1824 if ( $expiry_description && $protect )
1825 $comment .= "$expiry_description";
1827 $comment .= "$cascade_description";
1829 # Update restrictions table
1830 foreach( $limit as $action => $restrictions ) {
1831 if ($restrictions != '' ) {
1832 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1833 array( 'pr_page' => $id, 'pr_type' => $action
1834 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1835 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1837 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1838 'pr_type' => $action ), __METHOD__
);
1842 # Insert a null revision
1843 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1844 $nullRevId = $nullRevision->insertOn( $dbw );
1846 # Update page record
1847 $dbw->update( 'page',
1849 'page_touched' => $dbw->timestamp(),
1850 'page_restrictions' => '',
1851 'page_latest' => $nullRevId
1852 ), array( /* WHERE */
1854 ), 'Article::protect'
1856 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1858 # Update the protection log
1859 $log = new LogPage( 'protect' );
1864 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1866 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1870 } # End "changed" check
1876 * Take an array of page restrictions and flatten it to a string
1877 * suitable for insertion into the page_restrictions field.
1878 * @param array $limit
1882 function flattenRestrictions( $limit ) {
1883 if( !is_array( $limit ) ) {
1884 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1888 foreach( $limit as $action => $restrictions ) {
1889 if( $restrictions != '' ) {
1890 $bits[] = "$action=$restrictions";
1893 return implode( ':', $bits );
1897 * Auto-generates a deletion reason
1898 * @param bool &$hasHistory Whether the page has a history
1900 public function generateReason(&$hasHistory)
1903 $dbw = wfGetDB(DB_MASTER
);
1904 // Get the last revision
1905 $rev = Revision
::newFromTitle($this->mTitle
);
1908 // Get the article's contents
1909 $contents = $rev->getText();
1911 // If the page is blank, use the text from the previous revision,
1912 // which can only be blank if there's a move/import/protect dummy revision involved
1915 $prev = $rev->getPrevious();
1918 $contents = $prev->getText();
1923 // Find out if there was only one contributor
1924 // Only scan the last 20 revisions
1926 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1927 array('LIMIT' => $limit));
1929 // This page has no revisions, which is very weird
1931 if($res->numRows() > 1)
1934 $hasHistory = false;
1935 $row = $dbw->fetchObject($res);
1936 $onlyAuthor = $row->rev_user_text
;
1937 // Try to find a second contributor
1938 while( $row = $dbw->fetchObject($res) ) {
1939 if($row->rev_user_text
!= $onlyAuthor) {
1940 $onlyAuthor = false;
1944 $dbw->freeResult($res);
1946 // Generate the summary with a '$1' placeholder
1948 // The current revision is blank and the one before is also
1949 // blank. It's just not our lucky day
1950 $reason = wfMsgForContent('exbeforeblank', '$1');
1953 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1955 $reason = wfMsgForContent('excontent', '$1');
1958 // Replace newlines with spaces to prevent uglyness
1959 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1960 // Calculate the maximum amount of chars to get
1961 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1962 $maxLength = 255 - (strlen($reason) - 2) - 3;
1963 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1964 // Remove possible unfinished links
1965 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1966 // Now replace the '$1' placeholder
1967 $reason = str_replace( '$1', $contents, $reason );
1973 * UI entry point for page deletion
1976 global $wgUser, $wgOut, $wgRequest;
1978 $confirm = $wgRequest->wasPosted() &&
1979 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1981 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1982 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1984 $reason = $this->DeleteReasonList
;
1986 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1987 // Entry from drop down menu + additional comment
1988 $reason .= ': ' . $this->DeleteReason
;
1989 } elseif ( $reason == 'other' ) {
1990 $reason = $this->DeleteReason
;
1992 # Flag to hide all contents of the archived revisions
1993 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
1995 # This code desperately needs to be totally rewritten
1997 # Read-only check...
1998 if ( wfReadOnly() ) {
1999 $wgOut->readOnlyPage();
2004 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2006 if (count($permission_errors)>0) {
2007 $wgOut->showPermissionsErrorPage( $permission_errors );
2011 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2013 # Better double-check that it hasn't been deleted yet!
2014 $dbw = wfGetDB( DB_MASTER
);
2015 $conds = $this->mTitle
->pageCond();
2016 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2017 if ( $latest === false ) {
2018 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2022 # Hack for big sites
2023 $bigHistory = $this->isBigDeletion();
2024 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2025 global $wgLang, $wgDeleteRevisionsLimit;
2026 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2027 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2032 $this->doDelete( $reason, $suppress );
2033 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2035 } elseif( $this->mTitle
->userIsWatching() ) {
2041 // Generate deletion reason
2042 $hasHistory = false;
2043 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2045 // If the page has a history, insert a warning
2046 if( $hasHistory && !$confirm ) {
2047 $skin=$wgUser->getSkin();
2048 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2050 global $wgLang, $wgDeleteRevisionsLimit;
2051 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2052 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2056 return $this->confirmDelete( '', $reason );
2060 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2062 function isBigDeletion() {
2063 global $wgDeleteRevisionsLimit;
2064 if( $wgDeleteRevisionsLimit ) {
2065 $revCount = $this->estimateRevisionCount();
2066 return $revCount > $wgDeleteRevisionsLimit;
2072 * @return int approximate revision count
2074 function estimateRevisionCount() {
2076 // For an exact count...
2077 //return $dbr->selectField( 'revision', 'COUNT(*)',
2078 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2079 return $dbr->estimateRowCount( 'revision', '*',
2080 array( 'rev_page' => $this->getId() ), __METHOD__
);
2084 * Get the last N authors
2085 * @param int $num Number of revisions to get
2086 * @param string $revLatest The latest rev_id, selected from the master (optional)
2087 * @return array Array of authors, duplicates not removed
2089 function getLastNAuthors( $num, $revLatest = 0 ) {
2090 wfProfileIn( __METHOD__
);
2092 // First try the slave
2093 // If that doesn't have the latest revision, try the master
2095 $db = wfGetDB( DB_SLAVE
);
2097 $res = $db->select( array( 'page', 'revision' ),
2098 array( 'rev_id', 'rev_user_text' ),
2100 'page_namespace' => $this->mTitle
->getNamespace(),
2101 'page_title' => $this->mTitle
->getDBkey(),
2102 'rev_page = page_id'
2103 ), __METHOD__
, $this->getSelectOptions( array(
2104 'ORDER BY' => 'rev_timestamp DESC',
2109 wfProfileOut( __METHOD__
);
2112 $row = $db->fetchObject( $res );
2113 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2114 $db = wfGetDB( DB_MASTER
);
2119 } while ( $continue );
2121 $authors = array( $row->rev_user_text
);
2122 while ( $row = $db->fetchObject( $res ) ) {
2123 $authors[] = $row->rev_user_text
;
2125 wfProfileOut( __METHOD__
);
2130 * Output deletion confirmation dialog
2131 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2132 * @param $reason string Prefilled reason
2134 function confirmDelete( $par, $reason ) {
2135 global $wgOut, $wgUser, $wgContLang;
2136 $align = $wgContLang->isRtl() ?
'left' : 'right';
2138 wfDebug( "Article::confirmDelete\n" );
2140 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2141 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2142 $wgOut->addWikiMsg( 'confirmdeletetext' );
2144 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2145 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2146 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2147 $suppress .= "</td></tr>";
2152 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2153 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2154 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2155 Xml
::openElement( 'table' ) .
2156 "<tr id=\"wpDeleteReasonListRow\">
2157 <td align='$align'>" .
2158 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2161 Xml
::listDropDown( 'wpDeleteReasonList',
2162 wfMsgForContent( 'deletereason-dropdown' ),
2163 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2166 <tr id=\"wpDeleteReasonRow\">
2167 <td align='$align'>" .
2168 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2171 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2177 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2184 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2187 Xml
::closeElement( 'table' ) .
2188 Xml
::closeElement( 'fieldset' ) .
2189 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2190 Xml
::closeElement( 'form' );
2192 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2193 $skin = $wgUser->getSkin();
2194 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2195 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2198 $wgOut->addHTML( $form );
2199 $this->showLogExtract( $wgOut );
2204 * Show relevant lines from the deletion log
2206 function showLogExtract( $out ) {
2207 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2208 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2213 * Perform a deletion and output success or failure messages
2215 function doDelete( $reason, $suppress = false ) {
2216 global $wgOut, $wgUser;
2217 wfDebug( __METHOD__
."\n" );
2219 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2220 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2221 $deleted = $this->mTitle
->getPrefixedText();
2223 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2224 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2226 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2228 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2229 $wgOut->returnToMain( false );
2230 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2232 $wgOut->showFatalError( wfMsg( 'cannotdelete' ).'<br/>'.wfMsg('cannotdelete-merge') );
2238 * Back-end article deletion
2239 * Deletes the article with database consistency, writes logs, purges caches
2242 function doDeleteArticle( $reason, $suppress = false ) {
2243 global $wgUseSquid, $wgDeferredUpdateList;
2244 global $wgUseTrackbacks;
2246 wfDebug( __METHOD__
."\n" );
2248 $dbw = wfGetDB( DB_MASTER
);
2249 $ns = $this->mTitle
->getNamespace();
2250 $t = $this->mTitle
->getDBkey();
2251 $id = $this->mTitle
->getArticleID();
2253 if ( $t == '' ||
$id == 0 ) {
2257 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2258 array_push( $wgDeferredUpdateList, $u );
2260 // Bitfields to further suppress the content
2263 // This should be 15...
2264 $bitfield |
= Revision
::DELETED_TEXT
;
2265 $bitfield |
= Revision
::DELETED_COMMENT
;
2266 $bitfield |
= Revision
::DELETED_USER
;
2267 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2269 $bitfield = 'rev_deleted';
2272 // For now, shunt the revision data into the archive table.
2273 // Text is *not* removed from the text table; bulk storage
2274 // is left intact to avoid breaking block-compression or
2275 // immutable storage schemes.
2277 // For backwards compatibility, note that some older archive
2278 // table entries will have ar_text and ar_flags fields still.
2280 // In the future, we may keep revisions and mark them with
2281 // the rev_deleted field, which is reserved for this purpose.
2282 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2284 'ar_namespace' => 'page_namespace',
2285 'ar_title' => 'page_title',
2286 'ar_comment' => 'rev_comment',
2287 'ar_user' => 'rev_user',
2288 'ar_user_text' => 'rev_user_text',
2289 'ar_timestamp' => 'rev_timestamp',
2290 'ar_minor_edit' => 'rev_minor_edit',
2291 'ar_rev_id' => 'rev_id',
2292 'ar_text_id' => 'rev_text_id',
2293 'ar_text' => '\'\'', // Be explicit to appease
2294 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2295 'ar_len' => 'rev_len',
2296 'ar_page_id' => 'page_id',
2297 'ar_deleted' => $bitfield
2300 'page_id = rev_page'
2304 # Delete restrictions for it
2305 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2307 # Fix category table counts
2309 $res = $dbw->select( 'categorylinks', 'cl_to',
2310 array( 'cl_from' => $id ), __METHOD__
);
2311 foreach( $res as $row ) {
2312 $cats []= $row->cl_to
;
2314 $this->updateCategoryCounts( array(), $cats );
2316 # Now that it's safely backed up, delete it
2317 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2319 # If using cascading deletes, we can skip some explicit deletes
2320 if ( !$dbw->cascadingDeletes() ) {
2321 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2323 if ($wgUseTrackbacks)
2324 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2326 # Delete outgoing links
2327 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2328 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2329 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2330 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2331 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2332 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2333 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2336 # If using cleanup triggers, we can skip some manual deletes
2337 if ( !$dbw->cleanupTriggers() ) {
2339 # Clean up recentchanges entries...
2340 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2344 Article
::onArticleDelete( $this->mTitle
);
2346 # Clear the cached article id so the interface doesn't act like we exist
2347 $this->mTitle
->resetArticleID( 0 );
2348 $this->mTitle
->mArticleID
= 0;
2350 # Log the deletion, if the page was suppressed, log it at Oversight instead
2351 $logtype = $suppress ?
'suppress' : 'delete';
2352 $log = new LogPage( $logtype );
2353 $log->addEntry( 'delete', $this->mTitle
, $reason );
2359 * Roll back the most recent consecutive set of edits to a page
2360 * from the same user; fails if there are no eligible edits to
2361 * roll back to, e.g. user is the sole contributor. This function
2362 * performs permissions checks on $wgUser, then calls commitRollback()
2363 * to do the dirty work
2365 * @param string $fromP - Name of the user whose edits to rollback.
2366 * @param string $summary - Custom summary. Set to default summary if empty.
2367 * @param string $token - Rollback token.
2368 * @param bool $bot - If true, mark all reverted edits as bot.
2370 * @param array $resultDetails contains result-specific array of additional values
2371 * 'alreadyrolled' : 'current' (rev)
2372 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2374 * @return array of errors, each error formatted as
2375 * array(messagekey, param1, param2, ...).
2376 * On success, the array is empty. This array can also be passed to
2377 * OutputPage::showPermissionsErrorPage().
2379 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2381 $resultDetails = null;
2384 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2385 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2386 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2387 $errors[] = array( 'sessionfailure' );
2389 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2390 $errors[] = array( 'actionthrottledtext' );
2392 # If there were errors, bail out now
2396 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2400 * Backend implementation of doRollback(), please refer there for parameter
2401 * and return value documentation
2403 * NOTE: This function does NOT check ANY permissions, it just commits the
2404 * rollback to the DB Therefore, you should only call this function direct-
2405 * ly if you want to use custom permissions checks. If you don't, use
2406 * doRollback() instead.
2408 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2409 global $wgUseRCPatrol, $wgUser;
2410 $dbw = wfGetDB( DB_MASTER
);
2412 if( wfReadOnly() ) {
2413 return array( array( 'readonlytext' ) );
2416 # Get the last editor
2417 $current = Revision
::newFromTitle( $this->mTitle
);
2418 if( is_null( $current ) ) {
2419 # Something wrong... no page?
2420 return array(array('notanarticle'));
2423 $from = str_replace( '_', ' ', $fromP );
2424 if( $from != $current->getUserText() ) {
2425 $resultDetails = array( 'current' => $current );
2426 return array(array('alreadyrolled',
2427 htmlspecialchars($this->mTitle
->getPrefixedText()),
2428 htmlspecialchars($fromP),
2429 htmlspecialchars($current->getUserText())
2433 # Get the last edit not by this guy
2434 $user = intval( $current->getUser() );
2435 $user_text = $dbw->addQuotes( $current->getUserText() );
2436 $s = $dbw->selectRow( 'revision',
2437 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2438 array( 'rev_page' => $current->getPage(),
2439 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2441 array( 'USE INDEX' => 'page_timestamp',
2442 'ORDER BY' => 'rev_timestamp DESC' )
2444 if( $s === false ) {
2445 # No one else ever edited this page
2446 return array(array('cantrollback'));
2447 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2448 # Only admins can see this text
2449 return array(array('notvisiblerev'));
2453 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2454 # Mark all reverted edits as bot
2457 if ( $wgUseRCPatrol ) {
2458 # Mark all reverted edits as patrolled
2459 $set['rc_patrolled'] = 1;
2463 $dbw->update( 'recentchanges', $set,
2465 'rc_cur_id' => $current->getPage(),
2466 'rc_user_text' => $current->getUserText(),
2467 "rc_timestamp > '{$s->rev_timestamp}'",
2472 # Generate the edit summary if necessary
2473 $target = Revision
::newFromId( $s->rev_id
);
2474 if( empty( $summary ) )
2477 $summary = wfMsgForContent( 'revertpage',
2478 $target->getUserText(), $from,
2479 $s->rev_id
, $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2480 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2485 $flags = EDIT_UPDATE
;
2487 if ($wgUser->isAllowed('minoredit'))
2488 $flags |
= EDIT_MINOR
;
2490 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2491 $flags |
= EDIT_FORCE_BOT
;
2492 $this->doEdit( $target->getText(), $summary, $flags );
2494 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2496 $resultDetails = array(
2497 'summary' => $summary,
2498 'current' => $current,
2499 'target' => $target,
2505 * User interface for rollback operations
2507 function rollback() {
2508 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2511 $result = $this->doRollback(
2512 $wgRequest->getVal( 'from' ),
2513 $wgRequest->getText( 'summary' ),
2514 $wgRequest->getVal( 'token' ),
2515 $wgRequest->getBool( 'bot' ),
2519 if( in_array( array( 'blocked' ), $result ) ) {
2520 $wgOut->blockedPage();
2523 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2524 $wgOut->rateLimited();
2527 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2528 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2529 $errArray = $result[0];
2530 $errMsg = array_shift( $errArray );
2531 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2532 if( isset( $details['current'] ) ){
2533 $current = $details['current'];
2534 if( $current->getComment() != '' ) {
2535 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2540 # Display permissions errors before read-only message -- there's no
2541 # point in misleading the user into thinking the inability to rollback
2542 # is only temporary.
2543 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2544 # array_diff is completely broken for arrays of arrays, sigh. Re-
2545 # move any 'readonlytext' error manually.
2547 foreach( $result as $error ) {
2548 if( $error != array( 'readonlytext' ) ) {
2552 $wgOut->showPermissionsErrorPage( $out );
2555 if( $result == array( array('readonlytext') ) ) {
2556 $wgOut->readOnlyPage();
2560 $current = $details['current'];
2561 $target = $details['target'];
2562 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2563 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2564 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2565 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2566 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2567 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2568 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2569 $wgOut->returnToMain( false, $this->mTitle
);
2574 * Do standard deferred updates after page view
2577 function viewUpdates() {
2578 global $wgDeferredUpdateList;
2580 if ( 0 != $this->getID() ) {
2581 global $wgDisableCounters;
2582 if( !$wgDisableCounters ) {
2583 Article
::incViewCount( $this->getID() );
2584 $u = new SiteStatsUpdate( 1, 0, 0 );
2585 array_push( $wgDeferredUpdateList, $u );
2589 # Update newtalk / watchlist notification status
2591 $wgUser->clearNotification( $this->mTitle
);
2595 * Prepare text which is about to be saved.
2596 * Returns a stdclass with source, pst and output members
2598 function prepareTextForEdit( $text, $revid=null ) {
2599 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2601 return $this->mPreparedEdit
;
2604 $edit = (object)array();
2605 $edit->revid
= $revid;
2606 $edit->newText
= $text;
2607 $edit->pst
= $this->preSaveTransform( $text );
2608 $options = new ParserOptions
;
2609 $options->setTidy( true );
2610 $options->enableLimitReport();
2611 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2612 $edit->oldText
= $this->getContent();
2613 $this->mPreparedEdit
= $edit;
2618 * Do standard deferred updates after page edit.
2619 * Update links tables, site stats, search index and message cache.
2620 * Every 100th edit, prune the recent changes table.
2623 * @param $text New text of the article
2624 * @param $summary Edit summary
2625 * @param $minoredit Minor edit
2626 * @param $timestamp_of_pagechange Timestamp associated with the page change
2627 * @param $newid rev_id value of the new revision
2628 * @param $changed Whether or not the content actually changed
2630 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2631 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2633 wfProfileIn( __METHOD__
);
2636 # Be careful not to double-PST: $text is usually already PST-ed once
2637 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2638 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2639 $editInfo = $this->prepareTextForEdit( $text, $newid );
2641 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2642 $editInfo = $this->mPreparedEdit
;
2645 # Save it to the parser cache
2646 if ( $wgEnableParserCache ) {
2647 $parserCache = ParserCache
::singleton();
2648 $parserCache->save( $editInfo->output
, $this, $wgUser );
2651 # Update the links tables
2652 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2655 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2656 if ( 0 == mt_rand( 0, 99 ) ) {
2657 // Flush old entries from the `recentchanges` table; we do this on
2658 // random requests so as to avoid an increase in writes for no good reason
2660 $dbw = wfGetDB( DB_MASTER
);
2661 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2662 $recentchanges = $dbw->tableName( 'recentchanges' );
2663 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2664 $dbw->query( $sql );
2668 $id = $this->getID();
2669 $title = $this->mTitle
->getPrefixedDBkey();
2670 $shortTitle = $this->mTitle
->getDBkey();
2673 wfProfileOut( __METHOD__
);
2677 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2678 array_push( $wgDeferredUpdateList, $u );
2679 $u = new SearchUpdate( $id, $title, $text );
2680 array_push( $wgDeferredUpdateList, $u );
2682 # If this is another user's talk page, update newtalk
2683 # Don't do this if $changed = false otherwise some idiot can null-edit a
2684 # load of user talk pages and piss people off, nor if it's a minor edit
2685 # by a properly-flagged bot.
2686 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2687 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2688 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2689 $other = User
::newFromName( $shortTitle );
2690 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2691 // An anonymous user
2692 $other = new User();
2693 $other->setName( $shortTitle );
2696 $other->setNewtalk( true );
2701 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2702 $wgMessageCache->replace( $shortTitle, $text );
2705 wfProfileOut( __METHOD__
);
2709 * Perform article updates on a special page creation.
2711 * @param Revision $rev
2713 * @todo This is a shitty interface function. Kill it and replace the
2714 * other shitty functions like editUpdates and such so it's not needed
2717 function createUpdates( $rev ) {
2718 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2719 $this->mTotalAdjustment
= 1;
2720 $this->editUpdates( $rev->getText(), $rev->getComment(),
2721 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2725 * Generate the navigation links when browsing through an article revisions
2726 * It shows the information as:
2727 * Revision as of \<date\>; view current revision
2728 * \<- Previous version | Next Version -\>
2731 * @param string $oldid Revision ID of this article revision
2733 function setOldSubtitle( $oldid=0 ) {
2734 global $wgLang, $wgOut, $wgUser;
2736 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2740 $revision = Revision
::newFromId( $oldid );
2742 $current = ( $oldid == $this->mLatest
);
2743 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2744 $sk = $wgUser->getSkin();
2746 ?
wfMsg( 'currentrevisionlink' )
2747 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2750 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2751 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2753 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2754 : wfMsg( 'previousrevision' );
2756 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2758 $nextlink = $current
2759 ?
wfMsg( 'nextrevision' )
2760 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2761 $nextdiff = $current
2763 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2766 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2767 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2768 if( $revision->isCurrent() ) {
2769 // We don't handle top deleted edits too well
2770 $cdel = wfMsgHtml('rev-delundel');
2771 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2772 // If revision was hidden from sysops
2773 $cdel = wfMsgHtml('rev-delundel');
2775 $cdel = $sk->makeKnownLinkObj( $revdel,
2776 wfMsgHtml('rev-delundel'),
2777 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2778 '&oldid=' . urlencode( $oldid ) );
2779 // Bolden oversighted content
2780 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2781 $cdel = "<strong>$cdel</strong>";
2783 $cdel = "(<small>$cdel</small>) ";
2785 # Show user links if allowed to see them. Normally they
2786 # are hidden regardless, but since we can already see the text here...
2787 $userlinks = $sk->revUserTools( $revision, false );
2789 $m = wfMsg( 'revision-info-current' );
2790 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2791 ?
'revision-info-current'
2794 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2796 "\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";
2797 $wgOut->setSubtitle( $r );
2801 * This function is called right before saving the wikitext,
2802 * so we can do things like signatures and links-in-context.
2804 * @param string $text
2806 function preSaveTransform( $text ) {
2807 global $wgParser, $wgUser;
2808 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2811 /* Caching functions */
2814 * checkLastModified returns true if it has taken care of all
2815 * output to the client that is necessary for this request.
2816 * (that is, it has sent a cached version of the page)
2818 function tryFileCache() {
2819 static $called = false;
2821 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2825 if($this->isFileCacheable()) {
2826 $touched = $this->mTouched
;
2827 $cache = new HTMLFileCache( $this->mTitle
);
2828 if($cache->isFileCacheGood( $touched )) {
2829 wfDebug( "Article::tryFileCache(): about to load file\n" );
2830 $cache->loadFromFileCache();
2833 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2834 ob_start( array(&$cache, 'saveToFileCache' ) );
2837 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2842 * Check if the page can be cached
2845 function isFileCacheable() {
2846 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2847 $action = $wgRequest->getVal( 'action' );
2848 $oldid = $wgRequest->getVal( 'oldid' );
2849 $diff = $wgRequest->getVal( 'diff' );
2850 $redirect = $wgRequest->getVal( 'redirect' );
2851 $printable = $wgRequest->getVal( 'printable' );
2852 $page = $wgRequest->getVal( 'page' );
2854 //check for non-standard user language; this covers uselang,
2855 //and extensions for auto-detecting user language.
2856 $ulang = $wgLang->getCode();
2857 $clang = $wgContLang->getCode();
2859 $cacheable = $wgUseFileCache
2860 && (!$wgShowIPinHeader)
2861 && ($this->getID() != 0)
2862 && ($wgUser->isAnon())
2863 && (!$wgUser->getNewtalk())
2864 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2865 && (empty( $action ) ||
$action == 'view')
2868 && (!isset($redirect))
2869 && (!isset($printable))
2871 && (!$this->mRedirectedFrom
)
2872 && ($ulang === $clang);
2875 //extension may have reason to disable file caching on some pages.
2876 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2883 * Loads page_touched and returns a value indicating if it should be used
2886 function checkTouched() {
2887 if( !$this->mDataLoaded
) {
2888 $this->loadPageData();
2890 return !$this->mIsRedirect
;
2894 * Get the page_touched field
2896 function getTouched() {
2897 # Ensure that page data has been loaded
2898 if( !$this->mDataLoaded
) {
2899 $this->loadPageData();
2901 return $this->mTouched
;
2905 * Get the page_latest field
2907 function getLatest() {
2908 if ( !$this->mDataLoaded
) {
2909 $this->loadPageData();
2911 return $this->mLatest
;
2915 * Edit an article without doing all that other stuff
2916 * The article must already exist; link tables etc
2917 * are not updated, caches are not flushed.
2919 * @param string $text text submitted
2920 * @param string $comment comment submitted
2921 * @param bool $minor whereas it's a minor modification
2923 function quickEdit( $text, $comment = '', $minor = 0 ) {
2924 wfProfileIn( __METHOD__
);
2926 $dbw = wfGetDB( DB_MASTER
);
2928 $revision = new Revision( array(
2929 'page' => $this->getId(),
2931 'comment' => $comment,
2932 'minor_edit' => $minor ?
1 : 0,
2934 $revision->insertOn( $dbw );
2935 $this->updateRevisionOn( $dbw, $revision );
2938 wfProfileOut( __METHOD__
);
2942 * Used to increment the view counter
2945 * @param integer $id article id
2947 function incViewCount( $id ) {
2948 $id = intval( $id );
2949 global $wgHitcounterUpdateFreq, $wgDBtype;
2951 $dbw = wfGetDB( DB_MASTER
);
2952 $pageTable = $dbw->tableName( 'page' );
2953 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2954 $acchitsTable = $dbw->tableName( 'acchits' );
2956 if( $wgHitcounterUpdateFreq <= 1 ) {
2957 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2961 # Not important enough to warrant an error page in case of failure
2962 $oldignore = $dbw->ignoreErrors( true );
2964 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2966 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2967 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2968 # Most of the time (or on SQL errors), skip row count check
2969 $dbw->ignoreErrors( $oldignore );
2973 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2974 $row = $dbw->fetchObject( $res );
2975 $rown = intval( $row->n
);
2976 if( $rown >= $wgHitcounterUpdateFreq ){
2977 wfProfileIn( 'Article::incViewCount-collect' );
2978 $old_user_abort = ignore_user_abort( true );
2980 if ($wgDBtype == 'mysql')
2981 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2982 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2983 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2984 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2986 $dbw->query("DELETE FROM $hitcounterTable");
2987 if ($wgDBtype == 'mysql') {
2988 $dbw->query('UNLOCK TABLES');
2989 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2990 'WHERE page_id = hc_id');
2993 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2994 "FROM $acchitsTable WHERE page_id = hc_id");
2996 $dbw->query("DROP TABLE $acchitsTable");
2998 ignore_user_abort( $old_user_abort );
2999 wfProfileOut( 'Article::incViewCount-collect' );
3001 $dbw->ignoreErrors( $oldignore );
3005 * The onArticle*() functions are supposed to be a kind of hooks
3006 * which should be called whenever any of the specified actions
3009 * This is a good place to put code to clear caches, for instance.
3011 * This is called on page move and undelete, as well as edit
3013 * @param $title_obj a title object
3016 static function onArticleCreate($title) {
3017 # The talk page isn't in the regular link tables, so we need to update manually:
3018 if ( $title->isTalkPage() ) {
3019 $other = $title->getSubjectPage();
3021 $other = $title->getTalkPage();
3023 $other->invalidateCache();
3024 $other->purgeSquid();
3026 $title->touchLinks();
3027 $title->purgeSquid();
3028 $title->deleteTitleProtection();
3031 static function onArticleDelete( $title ) {
3032 global $wgUseFileCache, $wgMessageCache;
3034 // Update existence markers on article/talk tabs...
3035 if( $title->isTalkPage() ) {
3036 $other = $title->getSubjectPage();
3038 $other = $title->getTalkPage();
3040 $other->invalidateCache();
3041 $other->purgeSquid();
3043 $title->touchLinks();
3044 $title->purgeSquid();
3047 if ( $wgUseFileCache ) {
3048 $cm = new HTMLFileCache( $title );
3049 @unlink
( $cm->fileCacheName() );
3052 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3053 $wgMessageCache->replace( $title->getDBkey(), false );
3055 if( $title->getNamespace() == NS_IMAGE
) {
3056 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3057 $update->doUpdate();
3062 * Purge caches on page update etc
3064 static function onArticleEdit( $title ) {
3065 global $wgDeferredUpdateList, $wgUseFileCache;
3067 // Invalidate caches of articles which include this page
3068 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3070 // Invalidate the caches of all pages which redirect here
3071 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3073 # Purge squid for this page only
3074 $title->purgeSquid();
3077 if ( $wgUseFileCache ) {
3078 $cm = new HTMLFileCache( $title );
3079 @unlink
( $cm->fileCacheName() );
3086 * Overriden by ImagePage class, only present here to avoid a fatal error
3087 * Called for ?action=revert
3089 public function revert(){
3091 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3095 * Info about this page
3096 * Called for ?action=info when $wgAllowPageInfo is on.
3101 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3103 if ( !$wgAllowPageInfo ) {
3104 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3108 $page = $this->mTitle
->getSubjectPage();
3110 $wgOut->setPagetitle( $page->getPrefixedText() );
3111 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3112 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3114 if( !$this->mTitle
->exists() ) {
3115 $wgOut->addHtml( '<div class="noarticletext">' );
3116 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3117 // This doesn't quite make sense; the user is asking for
3118 // information about the _page_, not the message... -- RC
3119 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3121 $msg = $wgUser->isLoggedIn()
3123 : 'noarticletextanon';
3124 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3126 $wgOut->addHtml( '</div>' );
3128 $dbr = wfGetDB( DB_SLAVE
);
3130 'wl_title' => $page->getDBkey(),
3131 'wl_namespace' => $page->getNamespace() );
3132 $numwatchers = $dbr->selectField(
3137 $this->getSelectOptions() );
3139 $pageInfo = $this->pageCountInfo( $page );
3140 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3142 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3143 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3145 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3147 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3149 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3151 $wgOut->addHTML( '</ul>' );
3157 * Return the total number of edits and number of unique editors
3158 * on a given page. If page does not exist, returns false.
3160 * @param Title $title
3164 function pageCountInfo( $title ) {
3165 $id = $title->getArticleId();
3170 $dbr = wfGetDB( DB_SLAVE
);
3172 $rev_clause = array( 'rev_page' => $id );
3174 $edits = $dbr->selectField(
3179 $this->getSelectOptions() );
3181 $authors = $dbr->selectField(
3183 'COUNT(DISTINCT rev_user_text)',
3186 $this->getSelectOptions() );
3188 return array( 'edits' => $edits, 'authors' => $authors );
3192 * Return a list of templates used by this article.
3193 * Uses the templatelinks table
3195 * @return array Array of Title objects
3197 function getUsedTemplates() {
3199 $id = $this->mTitle
->getArticleID();
3204 $dbr = wfGetDB( DB_SLAVE
);
3205 $res = $dbr->select( array( 'templatelinks' ),
3206 array( 'tl_namespace', 'tl_title' ),
3207 array( 'tl_from' => $id ),
3208 'Article:getUsedTemplates' );
3209 if ( false !== $res ) {
3210 if ( $dbr->numRows( $res ) ) {
3211 while ( $row = $dbr->fetchObject( $res ) ) {
3212 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3216 $dbr->freeResult( $res );
3221 * Returns a list of hidden categories this page is a member of.
3222 * Uses the page_props and categorylinks tables.
3224 * @return array Array of Title objects
3226 function getHiddenCategories() {
3228 $id = $this->mTitle
->getArticleID();
3233 $dbr = wfGetDB( DB_SLAVE
);
3234 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3236 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3237 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3238 'Article:getHiddenCategories' );
3239 if ( false !== $res ) {
3240 if ( $dbr->numRows( $res ) ) {
3241 while ( $row = $dbr->fetchObject( $res ) ) {
3242 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3246 $dbr->freeResult( $res );
3251 * Return an auto-generated summary if the text provided is a redirect.
3253 * @param string $text The wikitext to check
3254 * @return string '' or an appropriate summary
3256 public static function getRedirectAutosummary( $text ) {
3257 $rt = Title
::newFromRedirect( $text );
3258 if( is_object( $rt ) )
3259 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3265 * Return an auto-generated summary if the new text is much shorter than
3268 * @param string $oldtext The previous text of the page
3269 * @param string $text The submitted text of the page
3270 * @return string An appropriate autosummary, or an empty string.
3272 public static function getBlankingAutosummary( $oldtext, $text ) {
3273 if ($oldtext!='' && $text=='') {
3274 return wfMsgForContent('autosumm-blank');
3275 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3276 #Removing more than 90% of the article
3278 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3279 return wfMsgForContent('autosumm-replace', $truncatedtext);
3286 * Return an applicable autosummary if one exists for the given edit.
3287 * @param string $oldtext The previous text of the page.
3288 * @param string $newtext The submitted text of the page.
3289 * @param bitmask $flags A bitmask of flags submitted for the edit.
3290 * @return string An appropriate autosummary, or an empty string.
3292 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3294 # This code is UGLY UGLY UGLY.
3295 # Somebody PLEASE come up with a more elegant way to do it.
3297 #Redirect autosummaries
3298 $summary = self
::getRedirectAutosummary( $newtext );
3303 #Blanking autosummaries
3304 if (!($flags & EDIT_NEW
))
3305 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3310 #New page autosummaries
3311 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3312 #If they're making a new article, give its text, truncated, in the summary.
3314 $truncatedtext = $wgContLang->truncate(
3315 str_replace("\n", ' ', $newtext),
3316 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3318 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3328 * Add the primary page-view wikitext to the output buffer
3329 * Saves the text into the parser cache if possible.
3330 * Updates templatelinks if it is out of date.
3332 * @param string $text
3333 * @param bool $cache
3335 public function outputWikiText( $text, $cache = true ) {
3336 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3338 $popts = $wgOut->parserOptions();
3339 $popts->setTidy(true);
3340 $popts->enableLimitReport();
3341 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3342 $popts, true, true, $this->getRevIdFetched() );
3343 $popts->setTidy(false);
3344 $popts->enableLimitReport( false );
3345 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3346 $parserCache = ParserCache
::singleton();
3347 $parserCache->save( $parserOutput, $this, $wgUser );
3350 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3351 // templatelinks table may have become out of sync,
3352 // especially if using variable-based transclusions.
3353 // For paranoia, check if things have changed and if
3354 // so apply updates to the database. This will ensure
3355 // that cascaded protections apply as soon as the changes
3358 # Get templates from templatelinks
3359 $id = $this->mTitle
->getArticleID();
3361 $tlTemplates = array();
3363 $dbr = wfGetDB( DB_SLAVE
);
3364 $res = $dbr->select( array( 'templatelinks' ),
3365 array( 'tl_namespace', 'tl_title' ),
3366 array( 'tl_from' => $id ),
3367 'Article:getUsedTemplates' );
3371 if ( false !== $res ) {
3372 if ( $dbr->numRows( $res ) ) {
3373 while ( $row = $dbr->fetchObject( $res ) ) {
3374 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3379 # Get templates from parser output.
3380 $poTemplates_allns = $parserOutput->getTemplates();
3382 $poTemplates = array ();
3383 foreach ( $poTemplates_allns as $ns_templates ) {
3384 $poTemplates = array_merge( $poTemplates, $ns_templates );
3388 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3390 if ( count( $templates_diff ) > 0 ) {
3391 # Whee, link updates time.
3392 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3394 $dbw = wfGetDb( DB_MASTER
);
3403 $wgOut->addParserOutput( $parserOutput );
3407 * Update all the appropriate counts in the category table, given that
3408 * we've added the categories $added and deleted the categories $deleted.
3410 * @param $added array The names of categories that were added
3411 * @param $deleted array The names of categories that were deleted
3414 public function updateCategoryCounts( $added, $deleted ) {
3415 $ns = $this->mTitle
->getNamespace();
3416 $dbw = wfGetDB( DB_MASTER
);
3418 # First make sure the rows exist. If one of the "deleted" ones didn't
3419 # exist, we might legitimately not create it, but it's simpler to just
3420 # create it and then give it a negative value, since the value is bogus
3423 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3424 $insertCats = array_merge( $added, $deleted );
3425 if( !$insertCats ) {
3426 # Okay, nothing to do
3429 $insertRows = array();
3430 foreach( $insertCats as $cat ) {
3431 $insertRows[] = array( 'cat_title' => $cat );
3433 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3435 $addFields = array( 'cat_pages = cat_pages + 1' );
3436 $removeFields = array( 'cat_pages = cat_pages - 1' );
3437 if( $ns == NS_CATEGORY
) {
3438 $addFields[] = 'cat_subcats = cat_subcats + 1';
3439 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3440 } elseif( $ns == NS_IMAGE
) {
3441 $addFields[] = 'cat_files = cat_files + 1';
3442 $removeFields[] = 'cat_files = cat_files - 1';
3449 array( 'cat_title' => $added ),
3457 array( 'cat_title' => $deleted ),