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 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1164 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1165 wfProfileOut( __METHOD__
);
1166 return ( $dbw->affectedRows() != 0 );
1173 * If the given revision is newer than the currently set page_latest,
1174 * update the page record. Otherwise, do nothing.
1176 * @param Database $dbw
1177 * @param Revision $revision
1179 function updateIfNewerOn( &$dbw, $revision ) {
1180 wfProfileIn( __METHOD__
);
1182 $row = $dbw->selectRow(
1183 array( 'revision', 'page' ),
1184 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1186 'page_id' => $this->getId(),
1187 'page_latest=rev_id' ),
1190 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1191 wfProfileOut( __METHOD__
);
1194 $prev = $row->rev_id
;
1195 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1197 # No or missing previous revision; mark the page as new
1199 $lastRevIsRedirect = null;
1202 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1203 wfProfileOut( __METHOD__
);
1208 * @return string Complete article text, or null if error
1210 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1211 wfProfileIn( __METHOD__
);
1213 if( $section == '' ) {
1214 // Whole-page edit; let the text through unmolested.
1216 if( is_null( $edittime ) ) {
1217 $rev = Revision
::newFromTitle( $this->mTitle
);
1219 $dbw = wfGetDB( DB_MASTER
);
1220 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1222 if( is_null( $rev ) ) {
1223 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1224 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1227 $oldtext = $rev->getText();
1229 if( $section == 'new' ) {
1230 # Inserting a new section
1231 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1232 $text = strlen( trim( $oldtext ) ) > 0
1233 ?
"{$oldtext}\n\n{$subject}{$text}"
1234 : "{$subject}{$text}";
1236 # Replacing an existing section; roll out the big guns
1238 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1243 wfProfileOut( __METHOD__
);
1248 * @deprecated use Article::doEdit()
1250 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1251 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1252 ( $isminor ? EDIT_MINOR
: 0 ) |
1253 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1254 ( $bot ? EDIT_FORCE_BOT
: 0 );
1256 # If this is a comment, add the summary as headline
1257 if ( $comment && $summary != "" ) {
1258 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1261 $this->doEdit( $text, $summary, $flags );
1263 $dbw = wfGetDB( DB_MASTER
);
1265 if (!$this->mTitle
->userIsWatching()) {
1271 if ( $this->mTitle
->userIsWatching() ) {
1277 $this->doRedirect( $this->isRedirect( $text ) );
1281 * @deprecated use Article::doEdit()
1283 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1284 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1285 ( $minor ? EDIT_MINOR
: 0 ) |
1286 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1288 $good = $this->doEdit( $text, $summary, $flags );
1290 $dbw = wfGetDB( DB_MASTER
);
1292 if (!$this->mTitle
->userIsWatching()) {
1298 if ( $this->mTitle
->userIsWatching() ) {
1305 $extraq = ''; // Give extensions a chance to modify URL query on update
1306 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1308 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1316 * Change an existing article or create a new article. Updates RC and all necessary caches,
1317 * optionally via the deferred update array.
1319 * $wgUser must be set before calling this function.
1321 * @param string $text New text
1322 * @param string $summary Edit summary
1323 * @param integer $flags bitfield:
1325 * Article is known or assumed to be non-existent, create a new one
1327 * Article is known or assumed to be pre-existing, update it
1329 * Mark this edit minor, if the user is allowed to do so
1331 * Do not log the change in recentchanges
1333 * Mark the edit a "bot" edit regardless of user rights
1334 * EDIT_DEFER_UPDATES
1335 * Defer some of the updates until the end of index.php
1337 * Fill in blank summaries with generated text where possible
1339 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1340 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1341 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1342 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1343 * to MediaWiki's performance-optimised locking strategy.
1345 * @return bool success
1347 function doEdit( $text, $summary, $flags = 0 ) {
1348 global $wgUser, $wgDBtransactions;
1350 wfProfileIn( __METHOD__
);
1353 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1354 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1356 $flags |
= EDIT_UPDATE
;
1362 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1363 &$summary, $flags & EDIT_MINOR
,
1364 null, null, &$flags ) ) )
1366 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1367 wfProfileOut( __METHOD__
);
1371 # Silently ignore EDIT_MINOR if not allowed
1372 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1373 $bot = $flags & EDIT_FORCE_BOT
;
1375 $oldtext = $this->getContent();
1376 $oldsize = strlen( $oldtext );
1378 # Provide autosummaries if one is not provided.
1379 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1380 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1382 $editInfo = $this->prepareTextForEdit( $text );
1383 $text = $editInfo->pst
;
1384 $newsize = strlen( $text );
1386 $dbw = wfGetDB( DB_MASTER
);
1387 $now = wfTimestampNow();
1389 if ( $flags & EDIT_UPDATE
) {
1390 # Update article, but only if changed.
1392 # Make sure the revision is either completely inserted or not inserted at all
1393 if( !$wgDBtransactions ) {
1394 $userAbort = ignore_user_abort( true );
1400 $changed = ( strcmp( $text, $oldtext ) != 0 );
1403 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1404 - (int)$this->isCountable( $oldtext );
1405 $this->mTotalAdjustment
= 0;
1407 $lastRevision = $dbw->selectField(
1408 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1410 if ( !$lastRevision ) {
1411 # Article gone missing
1412 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1413 wfProfileOut( __METHOD__
);
1417 $revision = new Revision( array(
1418 'page' => $this->getId(),
1419 'comment' => $summary,
1420 'minor_edit' => $isminor,
1422 'parent_id' => $lastRevision
1426 $revisionId = $revision->insertOn( $dbw );
1429 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1432 /* Belated edit conflict! Run away!! */
1436 # Update recentchanges
1437 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1438 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1439 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1442 # Mark as patrolled if the user can do so
1443 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1444 RecentChange
::markPatrolled( $rcid );
1445 PatrolLog
::record( $rcid, true );
1448 $wgUser->incEditCount();
1453 // Keep the same revision ID, but do some updates on it
1454 $revisionId = $this->getRevIdFetched();
1455 // Update page_touched, this is usually implicit in the page update
1456 // Other cache updates are done in onArticleEdit()
1457 $this->mTitle
->invalidateCache();
1460 if( !$wgDBtransactions ) {
1461 ignore_user_abort( $userAbort );
1465 # Invalidate cache of this article and all pages using this article
1466 # as a template. Partly deferred.
1467 Article
::onArticleEdit( $this->mTitle
);
1469 # Update links tables, site stats, etc.
1470 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1473 # Create new article
1475 # Set statistics members
1476 # We work out if it's countable after PST to avoid counter drift
1477 # when articles are created with {{subst:}}
1478 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1479 $this->mTotalAdjustment
= 1;
1483 # Add the page record; stake our claim on this title!
1484 # This will fail with a database query exception if the article already exists
1485 $newid = $this->insertOn( $dbw );
1487 # Save the revision text...
1488 $revision = new Revision( array(
1490 'comment' => $summary,
1491 'minor_edit' => $isminor,
1494 $revisionId = $revision->insertOn( $dbw );
1496 $this->mTitle
->resetArticleID( $newid );
1498 # Update the page record with revision data
1499 $this->updateRevisionOn( $dbw, $revision, 0 );
1501 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1502 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1503 '', strlen( $text ), $revisionId );
1504 # Mark as patrolled if the user can
1505 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1506 RecentChange
::markPatrolled( $rcid );
1507 PatrolLog
::record( $rcid, true );
1510 $wgUser->incEditCount();
1513 # Update links, etc.
1514 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1517 Article
::onArticleCreate( $this->mTitle
);
1519 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1520 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1523 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1528 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1529 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1532 wfProfileOut( __METHOD__
);
1537 * @deprecated wrapper for doRedirect
1539 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1540 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1544 * Output a redirect back to the article.
1545 * This is typically used after an edit.
1547 * @param boolean $noRedir Add redirect=no
1548 * @param string $sectionAnchor section to redirect to, including "#"
1549 * @param string $extraq, extra query params
1551 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1554 $query = 'redirect=no';
1556 $query .= "&$query";
1560 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1564 * Mark this particular edit/page as patrolled
1566 function markpatrolled() {
1567 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1568 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1570 # Check patrol config options
1572 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1573 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1577 # If we haven't been given an rc_id value, we can't do anything
1578 $rcid = (int) $wgRequest->getVal('rcid');
1579 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1580 if ( is_null ( $rc ) )
1582 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1586 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1587 // Only new pages can be patrolled if the general patrolling is off....???
1588 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1590 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1595 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1597 if (count($permission_errors)>0)
1599 $wgOut->showPermissionsErrorPage( $permission_errors );
1603 # Handle the 'MarkPatrolled' hook
1604 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1608 #It would be nice to see where the user had actually come from, but for now just guess
1609 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1610 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1612 # If it's left up to us, check that the user is allowed to patrol this edit
1613 # If the user has the "autopatrol" right, then we'll assume there are no
1614 # other conditions stopping them doing so
1615 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1616 $rc = RecentChange
::newFromId( $rcid );
1617 # Graceful error handling, as we've done before here...
1618 # (If the recent change doesn't exist, then it doesn't matter whether
1619 # the user is allowed to patrol it or not; nothing is going to happen
1620 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1621 # The user made this edit, and can't patrol it
1622 # Tell them so, and then back off
1623 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1624 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1625 $wgOut->returnToMain( false, $return );
1630 # Check that the revision isn't patrolled already
1631 # Prevents duplicate log entries
1632 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1633 # Mark the edit as patrolled
1634 RecentChange
::markPatrolled( $rcid );
1635 PatrolLog
::record( $rcid );
1636 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1640 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1641 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1642 $wgOut->returnToMain( false, $return );
1646 * User-interface handler for the "watch" action
1651 global $wgUser, $wgOut;
1653 if ( $wgUser->isAnon() ) {
1654 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1657 if ( wfReadOnly() ) {
1658 $wgOut->readOnlyPage();
1662 if( $this->doWatch() ) {
1663 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1664 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1666 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1669 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1673 * Add this page to $wgUser's watchlist
1674 * @return bool true on successful watch operation
1676 function doWatch() {
1678 if( $wgUser->isAnon() ) {
1682 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1683 $wgUser->addWatch( $this->mTitle
);
1685 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1692 * User interface handler for the "unwatch" action.
1694 function unwatch() {
1696 global $wgUser, $wgOut;
1698 if ( $wgUser->isAnon() ) {
1699 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1702 if ( wfReadOnly() ) {
1703 $wgOut->readOnlyPage();
1707 if( $this->doUnwatch() ) {
1708 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1709 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1711 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1714 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1718 * Stop watching a page
1719 * @return bool true on successful unwatch
1721 function doUnwatch() {
1723 if( $wgUser->isAnon() ) {
1727 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1728 $wgUser->removeWatch( $this->mTitle
);
1730 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1737 * action=protect handler
1739 function protect() {
1740 $form = new ProtectionForm( $this );
1745 * action=unprotect handler (alias)
1747 function unprotect() {
1752 * Update the article's restriction field, and leave a log entry.
1754 * @param array $limit set of restriction keys
1755 * @param string $reason
1756 * @return bool true on success
1758 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1759 global $wgUser, $wgRestrictionTypes, $wgContLang;
1761 $id = $this->mTitle
->getArticleID();
1762 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1770 // Take this opportunity to purge out expired restrictions
1771 Title
::purgeExpiredRestrictions();
1773 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1774 # we expect a single selection, but the schema allows otherwise.
1776 foreach( $wgRestrictionTypes as $action )
1777 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1779 $current = Article
::flattenRestrictions( $current );
1780 $updated = Article
::flattenRestrictions( $limit );
1782 $changed = ( $current != $updated );
1783 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1784 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1785 $protect = ( $updated != '' );
1787 # If nothing's changed, do nothing
1789 global $wgGroupPermissions;
1790 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1792 $dbw = wfGetDB( DB_MASTER
);
1794 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1796 $expiry_description = '';
1797 if ( $encodedExpiry != 'infinity' ) {
1798 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1801 # Prepare a null revision to be added to the history
1802 $modified = $current != '' && $protect;
1804 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1806 $comment_type = 'unprotectedarticle';
1808 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1810 foreach( $limit as $action => $restrictions ) {
1811 # Check if the group level required to edit also can protect pages
1812 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1813 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1814 $wgGroupPermissions[$restrictions]['protect'] );
1817 $cascade_description = '';
1819 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1823 $comment .= ": $reason";
1825 $comment .= " [$updated]";
1826 if ( $expiry_description && $protect )
1827 $comment .= "$expiry_description";
1829 $comment .= "$cascade_description";
1831 # Update restrictions table
1832 foreach( $limit as $action => $restrictions ) {
1833 if ($restrictions != '' ) {
1834 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1835 array( 'pr_page' => $id, 'pr_type' => $action
1836 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1837 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1839 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1840 'pr_type' => $action ), __METHOD__
);
1844 # Insert a null revision
1845 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1846 $nullRevId = $nullRevision->insertOn( $dbw );
1848 # Update page record
1849 $dbw->update( 'page',
1851 'page_touched' => $dbw->timestamp(),
1852 'page_restrictions' => '',
1853 'page_latest' => $nullRevId
1854 ), array( /* WHERE */
1856 ), 'Article::protect'
1858 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1860 # Update the protection log
1861 $log = new LogPage( 'protect' );
1866 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1868 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1872 } # End "changed" check
1878 * Take an array of page restrictions and flatten it to a string
1879 * suitable for insertion into the page_restrictions field.
1880 * @param array $limit
1884 function flattenRestrictions( $limit ) {
1885 if( !is_array( $limit ) ) {
1886 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1890 foreach( $limit as $action => $restrictions ) {
1891 if( $restrictions != '' ) {
1892 $bits[] = "$action=$restrictions";
1895 return implode( ':', $bits );
1899 * Auto-generates a deletion reason
1900 * @param bool &$hasHistory Whether the page has a history
1902 public function generateReason(&$hasHistory)
1905 $dbw = wfGetDB(DB_MASTER
);
1906 // Get the last revision
1907 $rev = Revision
::newFromTitle($this->mTitle
);
1910 // Get the article's contents
1911 $contents = $rev->getText();
1913 // If the page is blank, use the text from the previous revision,
1914 // which can only be blank if there's a move/import/protect dummy revision involved
1917 $prev = $rev->getPrevious();
1920 $contents = $prev->getText();
1925 // Find out if there was only one contributor
1926 // Only scan the last 20 revisions
1928 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1929 array('LIMIT' => $limit));
1931 // This page has no revisions, which is very weird
1933 if($res->numRows() > 1)
1936 $hasHistory = false;
1937 $row = $dbw->fetchObject($res);
1938 $onlyAuthor = $row->rev_user_text
;
1939 // Try to find a second contributor
1940 while( $row = $dbw->fetchObject($res) ) {
1941 if($row->rev_user_text
!= $onlyAuthor) {
1942 $onlyAuthor = false;
1946 $dbw->freeResult($res);
1948 // Generate the summary with a '$1' placeholder
1950 // The current revision is blank and the one before is also
1951 // blank. It's just not our lucky day
1952 $reason = wfMsgForContent('exbeforeblank', '$1');
1955 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1957 $reason = wfMsgForContent('excontent', '$1');
1960 // Replace newlines with spaces to prevent uglyness
1961 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1962 // Calculate the maximum amount of chars to get
1963 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1964 $maxLength = 255 - (strlen($reason) - 2) - 3;
1965 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1966 // Remove possible unfinished links
1967 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1968 // Now replace the '$1' placeholder
1969 $reason = str_replace( '$1', $contents, $reason );
1975 * UI entry point for page deletion
1978 global $wgUser, $wgOut, $wgRequest;
1980 $confirm = $wgRequest->wasPosted() &&
1981 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1983 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1984 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1986 $reason = $this->DeleteReasonList
;
1988 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1989 // Entry from drop down menu + additional comment
1990 $reason .= ': ' . $this->DeleteReason
;
1991 } elseif ( $reason == 'other' ) {
1992 $reason = $this->DeleteReason
;
1994 # Flag to hide all contents of the archived revisions
1995 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
1997 # This code desperately needs to be totally rewritten
1999 # Read-only check...
2000 if ( wfReadOnly() ) {
2001 $wgOut->readOnlyPage();
2006 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2008 if (count($permission_errors)>0) {
2009 $wgOut->showPermissionsErrorPage( $permission_errors );
2013 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2015 # Better double-check that it hasn't been deleted yet!
2016 $dbw = wfGetDB( DB_MASTER
);
2017 $conds = $this->mTitle
->pageCond();
2018 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2019 if ( $latest === false ) {
2020 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2024 # Hack for big sites
2025 $bigHistory = $this->isBigDeletion();
2026 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2027 global $wgLang, $wgDeleteRevisionsLimit;
2028 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2029 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2034 $this->doDelete( $reason, $suppress );
2035 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2037 } elseif( $this->mTitle
->userIsWatching() ) {
2043 // Generate deletion reason
2044 $hasHistory = false;
2045 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2047 // If the page has a history, insert a warning
2048 if( $hasHistory && !$confirm ) {
2049 $skin=$wgUser->getSkin();
2050 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2052 global $wgLang, $wgDeleteRevisionsLimit;
2053 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2054 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2058 return $this->confirmDelete( '', $reason );
2062 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2064 function isBigDeletion() {
2065 global $wgDeleteRevisionsLimit;
2066 if( $wgDeleteRevisionsLimit ) {
2067 $revCount = $this->estimateRevisionCount();
2068 return $revCount > $wgDeleteRevisionsLimit;
2074 * @return int approximate revision count
2076 function estimateRevisionCount() {
2078 // For an exact count...
2079 //return $dbr->selectField( 'revision', 'COUNT(*)',
2080 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2081 return $dbr->estimateRowCount( 'revision', '*',
2082 array( 'rev_page' => $this->getId() ), __METHOD__
);
2086 * Get the last N authors
2087 * @param int $num Number of revisions to get
2088 * @param string $revLatest The latest rev_id, selected from the master (optional)
2089 * @return array Array of authors, duplicates not removed
2091 function getLastNAuthors( $num, $revLatest = 0 ) {
2092 wfProfileIn( __METHOD__
);
2094 // First try the slave
2095 // If that doesn't have the latest revision, try the master
2097 $db = wfGetDB( DB_SLAVE
);
2099 $res = $db->select( array( 'page', 'revision' ),
2100 array( 'rev_id', 'rev_user_text' ),
2102 'page_namespace' => $this->mTitle
->getNamespace(),
2103 'page_title' => $this->mTitle
->getDBkey(),
2104 'rev_page = page_id'
2105 ), __METHOD__
, $this->getSelectOptions( array(
2106 'ORDER BY' => 'rev_timestamp DESC',
2111 wfProfileOut( __METHOD__
);
2114 $row = $db->fetchObject( $res );
2115 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2116 $db = wfGetDB( DB_MASTER
);
2121 } while ( $continue );
2123 $authors = array( $row->rev_user_text
);
2124 while ( $row = $db->fetchObject( $res ) ) {
2125 $authors[] = $row->rev_user_text
;
2127 wfProfileOut( __METHOD__
);
2132 * Output deletion confirmation dialog
2133 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2134 * @param $reason string Prefilled reason
2136 function confirmDelete( $par, $reason ) {
2137 global $wgOut, $wgUser, $wgContLang;
2138 $align = $wgContLang->isRtl() ?
'left' : 'right';
2140 wfDebug( "Article::confirmDelete\n" );
2142 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2143 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2144 $wgOut->addWikiMsg( 'confirmdeletetext' );
2146 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2147 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2148 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2149 $suppress .= "</td></tr>";
2154 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2155 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2156 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2157 Xml
::openElement( 'table' ) .
2158 "<tr id=\"wpDeleteReasonListRow\">
2159 <td align='$align'>" .
2160 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2163 Xml
::listDropDown( 'wpDeleteReasonList',
2164 wfMsgForContent( 'deletereason-dropdown' ),
2165 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2168 <tr id=\"wpDeleteReasonRow\">
2169 <td align='$align'>" .
2170 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2173 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2179 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2186 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2189 Xml
::closeElement( 'table' ) .
2190 Xml
::closeElement( 'fieldset' ) .
2191 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2192 Xml
::closeElement( 'form' );
2194 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2195 $skin = $wgUser->getSkin();
2196 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2197 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2200 $wgOut->addHTML( $form );
2201 $this->showLogExtract( $wgOut );
2206 * Show relevant lines from the deletion log
2208 function showLogExtract( $out ) {
2209 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2210 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2215 * Perform a deletion and output success or failure messages
2217 function doDelete( $reason, $suppress = false ) {
2218 global $wgOut, $wgUser;
2219 wfDebug( __METHOD__
."\n" );
2221 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2222 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2223 $deleted = $this->mTitle
->getPrefixedText();
2225 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2226 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2228 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2230 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2231 $wgOut->returnToMain( false );
2232 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2234 $wgOut->showFatalError( wfMsg( 'cannotdelete' ).'<br/>'.wfMsg('cannotdelete-merge') );
2240 * Back-end article deletion
2241 * Deletes the article with database consistency, writes logs, purges caches
2244 function doDeleteArticle( $reason, $suppress = false ) {
2245 global $wgUseSquid, $wgDeferredUpdateList;
2246 global $wgUseTrackbacks;
2248 wfDebug( __METHOD__
."\n" );
2250 $dbw = wfGetDB( DB_MASTER
);
2251 $ns = $this->mTitle
->getNamespace();
2252 $t = $this->mTitle
->getDBkey();
2253 $id = $this->mTitle
->getArticleID();
2255 if ( $t == '' ||
$id == 0 ) {
2259 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2260 array_push( $wgDeferredUpdateList, $u );
2262 // Bitfields to further suppress the content
2265 // This should be 15...
2266 $bitfield |
= Revision
::DELETED_TEXT
;
2267 $bitfield |
= Revision
::DELETED_COMMENT
;
2268 $bitfield |
= Revision
::DELETED_USER
;
2269 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2271 $bitfield = 'rev_deleted';
2274 // For now, shunt the revision data into the archive table.
2275 // Text is *not* removed from the text table; bulk storage
2276 // is left intact to avoid breaking block-compression or
2277 // immutable storage schemes.
2279 // For backwards compatibility, note that some older archive
2280 // table entries will have ar_text and ar_flags fields still.
2282 // In the future, we may keep revisions and mark them with
2283 // the rev_deleted field, which is reserved for this purpose.
2284 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2286 'ar_namespace' => 'page_namespace',
2287 'ar_title' => 'page_title',
2288 'ar_comment' => 'rev_comment',
2289 'ar_user' => 'rev_user',
2290 'ar_user_text' => 'rev_user_text',
2291 'ar_timestamp' => 'rev_timestamp',
2292 'ar_minor_edit' => 'rev_minor_edit',
2293 'ar_rev_id' => 'rev_id',
2294 'ar_text_id' => 'rev_text_id',
2295 'ar_text' => '\'\'', // Be explicit to appease
2296 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2297 'ar_len' => 'rev_len',
2298 'ar_page_id' => 'page_id',
2299 'ar_deleted' => $bitfield
2302 'page_id = rev_page'
2306 # Delete restrictions for it
2307 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2309 # Fix category table counts
2311 $res = $dbw->select( 'categorylinks', 'cl_to',
2312 array( 'cl_from' => $id ), __METHOD__
);
2313 foreach( $res as $row ) {
2314 $cats []= $row->cl_to
;
2316 $this->updateCategoryCounts( array(), $cats );
2318 # Now that it's safely backed up, delete it
2319 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2321 # If using cascading deletes, we can skip some explicit deletes
2322 if ( !$dbw->cascadingDeletes() ) {
2323 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2325 if ($wgUseTrackbacks)
2326 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2328 # Delete outgoing links
2329 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2330 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2331 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2332 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2333 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2334 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2335 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2338 # If using cleanup triggers, we can skip some manual deletes
2339 if ( !$dbw->cleanupTriggers() ) {
2341 # Clean up recentchanges entries...
2342 $dbw->delete( 'recentchanges',
2343 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2348 Article
::onArticleDelete( $this->mTitle
);
2350 # Clear the cached article id so the interface doesn't act like we exist
2351 $this->mTitle
->resetArticleID( 0 );
2352 $this->mTitle
->mArticleID
= 0;
2354 # Log the deletion, if the page was suppressed, log it at Oversight instead
2355 $logtype = $suppress ?
'suppress' : 'delete';
2356 $log = new LogPage( $logtype );
2357 $log->addEntry( 'delete', $this->mTitle
, $reason );
2363 * Roll back the most recent consecutive set of edits to a page
2364 * from the same user; fails if there are no eligible edits to
2365 * roll back to, e.g. user is the sole contributor. This function
2366 * performs permissions checks on $wgUser, then calls commitRollback()
2367 * to do the dirty work
2369 * @param string $fromP - Name of the user whose edits to rollback.
2370 * @param string $summary - Custom summary. Set to default summary if empty.
2371 * @param string $token - Rollback token.
2372 * @param bool $bot - If true, mark all reverted edits as bot.
2374 * @param array $resultDetails contains result-specific array of additional values
2375 * 'alreadyrolled' : 'current' (rev)
2376 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2378 * @return array of errors, each error formatted as
2379 * array(messagekey, param1, param2, ...).
2380 * On success, the array is empty. This array can also be passed to
2381 * OutputPage::showPermissionsErrorPage().
2383 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2385 $resultDetails = null;
2388 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2389 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2390 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2391 $errors[] = array( 'sessionfailure' );
2393 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2394 $errors[] = array( 'actionthrottledtext' );
2396 # If there were errors, bail out now
2400 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2404 * Backend implementation of doRollback(), please refer there for parameter
2405 * and return value documentation
2407 * NOTE: This function does NOT check ANY permissions, it just commits the
2408 * rollback to the DB Therefore, you should only call this function direct-
2409 * ly if you want to use custom permissions checks. If you don't, use
2410 * doRollback() instead.
2412 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2413 global $wgUseRCPatrol, $wgUser;
2414 $dbw = wfGetDB( DB_MASTER
);
2416 if( wfReadOnly() ) {
2417 return array( array( 'readonlytext' ) );
2420 # Get the last editor
2421 $current = Revision
::newFromTitle( $this->mTitle
);
2422 if( is_null( $current ) ) {
2423 # Something wrong... no page?
2424 return array(array('notanarticle'));
2427 $from = str_replace( '_', ' ', $fromP );
2428 if( $from != $current->getUserText() ) {
2429 $resultDetails = array( 'current' => $current );
2430 return array(array('alreadyrolled',
2431 htmlspecialchars($this->mTitle
->getPrefixedText()),
2432 htmlspecialchars($fromP),
2433 htmlspecialchars($current->getUserText())
2437 # Get the last edit not by this guy
2438 $user = intval( $current->getUser() );
2439 $user_text = $dbw->addQuotes( $current->getUserText() );
2440 $s = $dbw->selectRow( 'revision',
2441 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2442 array( 'rev_page' => $current->getPage(),
2443 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2445 array( 'USE INDEX' => 'page_timestamp',
2446 'ORDER BY' => 'rev_timestamp DESC' )
2448 if( $s === false ) {
2449 # No one else ever edited this page
2450 return array(array('cantrollback'));
2451 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2452 # Only admins can see this text
2453 return array(array('notvisiblerev'));
2457 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2458 # Mark all reverted edits as bot
2461 if ( $wgUseRCPatrol ) {
2462 # Mark all reverted edits as patrolled
2463 $set['rc_patrolled'] = 1;
2467 $dbw->update( 'recentchanges', $set,
2469 'rc_cur_id' => $current->getPage(),
2470 'rc_user_text' => $current->getUserText(),
2471 "rc_timestamp > '{$s->rev_timestamp}'",
2476 # Generate the edit summary if necessary
2477 $target = Revision
::newFromId( $s->rev_id
);
2478 if( empty( $summary ) )
2481 $summary = wfMsgForContent( 'revertpage',
2482 $target->getUserText(), $from,
2483 $s->rev_id
, $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2484 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2489 $flags = EDIT_UPDATE
;
2491 if ($wgUser->isAllowed('minoredit'))
2492 $flags |
= EDIT_MINOR
;
2494 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2495 $flags |
= EDIT_FORCE_BOT
;
2496 $this->doEdit( $target->getText(), $summary, $flags );
2498 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2500 $resultDetails = array(
2501 'summary' => $summary,
2502 'current' => $current,
2503 'target' => $target,
2509 * User interface for rollback operations
2511 function rollback() {
2512 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2515 $result = $this->doRollback(
2516 $wgRequest->getVal( 'from' ),
2517 $wgRequest->getText( 'summary' ),
2518 $wgRequest->getVal( 'token' ),
2519 $wgRequest->getBool( 'bot' ),
2523 if( in_array( array( 'blocked' ), $result ) ) {
2524 $wgOut->blockedPage();
2527 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2528 $wgOut->rateLimited();
2531 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2532 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2533 $errArray = $result[0];
2534 $errMsg = array_shift( $errArray );
2535 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2536 if( isset( $details['current'] ) ){
2537 $current = $details['current'];
2538 if( $current->getComment() != '' ) {
2539 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2544 # Display permissions errors before read-only message -- there's no
2545 # point in misleading the user into thinking the inability to rollback
2546 # is only temporary.
2547 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2548 # array_diff is completely broken for arrays of arrays, sigh. Re-
2549 # move any 'readonlytext' error manually.
2551 foreach( $result as $error ) {
2552 if( $error != array( 'readonlytext' ) ) {
2556 $wgOut->showPermissionsErrorPage( $out );
2559 if( $result == array( array('readonlytext') ) ) {
2560 $wgOut->readOnlyPage();
2564 $current = $details['current'];
2565 $target = $details['target'];
2566 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2567 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2568 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2569 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2570 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2571 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2572 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2573 $wgOut->returnToMain( false, $this->mTitle
);
2578 * Do standard deferred updates after page view
2581 function viewUpdates() {
2582 global $wgDeferredUpdateList;
2584 if ( 0 != $this->getID() ) {
2585 global $wgDisableCounters;
2586 if( !$wgDisableCounters ) {
2587 Article
::incViewCount( $this->getID() );
2588 $u = new SiteStatsUpdate( 1, 0, 0 );
2589 array_push( $wgDeferredUpdateList, $u );
2593 # Update newtalk / watchlist notification status
2595 $wgUser->clearNotification( $this->mTitle
);
2599 * Prepare text which is about to be saved.
2600 * Returns a stdclass with source, pst and output members
2602 function prepareTextForEdit( $text, $revid=null ) {
2603 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2605 return $this->mPreparedEdit
;
2608 $edit = (object)array();
2609 $edit->revid
= $revid;
2610 $edit->newText
= $text;
2611 $edit->pst
= $this->preSaveTransform( $text );
2612 $options = new ParserOptions
;
2613 $options->setTidy( true );
2614 $options->enableLimitReport();
2615 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2616 $edit->oldText
= $this->getContent();
2617 $this->mPreparedEdit
= $edit;
2622 * Do standard deferred updates after page edit.
2623 * Update links tables, site stats, search index and message cache.
2624 * Every 100th edit, prune the recent changes table.
2627 * @param $text New text of the article
2628 * @param $summary Edit summary
2629 * @param $minoredit Minor edit
2630 * @param $timestamp_of_pagechange Timestamp associated with the page change
2631 * @param $newid rev_id value of the new revision
2632 * @param $changed Whether or not the content actually changed
2634 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2635 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2637 wfProfileIn( __METHOD__
);
2640 # Be careful not to double-PST: $text is usually already PST-ed once
2641 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2642 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2643 $editInfo = $this->prepareTextForEdit( $text, $newid );
2645 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2646 $editInfo = $this->mPreparedEdit
;
2649 # Save it to the parser cache
2650 if ( $wgEnableParserCache ) {
2651 $parserCache = ParserCache
::singleton();
2652 $parserCache->save( $editInfo->output
, $this, $wgUser );
2655 # Update the links tables
2656 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2659 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2660 if ( 0 == mt_rand( 0, 99 ) ) {
2661 // Flush old entries from the `recentchanges` table; we do this on
2662 // random requests so as to avoid an increase in writes for no good reason
2664 $dbw = wfGetDB( DB_MASTER
);
2665 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2666 $recentchanges = $dbw->tableName( 'recentchanges' );
2667 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2668 $dbw->query( $sql );
2672 $id = $this->getID();
2673 $title = $this->mTitle
->getPrefixedDBkey();
2674 $shortTitle = $this->mTitle
->getDBkey();
2677 wfProfileOut( __METHOD__
);
2681 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2682 array_push( $wgDeferredUpdateList, $u );
2683 $u = new SearchUpdate( $id, $title, $text );
2684 array_push( $wgDeferredUpdateList, $u );
2686 # If this is another user's talk page, update newtalk
2687 # Don't do this if $changed = false otherwise some idiot can null-edit a
2688 # load of user talk pages and piss people off, nor if it's a minor edit
2689 # by a properly-flagged bot.
2690 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2691 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2692 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2693 $other = User
::newFromName( $shortTitle );
2694 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2695 // An anonymous user
2696 $other = new User();
2697 $other->setName( $shortTitle );
2700 $other->setNewtalk( true );
2705 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2706 $wgMessageCache->replace( $shortTitle, $text );
2709 wfProfileOut( __METHOD__
);
2713 * Perform article updates on a special page creation.
2715 * @param Revision $rev
2717 * @todo This is a shitty interface function. Kill it and replace the
2718 * other shitty functions like editUpdates and such so it's not needed
2721 function createUpdates( $rev ) {
2722 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2723 $this->mTotalAdjustment
= 1;
2724 $this->editUpdates( $rev->getText(), $rev->getComment(),
2725 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2729 * Generate the navigation links when browsing through an article revisions
2730 * It shows the information as:
2731 * Revision as of \<date\>; view current revision
2732 * \<- Previous version | Next Version -\>
2735 * @param string $oldid Revision ID of this article revision
2737 function setOldSubtitle( $oldid=0 ) {
2738 global $wgLang, $wgOut, $wgUser;
2740 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2744 $revision = Revision
::newFromId( $oldid );
2746 $current = ( $oldid == $this->mLatest
);
2747 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2748 $sk = $wgUser->getSkin();
2750 ?
wfMsg( 'currentrevisionlink' )
2751 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2754 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2755 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2757 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2758 : wfMsg( 'previousrevision' );
2760 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2762 $nextlink = $current
2763 ?
wfMsg( 'nextrevision' )
2764 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2765 $nextdiff = $current
2767 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2770 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2771 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2772 if( $revision->isCurrent() ) {
2773 // We don't handle top deleted edits too well
2774 $cdel = wfMsgHtml('rev-delundel');
2775 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2776 // If revision was hidden from sysops
2777 $cdel = wfMsgHtml('rev-delundel');
2779 $cdel = $sk->makeKnownLinkObj( $revdel,
2780 wfMsgHtml('rev-delundel'),
2781 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2782 '&oldid=' . urlencode( $oldid ) );
2783 // Bolden oversighted content
2784 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2785 $cdel = "<strong>$cdel</strong>";
2787 $cdel = "(<small>$cdel</small>) ";
2789 # Show user links if allowed to see them. Normally they
2790 # are hidden regardless, but since we can already see the text here...
2791 $userlinks = $sk->revUserTools( $revision, false );
2793 $m = wfMsg( 'revision-info-current' );
2794 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2795 ?
'revision-info-current'
2798 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2800 "\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";
2801 $wgOut->setSubtitle( $r );
2805 * This function is called right before saving the wikitext,
2806 * so we can do things like signatures and links-in-context.
2808 * @param string $text
2810 function preSaveTransform( $text ) {
2811 global $wgParser, $wgUser;
2812 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2815 /* Caching functions */
2818 * checkLastModified returns true if it has taken care of all
2819 * output to the client that is necessary for this request.
2820 * (that is, it has sent a cached version of the page)
2822 function tryFileCache() {
2823 static $called = false;
2825 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2829 if($this->isFileCacheable()) {
2830 $touched = $this->mTouched
;
2831 $cache = new HTMLFileCache( $this->mTitle
);
2832 if($cache->isFileCacheGood( $touched )) {
2833 wfDebug( "Article::tryFileCache(): about to load file\n" );
2834 $cache->loadFromFileCache();
2837 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2838 ob_start( array(&$cache, 'saveToFileCache' ) );
2841 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2846 * Check if the page can be cached
2849 function isFileCacheable() {
2850 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2851 $action = $wgRequest->getVal( 'action' );
2852 $oldid = $wgRequest->getVal( 'oldid' );
2853 $diff = $wgRequest->getVal( 'diff' );
2854 $redirect = $wgRequest->getVal( 'redirect' );
2855 $printable = $wgRequest->getVal( 'printable' );
2856 $page = $wgRequest->getVal( 'page' );
2858 //check for non-standard user language; this covers uselang,
2859 //and extensions for auto-detecting user language.
2860 $ulang = $wgLang->getCode();
2861 $clang = $wgContLang->getCode();
2863 $cacheable = $wgUseFileCache
2864 && (!$wgShowIPinHeader)
2865 && ($this->getID() != 0)
2866 && ($wgUser->isAnon())
2867 && (!$wgUser->getNewtalk())
2868 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2869 && (empty( $action ) ||
$action == 'view')
2872 && (!isset($redirect))
2873 && (!isset($printable))
2875 && (!$this->mRedirectedFrom
)
2876 && ($ulang === $clang);
2879 //extension may have reason to disable file caching on some pages.
2880 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2887 * Loads page_touched and returns a value indicating if it should be used
2890 function checkTouched() {
2891 if( !$this->mDataLoaded
) {
2892 $this->loadPageData();
2894 return !$this->mIsRedirect
;
2898 * Get the page_touched field
2900 function getTouched() {
2901 # Ensure that page data has been loaded
2902 if( !$this->mDataLoaded
) {
2903 $this->loadPageData();
2905 return $this->mTouched
;
2909 * Get the page_latest field
2911 function getLatest() {
2912 if ( !$this->mDataLoaded
) {
2913 $this->loadPageData();
2915 return $this->mLatest
;
2919 * Edit an article without doing all that other stuff
2920 * The article must already exist; link tables etc
2921 * are not updated, caches are not flushed.
2923 * @param string $text text submitted
2924 * @param string $comment comment submitted
2925 * @param bool $minor whereas it's a minor modification
2927 function quickEdit( $text, $comment = '', $minor = 0 ) {
2928 wfProfileIn( __METHOD__
);
2930 $dbw = wfGetDB( DB_MASTER
);
2932 $revision = new Revision( array(
2933 'page' => $this->getId(),
2935 'comment' => $comment,
2936 'minor_edit' => $minor ?
1 : 0,
2938 $revision->insertOn( $dbw );
2939 $this->updateRevisionOn( $dbw, $revision );
2942 wfProfileOut( __METHOD__
);
2946 * Used to increment the view counter
2949 * @param integer $id article id
2951 function incViewCount( $id ) {
2952 $id = intval( $id );
2953 global $wgHitcounterUpdateFreq, $wgDBtype;
2955 $dbw = wfGetDB( DB_MASTER
);
2956 $pageTable = $dbw->tableName( 'page' );
2957 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2958 $acchitsTable = $dbw->tableName( 'acchits' );
2960 if( $wgHitcounterUpdateFreq <= 1 ) {
2961 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2965 # Not important enough to warrant an error page in case of failure
2966 $oldignore = $dbw->ignoreErrors( true );
2968 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2970 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2971 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2972 # Most of the time (or on SQL errors), skip row count check
2973 $dbw->ignoreErrors( $oldignore );
2977 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2978 $row = $dbw->fetchObject( $res );
2979 $rown = intval( $row->n
);
2980 if( $rown >= $wgHitcounterUpdateFreq ){
2981 wfProfileIn( 'Article::incViewCount-collect' );
2982 $old_user_abort = ignore_user_abort( true );
2984 if ($wgDBtype == 'mysql')
2985 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2986 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2987 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2988 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2990 $dbw->query("DELETE FROM $hitcounterTable");
2991 if ($wgDBtype == 'mysql') {
2992 $dbw->query('UNLOCK TABLES');
2993 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2994 'WHERE page_id = hc_id');
2997 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2998 "FROM $acchitsTable WHERE page_id = hc_id");
3000 $dbw->query("DROP TABLE $acchitsTable");
3002 ignore_user_abort( $old_user_abort );
3003 wfProfileOut( 'Article::incViewCount-collect' );
3005 $dbw->ignoreErrors( $oldignore );
3009 * The onArticle*() functions are supposed to be a kind of hooks
3010 * which should be called whenever any of the specified actions
3013 * This is a good place to put code to clear caches, for instance.
3015 * This is called on page move and undelete, as well as edit
3017 * @param $title_obj a title object
3020 static function onArticleCreate($title) {
3021 # The talk page isn't in the regular link tables, so we need to update manually:
3022 if ( $title->isTalkPage() ) {
3023 $other = $title->getSubjectPage();
3025 $other = $title->getTalkPage();
3027 $other->invalidateCache();
3028 $other->purgeSquid();
3030 $title->touchLinks();
3031 $title->purgeSquid();
3032 $title->deleteTitleProtection();
3035 static function onArticleDelete( $title ) {
3036 global $wgUseFileCache, $wgMessageCache;
3038 // Update existence markers on article/talk tabs...
3039 if( $title->isTalkPage() ) {
3040 $other = $title->getSubjectPage();
3042 $other = $title->getTalkPage();
3044 $other->invalidateCache();
3045 $other->purgeSquid();
3047 $title->touchLinks();
3048 $title->purgeSquid();
3051 if ( $wgUseFileCache ) {
3052 $cm = new HTMLFileCache( $title );
3053 @unlink
( $cm->fileCacheName() );
3056 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3057 $wgMessageCache->replace( $title->getDBkey(), false );
3059 if( $title->getNamespace() == NS_IMAGE
) {
3060 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3061 $update->doUpdate();
3066 * Purge caches on page update etc
3068 static function onArticleEdit( $title ) {
3069 global $wgDeferredUpdateList, $wgUseFileCache;
3071 // Invalidate caches of articles which include this page
3072 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3074 // Invalidate the caches of all pages which redirect here
3075 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3077 # Purge squid for this page only
3078 $title->purgeSquid();
3081 if ( $wgUseFileCache ) {
3082 $cm = new HTMLFileCache( $title );
3083 @unlink
( $cm->fileCacheName() );
3090 * Overriden by ImagePage class, only present here to avoid a fatal error
3091 * Called for ?action=revert
3093 public function revert(){
3095 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3099 * Info about this page
3100 * Called for ?action=info when $wgAllowPageInfo is on.
3105 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3107 if ( !$wgAllowPageInfo ) {
3108 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3112 $page = $this->mTitle
->getSubjectPage();
3114 $wgOut->setPagetitle( $page->getPrefixedText() );
3115 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3116 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3118 if( !$this->mTitle
->exists() ) {
3119 $wgOut->addHtml( '<div class="noarticletext">' );
3120 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3121 // This doesn't quite make sense; the user is asking for
3122 // information about the _page_, not the message... -- RC
3123 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3125 $msg = $wgUser->isLoggedIn()
3127 : 'noarticletextanon';
3128 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3130 $wgOut->addHtml( '</div>' );
3132 $dbr = wfGetDB( DB_SLAVE
);
3134 'wl_title' => $page->getDBkey(),
3135 'wl_namespace' => $page->getNamespace() );
3136 $numwatchers = $dbr->selectField(
3141 $this->getSelectOptions() );
3143 $pageInfo = $this->pageCountInfo( $page );
3144 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3146 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3147 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3149 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3151 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3153 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3155 $wgOut->addHTML( '</ul>' );
3161 * Return the total number of edits and number of unique editors
3162 * on a given page. If page does not exist, returns false.
3164 * @param Title $title
3168 function pageCountInfo( $title ) {
3169 $id = $title->getArticleId();
3174 $dbr = wfGetDB( DB_SLAVE
);
3176 $rev_clause = array( 'rev_page' => $id );
3178 $edits = $dbr->selectField(
3183 $this->getSelectOptions() );
3185 $authors = $dbr->selectField(
3187 'COUNT(DISTINCT rev_user_text)',
3190 $this->getSelectOptions() );
3192 return array( 'edits' => $edits, 'authors' => $authors );
3196 * Return a list of templates used by this article.
3197 * Uses the templatelinks table
3199 * @return array Array of Title objects
3201 function getUsedTemplates() {
3203 $id = $this->mTitle
->getArticleID();
3208 $dbr = wfGetDB( DB_SLAVE
);
3209 $res = $dbr->select( array( 'templatelinks' ),
3210 array( 'tl_namespace', 'tl_title' ),
3211 array( 'tl_from' => $id ),
3212 'Article:getUsedTemplates' );
3213 if ( false !== $res ) {
3214 if ( $dbr->numRows( $res ) ) {
3215 while ( $row = $dbr->fetchObject( $res ) ) {
3216 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3220 $dbr->freeResult( $res );
3225 * Returns a list of hidden categories this page is a member of.
3226 * Uses the page_props and categorylinks tables.
3228 * @return array Array of Title objects
3230 function getHiddenCategories() {
3232 $id = $this->mTitle
->getArticleID();
3237 $dbr = wfGetDB( DB_SLAVE
);
3238 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3240 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3241 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3242 'Article:getHiddenCategories' );
3243 if ( false !== $res ) {
3244 if ( $dbr->numRows( $res ) ) {
3245 while ( $row = $dbr->fetchObject( $res ) ) {
3246 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3250 $dbr->freeResult( $res );
3255 * Return an auto-generated summary if the text provided is a redirect.
3257 * @param string $text The wikitext to check
3258 * @return string '' or an appropriate summary
3260 public static function getRedirectAutosummary( $text ) {
3261 $rt = Title
::newFromRedirect( $text );
3262 if( is_object( $rt ) )
3263 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3269 * Return an auto-generated summary if the new text is much shorter than
3272 * @param string $oldtext The previous text of the page
3273 * @param string $text The submitted text of the page
3274 * @return string An appropriate autosummary, or an empty string.
3276 public static function getBlankingAutosummary( $oldtext, $text ) {
3277 if ($oldtext!='' && $text=='') {
3278 return wfMsgForContent('autosumm-blank');
3279 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3280 #Removing more than 90% of the article
3282 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3283 return wfMsgForContent('autosumm-replace', $truncatedtext);
3290 * Return an applicable autosummary if one exists for the given edit.
3291 * @param string $oldtext The previous text of the page.
3292 * @param string $newtext The submitted text of the page.
3293 * @param bitmask $flags A bitmask of flags submitted for the edit.
3294 * @return string An appropriate autosummary, or an empty string.
3296 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3298 # This code is UGLY UGLY UGLY.
3299 # Somebody PLEASE come up with a more elegant way to do it.
3301 #Redirect autosummaries
3302 $summary = self
::getRedirectAutosummary( $newtext );
3307 #Blanking autosummaries
3308 if (!($flags & EDIT_NEW
))
3309 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3314 #New page autosummaries
3315 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3316 #If they're making a new article, give its text, truncated, in the summary.
3318 $truncatedtext = $wgContLang->truncate(
3319 str_replace("\n", ' ', $newtext),
3320 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3322 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3332 * Add the primary page-view wikitext to the output buffer
3333 * Saves the text into the parser cache if possible.
3334 * Updates templatelinks if it is out of date.
3336 * @param string $text
3337 * @param bool $cache
3339 public function outputWikiText( $text, $cache = true ) {
3340 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3342 $popts = $wgOut->parserOptions();
3343 $popts->setTidy(true);
3344 $popts->enableLimitReport();
3345 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3346 $popts, true, true, $this->getRevIdFetched() );
3347 $popts->setTidy(false);
3348 $popts->enableLimitReport( false );
3349 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3350 $parserCache = ParserCache
::singleton();
3351 $parserCache->save( $parserOutput, $this, $wgUser );
3354 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3355 // templatelinks table may have become out of sync,
3356 // especially if using variable-based transclusions.
3357 // For paranoia, check if things have changed and if
3358 // so apply updates to the database. This will ensure
3359 // that cascaded protections apply as soon as the changes
3362 # Get templates from templatelinks
3363 $id = $this->mTitle
->getArticleID();
3365 $tlTemplates = array();
3367 $dbr = wfGetDB( DB_SLAVE
);
3368 $res = $dbr->select( array( 'templatelinks' ),
3369 array( 'tl_namespace', 'tl_title' ),
3370 array( 'tl_from' => $id ),
3371 'Article:getUsedTemplates' );
3375 if ( false !== $res ) {
3376 if ( $dbr->numRows( $res ) ) {
3377 while ( $row = $dbr->fetchObject( $res ) ) {
3378 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3383 # Get templates from parser output.
3384 $poTemplates_allns = $parserOutput->getTemplates();
3386 $poTemplates = array ();
3387 foreach ( $poTemplates_allns as $ns_templates ) {
3388 $poTemplates = array_merge( $poTemplates, $ns_templates );
3392 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3394 if ( count( $templates_diff ) > 0 ) {
3395 # Whee, link updates time.
3396 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3398 $dbw = wfGetDb( DB_MASTER
);
3407 $wgOut->addParserOutput( $parserOutput );
3411 * Update all the appropriate counts in the category table, given that
3412 * we've added the categories $added and deleted the categories $deleted.
3414 * @param $added array The names of categories that were added
3415 * @param $deleted array The names of categories that were deleted
3418 public function updateCategoryCounts( $added, $deleted ) {
3419 $ns = $this->mTitle
->getNamespace();
3420 $dbw = wfGetDB( DB_MASTER
);
3422 # First make sure the rows exist. If one of the "deleted" ones didn't
3423 # exist, we might legitimately not create it, but it's simpler to just
3424 # create it and then give it a negative value, since the value is bogus
3427 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3428 $insertCats = array_merge( $added, $deleted );
3429 if( !$insertCats ) {
3430 # Okay, nothing to do
3433 $insertRows = array();
3434 foreach( $insertCats as $cat ) {
3435 $insertRows[] = array( 'cat_title' => $cat );
3437 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3439 $addFields = array( 'cat_pages = cat_pages + 1' );
3440 $removeFields = array( 'cat_pages = cat_pages - 1' );
3441 if( $ns == NS_CATEGORY
) {
3442 $addFields[] = 'cat_subcats = cat_subcats + 1';
3443 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3444 } elseif( $ns == NS_IMAGE
) {
3445 $addFields[] = 'cat_files = cat_files + 1';
3446 $removeFields[] = 'cat_files = cat_files - 1';
3453 array( 'cat_title' => $added ),
3461 array( 'cat_title' => $deleted ),