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->replace('redirect', array('rd_from'), array(
100 'rd_from' => $this->getID(),
101 'rd_namespace' => $retval->getNamespace(),
102 'rd_title' => $retval->getDBKey()
108 * Get the Title object this page redirects to
110 * @return mixed false, Title of in-wiki target, or string with URL
112 function followRedirect() {
113 $text = $this->getContent();
114 $rt = Title
::newFromRedirect( $text );
116 # process if title object is valid and not special:userlogout
118 if( $rt->getInterwiki() != '' ) {
119 if( $rt->isLocal() ) {
120 // Offsite wikis need an HTTP redirect.
122 // This can be hard to reverse and may produce loops,
123 // so they may be disabled in the site configuration.
125 $source = $this->mTitle
->getFullURL( 'redirect=no' );
126 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
129 if( $rt->getNamespace() == NS_SPECIAL
) {
130 // Gotta handle redirects to special pages differently:
131 // Fill the HTTP response "Location" header and ignore
132 // the rest of the page we're on.
134 // This can be hard to reverse, so they may be disabled.
136 if( $rt->isSpecial( 'Userlogout' ) ) {
139 return $rt->getFullURL();
146 // No or invalid redirect
151 * get the title object of the article
153 function getTitle() {
154 return $this->mTitle
;
162 $this->mDataLoaded
= false;
163 $this->mContentLoaded
= false;
165 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
166 $this->mRedirectedFrom
= null; # Title object if set
167 $this->mRedirectTarget
= null; # Title object if set
169 $this->mTimestamp
= $this->mComment
= '';
170 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
171 $this->mTouched
= '19700101000000';
172 $this->mForUpdate
= false;
173 $this->mIsRedirect
= false;
174 $this->mRevIdFetched
= 0;
175 $this->mRedirectUrl
= false;
176 $this->mLatest
= false;
177 $this->mPreparedEdit
= false;
181 * Note that getContent/loadContent do not follow redirects anymore.
182 * If you need to fetch redirectable content easily, try
183 * the shortcut in Article::followContent()
185 * @todo There are still side-effects in this!
186 * In general, you should use the Revision class, not Article,
187 * to fetch text for purposes other than page views.
189 * @return Return the text of this revision
191 function getContent() {
192 global $wgUser, $wgOut, $wgMessageCache;
194 wfProfileIn( __METHOD__
);
196 if ( 0 == $this->getID() ) {
197 wfProfileOut( __METHOD__
);
198 $wgOut->setRobotpolicy( 'noindex,nofollow' );
200 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
201 $wgMessageCache->loadAllMessages();
202 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
204 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
207 return "<div class='noarticletext'>\n$ret\n</div>";
209 $this->loadContent();
210 wfProfileOut( __METHOD__
);
211 return $this->mContent
;
216 * This function returns the text of a section, specified by a number ($section).
217 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
218 * the first section before any such heading (section 0).
220 * If a section contains subsections, these are also returned.
222 * @param $text String: text to look in
223 * @param $section Integer: section number
224 * @return string text of the requested section
227 function getSection($text,$section) {
229 return $wgParser->getSection( $text, $section );
233 * @return int The oldid of the article that is to be shown, 0 for the
236 function getOldID() {
237 if ( is_null( $this->mOldId
) ) {
238 $this->mOldId
= $this->getOldIDFromRequest();
240 return $this->mOldId
;
244 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
246 * @return int The old id for the request
248 function getOldIDFromRequest() {
250 $this->mRedirectUrl
= false;
251 $oldid = $wgRequest->getVal( 'oldid' );
252 if ( isset( $oldid ) ) {
253 $oldid = intval( $oldid );
254 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
255 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
259 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
261 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
262 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
280 * Load the revision (including text) into this object
282 function loadContent() {
283 if ( $this->mContentLoaded
) return;
286 $oldid = $this->getOldID();
288 # Pre-fill content with error message so that if something
289 # fails we'll have something telling us what we intended.
290 $this->mOldId
= $oldid;
291 $this->fetchContent( $oldid );
296 * Fetch a page record with the given conditions
297 * @param Database $dbr
298 * @param array $conditions
301 function pageData( $dbr, $conditions ) {
315 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
316 $row = $dbr->selectRow(
322 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
327 * @param Database $dbr
328 * @param Title $title
330 function pageDataFromTitle( $dbr, $title ) {
331 return $this->pageData( $dbr, array(
332 'page_namespace' => $title->getNamespace(),
333 'page_title' => $title->getDBkey() ) );
337 * @param Database $dbr
340 function pageDataFromId( $dbr, $id ) {
341 return $this->pageData( $dbr, array( 'page_id' => $id ) );
345 * Set the general counter, title etc data loaded from
348 * @param object $data
351 function loadPageData( $data = 'fromdb' ) {
352 if ( $data === 'fromdb' ) {
353 $dbr = $this->getDB();
354 $data = $this->pageDataFromId( $dbr, $this->getId() );
357 $lc = LinkCache
::singleton();
359 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
361 $this->mTitle
->mArticleID
= $data->page_id
;
363 # Old-fashioned restrictions.
364 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
366 $this->mCounter
= $data->page_counter
;
367 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
368 $this->mIsRedirect
= $data->page_is_redirect
;
369 $this->mLatest
= $data->page_latest
;
371 if ( is_object( $this->mTitle
) ) {
372 $lc->addBadLinkObj( $this->mTitle
);
374 $this->mTitle
->mArticleID
= 0;
377 $this->mDataLoaded
= true;
381 * Get text of an article from database
382 * Does *NOT* follow redirects.
383 * @param int $oldid 0 for whatever the latest revision is
386 function fetchContent( $oldid = 0 ) {
387 if ( $this->mContentLoaded
) {
388 return $this->mContent
;
391 $dbr = $this->getDB();
393 # Pre-fill content with error message so that if something
394 # fails we'll have something telling us what we intended.
395 $t = $this->mTitle
->getPrefixedText();
397 $t .= ',oldid='.$oldid;
399 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
402 $revision = Revision
::newFromId( $oldid );
403 if( is_null( $revision ) ) {
404 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
407 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
409 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
412 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
413 $this->loadPageData( $data );
415 if( !$this->mDataLoaded
) {
416 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
418 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
421 $this->loadPageData( $data );
423 $revision = Revision
::newFromId( $this->mLatest
);
424 if( is_null( $revision ) ) {
425 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
430 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
431 // We should instead work with the Revision object when we need it...
432 $this->mContent
= $revision->revText(); // Loads if user is allowed
434 $this->mUser
= $revision->getUser();
435 $this->mUserText
= $revision->getUserText();
436 $this->mComment
= $revision->getComment();
437 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
439 $this->mRevIdFetched
= $revision->getID();
440 $this->mContentLoaded
= true;
441 $this->mRevision
=& $revision;
443 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
445 return $this->mContent
;
449 * Read/write accessor to select FOR UPDATE
451 * @param $x Mixed: FIXME
453 function forUpdate( $x = NULL ) {
454 return wfSetVar( $this->mForUpdate
, $x );
458 * Get the database which should be used for reads
463 return wfGetDB( DB_MASTER
);
467 * Get options for all SELECT statements
469 * @param $options Array: an optional options array which'll be appended to
471 * @return Array: options
473 function getSelectOptions( $options = '' ) {
474 if ( $this->mForUpdate
) {
475 if ( is_array( $options ) ) {
476 $options[] = 'FOR UPDATE';
478 $options = 'FOR UPDATE';
485 * @return int Page ID
488 if( $this->mTitle
) {
489 return $this->mTitle
->getArticleID();
496 * @return bool Whether or not the page exists in the database
499 return $this->getId() != 0;
503 * @return int The view count for the page
505 function getCount() {
506 if ( -1 == $this->mCounter
) {
507 $id = $this->getID();
511 $dbr = wfGetDB( DB_SLAVE
);
512 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
513 'Article::getCount', $this->getSelectOptions() );
516 return $this->mCounter
;
520 * Determine whether a page would be suitable for being counted as an
521 * article in the site_stats table based on the title & its content
523 * @param $text String: text to analyze
526 function isCountable( $text ) {
527 global $wgUseCommaCount;
529 $token = $wgUseCommaCount ?
',' : '[[';
531 $this->mTitle
->isContentPage()
532 && !$this->isRedirect( $text )
533 && in_string( $token, $text );
537 * Tests if the article text represents a redirect
539 * @param $text String: FIXME
542 function isRedirect( $text = false ) {
543 if ( $text === false ) {
544 $this->loadContent();
545 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
547 $titleObj = Title
::newFromRedirect( $text );
549 return $titleObj !== NULL;
553 * Returns true if the currently-referenced revision is the current edit
554 * to this page (and it exists).
557 function isCurrent() {
558 # If no oldid, this is the current version.
559 if ($this->getOldID() == 0)
562 return $this->exists() &&
563 isset( $this->mRevision
) &&
564 $this->mRevision
->isCurrent();
568 * Loads everything except the text
569 * This isn't necessary for all uses, so it's only done if needed.
572 function loadLastEdit() {
573 if ( -1 != $this->mUser
)
576 # New or non-existent articles have no user information
577 $id = $this->getID();
578 if ( 0 == $id ) return;
580 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
581 if( !is_null( $this->mLastRevision
) ) {
582 $this->mUser
= $this->mLastRevision
->getUser();
583 $this->mUserText
= $this->mLastRevision
->getUserText();
584 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
585 $this->mComment
= $this->mLastRevision
->getComment();
586 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
587 $this->mRevIdFetched
= $this->mLastRevision
->getID();
591 function getTimestamp() {
592 // Check if the field has been filled by ParserCache::get()
593 if ( !$this->mTimestamp
) {
594 $this->loadLastEdit();
596 return wfTimestamp(TS_MW
, $this->mTimestamp
);
600 $this->loadLastEdit();
604 function getUserText() {
605 $this->loadLastEdit();
606 return $this->mUserText
;
609 function getComment() {
610 $this->loadLastEdit();
611 return $this->mComment
;
614 function getMinorEdit() {
615 $this->loadLastEdit();
616 return $this->mMinorEdit
;
619 function getRevIdFetched() {
620 $this->loadLastEdit();
621 return $this->mRevIdFetched
;
625 * @todo Document, fixme $offset never used.
626 * @param $limit Integer: default 0.
627 * @param $offset Integer: default 0.
629 function getContributors($limit = 0, $offset = 0) {
630 # XXX: this is expensive; cache this info somewhere.
633 $dbr = wfGetDB( DB_SLAVE
);
634 $revTable = $dbr->tableName( 'revision' );
635 $userTable = $dbr->tableName( 'user' );
636 $user = $this->getUser();
637 $pageId = $this->getId();
639 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
640 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
641 WHERE rev_page = $pageId
642 AND rev_user != $user
643 GROUP BY rev_user, rev_user_text, user_real_name
644 ORDER BY timestamp DESC";
646 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
647 $sql .= ' '. $this->getSelectOptions();
649 $res = $dbr->query($sql, __METHOD__
);
651 while ( $line = $dbr->fetchObject( $res ) ) {
652 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
655 $dbr->freeResult($res);
660 * This is the default action of the script: just view the page of
664 global $wgUser, $wgOut, $wgRequest, $wgContLang;
665 global $wgEnableParserCache, $wgStylePath, $wgParser;
666 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
667 global $wgDefaultRobotPolicy;
668 $sk = $wgUser->getSkin();
670 wfProfileIn( __METHOD__
);
672 $parserCache = ParserCache
::singleton();
673 $ns = $this->mTitle
->getNamespace(); # shortcut
675 # Get variables from query string
676 $oldid = $this->getOldID();
678 # getOldID may want us to redirect somewhere else
679 if ( $this->mRedirectUrl
) {
680 $wgOut->redirect( $this->mRedirectUrl
);
681 wfProfileOut( __METHOD__
);
685 $diff = $wgRequest->getVal( 'diff' );
686 $rcid = $wgRequest->getVal( 'rcid' );
687 $rdfrom = $wgRequest->getVal( 'rdfrom' );
688 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
689 $purge = $wgRequest->getVal( 'action' ) == 'purge';
691 $wgOut->setArticleFlag( true );
693 # Discourage indexing of printable versions, but encourage following
694 if( $wgOut->isPrintable() ) {
695 $policy = 'noindex,follow';
696 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
697 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
698 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
699 # Honour customised robot policies for this namespace
700 $policy = $wgNamespaceRobotPolicies[$ns];
702 $policy = $wgDefaultRobotPolicy;
704 $wgOut->setRobotPolicy( $policy );
706 # If we got diff and oldid in the query, we want to see a
707 # diff page instead of the article.
709 if ( !is_null( $diff ) ) {
710 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
712 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
713 // DifferenceEngine directly fetched the revision:
714 $this->mRevIdFetched
= $de->mNewid
;
715 $de->showDiffPage( $diffOnly );
717 // Needed to get the page's current revision
718 $this->loadPageData();
719 if( $diff == 0 ||
$diff == $this->mLatest
) {
720 # Run view updates for current revision only
721 $this->viewUpdates();
723 wfProfileOut( __METHOD__
);
727 if ( empty( $oldid ) && $this->checkTouched() ) {
728 $wgOut->setETag($parserCache->getETag($this, $wgUser));
730 if( $wgOut->checkLastModified( $this->mTouched
) ){
731 wfProfileOut( __METHOD__
);
733 } else if ( $this->tryFileCache() ) {
734 # tell wgOut that output is taken care of
736 $this->viewUpdates();
737 wfProfileOut( __METHOD__
);
742 # Should the parser cache be used?
743 $pcache = $wgEnableParserCache
744 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
747 && !$this->mTitle
->isCssOrJsPage()
748 && !$this->mTitle
->isCssJsSubpage();
749 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
750 if ( $wgUser->getOption( 'stubthreshold' ) ) {
751 wfIncrStats( 'pcache_miss_stub' );
754 $wasRedirected = false;
755 if ( isset( $this->mRedirectedFrom
) ) {
756 // This is an internally redirected page view.
757 // We'll need a backlink to the source page for navigation.
758 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
759 $sk = $wgUser->getSkin();
760 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
761 $s = wfMsg( 'redirectedfrom', $redir );
762 $wgOut->setSubtitle( $s );
764 // Set the fragment if one was specified in the redirect
765 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
766 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
767 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
769 $wasRedirected = true;
771 } elseif ( !empty( $rdfrom ) ) {
772 // This is an externally redirected view, from some other wiki.
773 // If it was reported from a trusted site, supply a backlink.
774 global $wgRedirectSources;
775 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
776 $sk = $wgUser->getSkin();
777 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
778 $s = wfMsg( 'redirectedfrom', $redir );
779 $wgOut->setSubtitle( $s );
780 $wasRedirected = true;
785 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
787 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
788 // Ensure that UI elements requiring revision ID have
789 // the correct version information.
790 $wgOut->setRevisionId( $this->mLatest
);
794 if ( !$outputDone ) {
795 $text = $this->getContent();
796 if ( $text === false ) {
797 # Failed to load, replace text with error message
798 $t = $this->mTitle
->getPrefixedText();
800 $t .= ',oldid='.$oldid;
801 $text = wfMsg( 'missingarticle', $t );
803 $text = wfMsg( 'noarticletext', $t );
807 # Another whitelist check in case oldid is altering the title
808 if ( !$this->mTitle
->userCanRead() ) {
809 $wgOut->loginToUse();
814 # We're looking at an old revision
816 if ( !empty( $oldid ) ) {
817 $wgOut->setRobotpolicy( 'noindex,nofollow' );
818 if( is_null( $this->mRevision
) ) {
819 // FIXME: This would be a nice place to load the 'no such page' text.
821 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
822 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
823 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
824 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
825 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
828 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
829 // and we are allowed to see...
837 $wgOut->setRevisionId( $this->getRevIdFetched() );
839 // Pages containing custom CSS or JavaScript get special treatment
840 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
841 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
843 // Give hooks a chance to customise the output
844 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
845 // Wrap the whole lot in a <pre> and don't parse
847 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
848 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
849 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
850 $wgOut->addHtml( "\n</pre>\n" );
855 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
857 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
858 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
859 # Don't overwrite the subtitle if this was an old revision
860 if( !$wasRedirected && $this->isCurrent() ) {
861 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
863 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
865 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
866 '<span class="redirectText">'.$link.'</span>' );
868 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
869 $wgOut->addParserOutputNoText( $parseout );
870 } else if ( $pcache ) {
871 # Display content and save to parser cache
872 $this->outputWikiText( $text );
874 # Display content, don't attempt to save to parser cache
875 # Don't show section-edit links on old revisions... this way lies madness.
876 if( !$this->isCurrent() ) {
877 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
879 # Display content and don't save to parser cache
880 # With timing hack -- TS 2006-07-26
882 $this->outputWikiText( $text, false );
887 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
888 $this->mTitle
->getPrefixedDBkey()));
891 if( !$this->isCurrent() ) {
892 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
897 /* title may have been set from the cache */
898 $t = $wgOut->getPageTitle();
900 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
903 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
904 if( $ns == NS_USER_TALK
&&
905 IP
::isValid( $this->mTitle
->getText() ) ) {
906 $wgOut->addWikiMsg('anontalkpagetext');
909 # If we have been passed an &rcid= parameter, we want to give the user a
910 # chance to mark this new article as patrolled.
911 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
913 "<div class='patrollink'>" .
914 wfMsgHtml( 'markaspatrolledlink',
915 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
916 "action=markpatrolled&rcid=$rcid" )
923 if ($wgUseTrackbacks)
924 $this->addTrackbacks();
926 $this->viewUpdates();
927 wfProfileOut( __METHOD__
);
930 function addTrackbacks() {
931 global $wgOut, $wgUser;
933 $dbr = wfGetDB(DB_SLAVE
);
935 /* FROM */ 'trackbacks',
936 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
937 /* WHERE */ array('tb_page' => $this->getID())
940 if (!$dbr->numrows($tbs))
944 while ($o = $dbr->fetchObject($tbs)) {
946 if ($wgUser->isAllowed( 'trackback' )) {
947 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
948 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
949 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
952 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
959 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
962 function deletetrackback() {
963 global $wgUser, $wgRequest, $wgOut, $wgTitle;
965 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
966 $wgOut->addWikiMsg( 'sessionfailure' );
970 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
972 if (count($permission_errors)>0)
974 $wgOut->showPermissionsErrorPage( $permission_errors );
978 $db = wfGetDB(DB_MASTER
);
979 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
980 $wgTitle->invalidateCache();
981 $wgOut->addWikiMsg('trackbackdeleteok');
987 $wgOut->setArticleBodyOnly(true);
992 * Handle action=purge
995 global $wgUser, $wgRequest, $wgOut;
997 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
998 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1002 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1003 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1004 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1005 $msg = str_replace( '$1',
1006 "<form method=\"post\" action=\"$action\">\n" .
1007 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1008 "</form>\n", $msg );
1010 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1011 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1012 $wgOut->addHTML( $msg );
1017 * Perform the actions of a page purging
1019 function doPurge() {
1021 // Invalidate the cache
1022 $this->mTitle
->invalidateCache();
1024 if ( $wgUseSquid ) {
1025 // Commit the transaction before the purge is sent
1026 $dbw = wfGetDB( DB_MASTER
);
1027 $dbw->immediateCommit();
1030 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1031 $update->doUpdate();
1033 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1034 global $wgMessageCache;
1035 if ( $this->getID() == 0 ) {
1038 $text = $this->getContent();
1040 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1046 * Insert a new empty page record for this article.
1047 * This *must* be followed up by creating a revision
1048 * and running $this->updateToLatest( $rev_id );
1049 * or else the record will be left in a funky state.
1050 * Best if all done inside a transaction.
1052 * @param Database $dbw
1053 * @return int The newly created page_id key
1056 function insertOn( $dbw ) {
1057 wfProfileIn( __METHOD__
);
1059 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1060 $dbw->insert( 'page', array(
1061 'page_id' => $page_id,
1062 'page_namespace' => $this->mTitle
->getNamespace(),
1063 'page_title' => $this->mTitle
->getDBkey(),
1064 'page_counter' => 0,
1065 'page_restrictions' => '',
1066 'page_is_redirect' => 0, # Will set this shortly...
1068 'page_random' => wfRandom(),
1069 'page_touched' => $dbw->timestamp(),
1070 'page_latest' => 0, # Fill this in shortly...
1071 'page_len' => 0, # Fill this in shortly...
1073 $newid = $dbw->insertId();
1075 $this->mTitle
->resetArticleId( $newid );
1077 wfProfileOut( __METHOD__
);
1082 * Update the page record to point to a newly saved revision.
1084 * @param Database $dbw
1085 * @param Revision $revision For ID number, and text used to set
1086 length and redirect status fields
1087 * @param int $lastRevision If given, will not overwrite the page field
1088 * when different from the currently set value.
1089 * Giving 0 indicates the new page flag should
1091 * @param bool $lastRevIsRedirect If given, will optimize adding and
1092 * removing rows in redirect table.
1093 * @return bool true on success, false on failure
1096 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1097 wfProfileIn( __METHOD__
);
1099 $text = $revision->getText();
1100 $rt = Title
::newFromRedirect( $text );
1102 $conditions = array( 'page_id' => $this->getId() );
1103 if( !is_null( $lastRevision ) ) {
1104 # An extra check against threads stepping on each other
1105 $conditions['page_latest'] = $lastRevision;
1108 $dbw->update( 'page',
1110 'page_latest' => $revision->getId(),
1111 'page_touched' => $dbw->timestamp(),
1112 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1113 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1114 'page_len' => strlen( $text ),
1119 $result = $dbw->affectedRows() != 0;
1122 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1125 wfProfileOut( __METHOD__
);
1130 * Add row to the redirect table if this is a redirect, remove otherwise.
1132 * @param Database $dbw
1133 * @param $redirectTitle a title object pointing to the redirect target,
1134 * or NULL if this is not a redirect
1135 * @param bool $lastRevIsRedirect If given, will optimize adding and
1136 * removing rows in redirect table.
1137 * @return bool true on success, false on failure
1140 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1142 // Always update redirects (target link might have changed)
1143 // Update/Insert if we don't know if the last revision was a redirect or not
1144 // Delete if changing from redirect to non-redirect
1145 $isRedirect = !is_null($redirectTitle);
1146 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1148 wfProfileIn( __METHOD__
);
1152 // This title is a redirect, Add/Update row in the redirect table
1153 $set = array( /* SET */
1154 'rd_namespace' => $redirectTitle->getNamespace(),
1155 'rd_title' => $redirectTitle->getDBkey(),
1156 'rd_from' => $this->getId(),
1159 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1161 // This is not a redirect, remove row from redirect table
1162 $where = array( 'rd_from' => $this->getId() );
1163 $dbw->delete( 'redirect', $where, __METHOD__
);
1166 if( $this->getTitle()->getNamespace() == NS_IMAGE
)
1167 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1168 wfProfileOut( __METHOD__
);
1169 return ( $dbw->affectedRows() != 0 );
1176 * If the given revision is newer than the currently set page_latest,
1177 * update the page record. Otherwise, do nothing.
1179 * @param Database $dbw
1180 * @param Revision $revision
1182 function updateIfNewerOn( &$dbw, $revision ) {
1183 wfProfileIn( __METHOD__
);
1185 $row = $dbw->selectRow(
1186 array( 'revision', 'page' ),
1187 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1189 'page_id' => $this->getId(),
1190 'page_latest=rev_id' ),
1193 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1194 wfProfileOut( __METHOD__
);
1197 $prev = $row->rev_id
;
1198 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1200 # No or missing previous revision; mark the page as new
1202 $lastRevIsRedirect = null;
1205 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1206 wfProfileOut( __METHOD__
);
1211 * @return string Complete article text, or null if error
1213 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1214 wfProfileIn( __METHOD__
);
1216 if( $section == '' ) {
1217 // Whole-page edit; let the text through unmolested.
1219 if( is_null( $edittime ) ) {
1220 $rev = Revision
::newFromTitle( $this->mTitle
);
1222 $dbw = wfGetDB( DB_MASTER
);
1223 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1225 if( is_null( $rev ) ) {
1226 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1227 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1230 $oldtext = $rev->getText();
1232 if( $section == 'new' ) {
1233 # Inserting a new section
1234 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1235 $text = strlen( trim( $oldtext ) ) > 0
1236 ?
"{$oldtext}\n\n{$subject}{$text}"
1237 : "{$subject}{$text}";
1239 # Replacing an existing section; roll out the big guns
1241 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1246 wfProfileOut( __METHOD__
);
1251 * @deprecated use Article::doEdit()
1253 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1254 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1255 ( $isminor ? EDIT_MINOR
: 0 ) |
1256 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1257 ( $bot ? EDIT_FORCE_BOT
: 0 );
1259 # If this is a comment, add the summary as headline
1260 if ( $comment && $summary != "" ) {
1261 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1264 $this->doEdit( $text, $summary, $flags );
1266 $dbw = wfGetDB( DB_MASTER
);
1268 if (!$this->mTitle
->userIsWatching()) {
1274 if ( $this->mTitle
->userIsWatching() ) {
1280 $this->doRedirect( $this->isRedirect( $text ) );
1284 * @deprecated use Article::doEdit()
1286 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1287 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1288 ( $minor ? EDIT_MINOR
: 0 ) |
1289 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1291 $good = $this->doEdit( $text, $summary, $flags );
1293 $dbw = wfGetDB( DB_MASTER
);
1295 if (!$this->mTitle
->userIsWatching()) {
1301 if ( $this->mTitle
->userIsWatching() ) {
1308 $extraq = ''; // Give extensions a chance to modify URL query on update
1309 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1311 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1319 * Change an existing article or create a new article. Updates RC and all necessary caches,
1320 * optionally via the deferred update array.
1322 * $wgUser must be set before calling this function.
1324 * @param string $text New text
1325 * @param string $summary Edit summary
1326 * @param integer $flags bitfield:
1328 * Article is known or assumed to be non-existent, create a new one
1330 * Article is known or assumed to be pre-existing, update it
1332 * Mark this edit minor, if the user is allowed to do so
1334 * Do not log the change in recentchanges
1336 * Mark the edit a "bot" edit regardless of user rights
1337 * EDIT_DEFER_UPDATES
1338 * Defer some of the updates until the end of index.php
1340 * Fill in blank summaries with generated text where possible
1342 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1343 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1344 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1345 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1346 * to MediaWiki's performance-optimised locking strategy.
1348 * @return bool success
1350 function doEdit( $text, $summary, $flags = 0 ) {
1351 global $wgUser, $wgDBtransactions;
1353 wfProfileIn( __METHOD__
);
1356 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1357 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1359 $flags |
= EDIT_UPDATE
;
1365 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1366 &$summary, $flags & EDIT_MINOR
,
1367 null, null, &$flags ) ) )
1369 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1370 wfProfileOut( __METHOD__
);
1374 # Silently ignore EDIT_MINOR if not allowed
1375 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1376 $bot = $flags & EDIT_FORCE_BOT
;
1378 $oldtext = $this->getContent();
1379 $oldsize = strlen( $oldtext );
1381 # Provide autosummaries if one is not provided.
1382 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1383 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1385 $editInfo = $this->prepareTextForEdit( $text );
1386 $text = $editInfo->pst
;
1387 $newsize = strlen( $text );
1389 $dbw = wfGetDB( DB_MASTER
);
1390 $now = wfTimestampNow();
1392 if ( $flags & EDIT_UPDATE
) {
1393 # Update article, but only if changed.
1395 # Make sure the revision is either completely inserted or not inserted at all
1396 if( !$wgDBtransactions ) {
1397 $userAbort = ignore_user_abort( true );
1403 $changed = ( strcmp( $text, $oldtext ) != 0 );
1406 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1407 - (int)$this->isCountable( $oldtext );
1408 $this->mTotalAdjustment
= 0;
1410 $lastRevision = $dbw->selectField(
1411 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1413 if ( !$lastRevision ) {
1414 # Article gone missing
1415 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1416 wfProfileOut( __METHOD__
);
1420 $revision = new Revision( array(
1421 'page' => $this->getId(),
1422 'comment' => $summary,
1423 'minor_edit' => $isminor,
1425 'parent_id' => $lastRevision
1429 $revisionId = $revision->insertOn( $dbw );
1432 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1435 /* Belated edit conflict! Run away!! */
1439 # Update recentchanges
1440 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1441 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1442 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1445 # Mark as patrolled if the user can do so
1446 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1447 RecentChange
::markPatrolled( $rcid );
1448 PatrolLog
::record( $rcid, true );
1451 $wgUser->incEditCount();
1456 // Keep the same revision ID, but do some updates on it
1457 $revisionId = $this->getRevIdFetched();
1458 // Update page_touched, this is usually implicit in the page update
1459 // Other cache updates are done in onArticleEdit()
1460 $this->mTitle
->invalidateCache();
1463 if( !$wgDBtransactions ) {
1464 ignore_user_abort( $userAbort );
1468 # Invalidate cache of this article and all pages using this article
1469 # as a template. Partly deferred.
1470 Article
::onArticleEdit( $this->mTitle
);
1472 # Update links tables, site stats, etc.
1473 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1476 # Create new article
1478 # Set statistics members
1479 # We work out if it's countable after PST to avoid counter drift
1480 # when articles are created with {{subst:}}
1481 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1482 $this->mTotalAdjustment
= 1;
1486 # Add the page record; stake our claim on this title!
1487 # This will fail with a database query exception if the article already exists
1488 $newid = $this->insertOn( $dbw );
1490 # Save the revision text...
1491 $revision = new Revision( array(
1493 'comment' => $summary,
1494 'minor_edit' => $isminor,
1497 $revisionId = $revision->insertOn( $dbw );
1499 $this->mTitle
->resetArticleID( $newid );
1501 # Update the page record with revision data
1502 $this->updateRevisionOn( $dbw, $revision, 0 );
1504 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1505 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1506 '', strlen( $text ), $revisionId );
1507 # Mark as patrolled if the user can
1508 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1509 RecentChange
::markPatrolled( $rcid );
1510 PatrolLog
::record( $rcid, true );
1513 $wgUser->incEditCount();
1516 # Update links, etc.
1517 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1520 Article
::onArticleCreate( $this->mTitle
);
1522 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1523 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1526 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1531 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1532 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1535 wfProfileOut( __METHOD__
);
1540 * @deprecated wrapper for doRedirect
1542 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1543 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1547 * Output a redirect back to the article.
1548 * This is typically used after an edit.
1550 * @param boolean $noRedir Add redirect=no
1551 * @param string $sectionAnchor section to redirect to, including "#"
1552 * @param string $extraq, extra query params
1554 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1557 $query = 'redirect=no';
1559 $query .= "&$query";
1563 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1567 * Mark this particular edit/page as patrolled
1569 function markpatrolled() {
1570 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1571 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1573 # Check patrol config options
1575 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1576 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1580 # If we haven't been given an rc_id value, we can't do anything
1581 $rcid = (int) $wgRequest->getVal('rcid');
1582 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1583 if ( is_null ( $rc ) )
1585 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1589 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW
) {
1590 // Only new pages can be patrolled if the general patrolling is off....???
1591 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1593 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1598 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1600 if (count($permission_errors)>0)
1602 $wgOut->showPermissionsErrorPage( $permission_errors );
1606 # Handle the 'MarkPatrolled' hook
1607 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1611 #It would be nice to see where the user had actually come from, but for now just guess
1612 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
1613 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1615 # If it's left up to us, check that the user is allowed to patrol this edit
1616 # If the user has the "autopatrol" right, then we'll assume there are no
1617 # other conditions stopping them doing so
1618 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1619 $rc = RecentChange
::newFromId( $rcid );
1620 # Graceful error handling, as we've done before here...
1621 # (If the recent change doesn't exist, then it doesn't matter whether
1622 # the user is allowed to patrol it or not; nothing is going to happen
1623 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1624 # The user made this edit, and can't patrol it
1625 # Tell them so, and then back off
1626 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1627 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1628 $wgOut->returnToMain( false, $return );
1633 # Check that the revision isn't patrolled already
1634 # Prevents duplicate log entries
1635 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1636 # Mark the edit as patrolled
1637 RecentChange
::markPatrolled( $rcid );
1638 PatrolLog
::record( $rcid );
1639 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1643 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1644 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1645 $wgOut->returnToMain( false, $return );
1649 * User-interface handler for the "watch" action
1654 global $wgUser, $wgOut;
1656 if ( $wgUser->isAnon() ) {
1657 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1660 if ( wfReadOnly() ) {
1661 $wgOut->readOnlyPage();
1665 if( $this->doWatch() ) {
1666 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1667 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1669 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
1672 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1676 * Add this page to $wgUser's watchlist
1677 * @return bool true on successful watch operation
1679 function doWatch() {
1681 if( $wgUser->isAnon() ) {
1685 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1686 $wgUser->addWatch( $this->mTitle
);
1688 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1695 * User interface handler for the "unwatch" action.
1697 function unwatch() {
1699 global $wgUser, $wgOut;
1701 if ( $wgUser->isAnon() ) {
1702 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1705 if ( wfReadOnly() ) {
1706 $wgOut->readOnlyPage();
1710 if( $this->doUnwatch() ) {
1711 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1712 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1714 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
1717 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1721 * Stop watching a page
1722 * @return bool true on successful unwatch
1724 function doUnwatch() {
1726 if( $wgUser->isAnon() ) {
1730 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1731 $wgUser->removeWatch( $this->mTitle
);
1733 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1740 * action=protect handler
1742 function protect() {
1743 $form = new ProtectionForm( $this );
1748 * action=unprotect handler (alias)
1750 function unprotect() {
1755 * Update the article's restriction field, and leave a log entry.
1757 * @param array $limit set of restriction keys
1758 * @param string $reason
1759 * @return bool true on success
1761 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1762 global $wgUser, $wgRestrictionTypes, $wgContLang;
1764 $id = $this->mTitle
->getArticleID();
1765 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1773 // Take this opportunity to purge out expired restrictions
1774 Title
::purgeExpiredRestrictions();
1776 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1777 # we expect a single selection, but the schema allows otherwise.
1779 foreach( $wgRestrictionTypes as $action )
1780 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1782 $current = Article
::flattenRestrictions( $current );
1783 $updated = Article
::flattenRestrictions( $limit );
1785 $changed = ( $current != $updated );
1786 $changed = $changed ||
($updated && $this->mTitle
->areRestrictionsCascading() != $cascade);
1787 $changed = $changed ||
($updated && $this->mTitle
->mRestrictionsExpiry
!= $expiry);
1788 $protect = ( $updated != '' );
1790 # If nothing's changed, do nothing
1792 global $wgGroupPermissions;
1793 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1795 $dbw = wfGetDB( DB_MASTER
);
1797 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1799 $expiry_description = '';
1800 if ( $encodedExpiry != 'infinity' ) {
1801 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1804 # Prepare a null revision to be added to the history
1805 $modified = $current != '' && $protect;
1807 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1809 $comment_type = 'unprotectedarticle';
1811 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1813 foreach( $limit as $action => $restrictions ) {
1814 # Check if the group level required to edit also can protect pages
1815 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1816 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1817 $wgGroupPermissions[$restrictions]['protect'] );
1820 $cascade_description = '';
1822 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1826 $comment .= ": $reason";
1828 $comment .= " [$updated]";
1829 if ( $expiry_description && $protect )
1830 $comment .= "$expiry_description";
1832 $comment .= "$cascade_description";
1834 # Update restrictions table
1835 foreach( $limit as $action => $restrictions ) {
1836 if ($restrictions != '' ) {
1837 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1838 array( 'pr_page' => $id, 'pr_type' => $action
1839 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1840 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1842 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1843 'pr_type' => $action ), __METHOD__
);
1847 # Insert a null revision
1848 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1849 $nullRevId = $nullRevision->insertOn( $dbw );
1851 # Update page record
1852 $dbw->update( 'page',
1854 'page_touched' => $dbw->timestamp(),
1855 'page_restrictions' => '',
1856 'page_latest' => $nullRevId
1857 ), array( /* WHERE */
1859 ), 'Article::protect'
1861 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1863 # Update the protection log
1864 $log = new LogPage( 'protect' );
1869 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1871 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1875 } # End "changed" check
1881 * Take an array of page restrictions and flatten it to a string
1882 * suitable for insertion into the page_restrictions field.
1883 * @param array $limit
1887 function flattenRestrictions( $limit ) {
1888 if( !is_array( $limit ) ) {
1889 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1893 foreach( $limit as $action => $restrictions ) {
1894 if( $restrictions != '' ) {
1895 $bits[] = "$action=$restrictions";
1898 return implode( ':', $bits );
1902 * Auto-generates a deletion reason
1903 * @param bool &$hasHistory Whether the page has a history
1905 public function generateReason(&$hasHistory)
1908 $dbw = wfGetDB(DB_MASTER
);
1909 // Get the last revision
1910 $rev = Revision
::newFromTitle($this->mTitle
);
1913 // Get the article's contents
1914 $contents = $rev->getText();
1916 // If the page is blank, use the text from the previous revision,
1917 // which can only be blank if there's a move/import/protect dummy revision involved
1920 $prev = $rev->getPrevious();
1923 $contents = $prev->getText();
1928 // Find out if there was only one contributor
1929 // Only scan the last 20 revisions
1931 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1932 array('LIMIT' => $limit));
1934 // This page has no revisions, which is very weird
1936 if($res->numRows() > 1)
1939 $hasHistory = false;
1940 $row = $dbw->fetchObject($res);
1941 $onlyAuthor = $row->rev_user_text
;
1942 // Try to find a second contributor
1943 while( $row = $dbw->fetchObject($res) ) {
1944 if($row->rev_user_text
!= $onlyAuthor) {
1945 $onlyAuthor = false;
1949 $dbw->freeResult($res);
1951 // Generate the summary with a '$1' placeholder
1953 // The current revision is blank and the one before is also
1954 // blank. It's just not our lucky day
1955 $reason = wfMsgForContent('exbeforeblank', '$1');
1958 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1960 $reason = wfMsgForContent('excontent', '$1');
1963 // Replace newlines with spaces to prevent uglyness
1964 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1965 // Calculate the maximum amount of chars to get
1966 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1967 $maxLength = 255 - (strlen($reason) - 2) - 3;
1968 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1969 // Remove possible unfinished links
1970 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1971 // Now replace the '$1' placeholder
1972 $reason = str_replace( '$1', $contents, $reason );
1978 * UI entry point for page deletion
1981 global $wgUser, $wgOut, $wgRequest;
1983 $confirm = $wgRequest->wasPosted() &&
1984 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1986 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1987 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1989 $reason = $this->DeleteReasonList
;
1991 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1992 // Entry from drop down menu + additional comment
1993 $reason .= ': ' . $this->DeleteReason
;
1994 } elseif ( $reason == 'other' ) {
1995 $reason = $this->DeleteReason
;
1997 # Flag to hide all contents of the archived revisions
1998 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
2000 # This code desperately needs to be totally rewritten
2002 # Read-only check...
2003 if ( wfReadOnly() ) {
2004 $wgOut->readOnlyPage();
2009 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2011 if (count($permission_errors)>0) {
2012 $wgOut->showPermissionsErrorPage( $permission_errors );
2016 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2018 # Better double-check that it hasn't been deleted yet!
2019 $dbw = wfGetDB( DB_MASTER
);
2020 $conds = $this->mTitle
->pageCond();
2021 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2022 if ( $latest === false ) {
2023 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2027 # Hack for big sites
2028 $bigHistory = $this->isBigDeletion();
2029 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2030 global $wgLang, $wgDeleteRevisionsLimit;
2031 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2032 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2037 $this->doDelete( $reason, $suppress );
2038 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2040 } elseif( $this->mTitle
->userIsWatching() ) {
2046 // Generate deletion reason
2047 $hasHistory = false;
2048 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2050 // If the page has a history, insert a warning
2051 if( $hasHistory && !$confirm ) {
2052 $skin=$wgUser->getSkin();
2053 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2055 global $wgLang, $wgDeleteRevisionsLimit;
2056 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2057 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2061 return $this->confirmDelete( '', $reason );
2065 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2067 function isBigDeletion() {
2068 global $wgDeleteRevisionsLimit;
2069 if( $wgDeleteRevisionsLimit ) {
2070 $revCount = $this->estimateRevisionCount();
2071 return $revCount > $wgDeleteRevisionsLimit;
2077 * @return int approximate revision count
2079 function estimateRevisionCount() {
2081 // For an exact count...
2082 //return $dbr->selectField( 'revision', 'COUNT(*)',
2083 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2084 return $dbr->estimateRowCount( 'revision', '*',
2085 array( 'rev_page' => $this->getId() ), __METHOD__
);
2089 * Get the last N authors
2090 * @param int $num Number of revisions to get
2091 * @param string $revLatest The latest rev_id, selected from the master (optional)
2092 * @return array Array of authors, duplicates not removed
2094 function getLastNAuthors( $num, $revLatest = 0 ) {
2095 wfProfileIn( __METHOD__
);
2097 // First try the slave
2098 // If that doesn't have the latest revision, try the master
2100 $db = wfGetDB( DB_SLAVE
);
2102 $res = $db->select( array( 'page', 'revision' ),
2103 array( 'rev_id', 'rev_user_text' ),
2105 'page_namespace' => $this->mTitle
->getNamespace(),
2106 'page_title' => $this->mTitle
->getDBkey(),
2107 'rev_page = page_id'
2108 ), __METHOD__
, $this->getSelectOptions( array(
2109 'ORDER BY' => 'rev_timestamp DESC',
2114 wfProfileOut( __METHOD__
);
2117 $row = $db->fetchObject( $res );
2118 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2119 $db = wfGetDB( DB_MASTER
);
2124 } while ( $continue );
2126 $authors = array( $row->rev_user_text
);
2127 while ( $row = $db->fetchObject( $res ) ) {
2128 $authors[] = $row->rev_user_text
;
2130 wfProfileOut( __METHOD__
);
2135 * Output deletion confirmation dialog
2136 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2137 * @param $reason string Prefilled reason
2139 function confirmDelete( $par, $reason ) {
2140 global $wgOut, $wgUser, $wgContLang;
2141 $align = $wgContLang->isRtl() ?
'left' : 'right';
2143 wfDebug( "Article::confirmDelete\n" );
2145 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2146 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2147 $wgOut->addWikiMsg( 'confirmdeletetext' );
2149 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2150 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2151 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2152 $suppress .= "</td></tr>";
2157 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2158 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2159 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2160 Xml
::openElement( 'table' ) .
2161 "<tr id=\"wpDeleteReasonListRow\">
2162 <td align='$align'>" .
2163 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2166 Xml
::listDropDown( 'wpDeleteReasonList',
2167 wfMsgForContent( 'deletereason-dropdown' ),
2168 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2171 <tr id=\"wpDeleteReasonRow\">
2172 <td align='$align'>" .
2173 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2176 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2182 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2189 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2192 Xml
::closeElement( 'table' ) .
2193 Xml
::closeElement( 'fieldset' ) .
2194 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2195 Xml
::closeElement( 'form' );
2197 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2198 $skin = $wgUser->getSkin();
2199 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2200 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2203 $wgOut->addHTML( $form );
2204 $this->showLogExtract( $wgOut );
2209 * Show relevant lines from the deletion log
2211 function showLogExtract( $out ) {
2212 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2213 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2218 * Perform a deletion and output success or failure messages
2220 function doDelete( $reason, $suppress = false ) {
2221 global $wgOut, $wgUser;
2222 wfDebug( __METHOD__
."\n" );
2224 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2225 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2226 $deleted = $this->mTitle
->getPrefixedText();
2228 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2229 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2231 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2233 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2234 $wgOut->returnToMain( false );
2235 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2237 $wgOut->showFatalError( wfMsg( 'cannotdelete' ).'<br/>'.wfMsg('cannotdelete-merge') );
2243 * Back-end article deletion
2244 * Deletes the article with database consistency, writes logs, purges caches
2247 function doDeleteArticle( $reason, $suppress = false ) {
2248 global $wgUseSquid, $wgDeferredUpdateList;
2249 global $wgUseTrackbacks;
2251 wfDebug( __METHOD__
."\n" );
2253 $dbw = wfGetDB( DB_MASTER
);
2254 $ns = $this->mTitle
->getNamespace();
2255 $t = $this->mTitle
->getDBkey();
2256 $id = $this->mTitle
->getArticleID();
2258 if ( $t == '' ||
$id == 0 ) {
2262 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2263 array_push( $wgDeferredUpdateList, $u );
2265 // Bitfields to further suppress the content
2268 // This should be 15...
2269 $bitfield |
= Revision
::DELETED_TEXT
;
2270 $bitfield |
= Revision
::DELETED_COMMENT
;
2271 $bitfield |
= Revision
::DELETED_USER
;
2272 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2274 $bitfield = 'rev_deleted';
2277 // For now, shunt the revision data into the archive table.
2278 // Text is *not* removed from the text table; bulk storage
2279 // is left intact to avoid breaking block-compression or
2280 // immutable storage schemes.
2282 // For backwards compatibility, note that some older archive
2283 // table entries will have ar_text and ar_flags fields still.
2285 // In the future, we may keep revisions and mark them with
2286 // the rev_deleted field, which is reserved for this purpose.
2287 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2289 'ar_namespace' => 'page_namespace',
2290 'ar_title' => 'page_title',
2291 'ar_comment' => 'rev_comment',
2292 'ar_user' => 'rev_user',
2293 'ar_user_text' => 'rev_user_text',
2294 'ar_timestamp' => 'rev_timestamp',
2295 'ar_minor_edit' => 'rev_minor_edit',
2296 'ar_rev_id' => 'rev_id',
2297 'ar_text_id' => 'rev_text_id',
2298 'ar_text' => '\'\'', // Be explicit to appease
2299 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2300 'ar_len' => 'rev_len',
2301 'ar_page_id' => 'page_id',
2302 'ar_deleted' => $bitfield
2305 'page_id = rev_page'
2309 # Delete restrictions for it
2310 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2312 # Fix category table counts
2314 $res = $dbw->select( 'categorylinks', 'cl_to',
2315 array( 'cl_from' => $id ), __METHOD__
);
2316 foreach( $res as $row ) {
2317 $cats []= $row->cl_to
;
2319 $this->updateCategoryCounts( array(), $cats );
2321 # Now that it's safely backed up, delete it
2322 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2324 # If using cascading deletes, we can skip some explicit deletes
2325 if ( !$dbw->cascadingDeletes() ) {
2326 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2328 if ($wgUseTrackbacks)
2329 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2331 # Delete outgoing links
2332 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2333 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2334 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2335 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2336 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2337 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2338 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2341 # If using cleanup triggers, we can skip some manual deletes
2342 if ( !$dbw->cleanupTriggers() ) {
2344 # Clean up recentchanges entries...
2345 $dbw->delete( 'recentchanges',
2346 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2351 Article
::onArticleDelete( $this->mTitle
);
2353 # Clear the cached article id so the interface doesn't act like we exist
2354 $this->mTitle
->resetArticleID( 0 );
2355 $this->mTitle
->mArticleID
= 0;
2357 # Log the deletion, if the page was suppressed, log it at Oversight instead
2358 $logtype = $suppress ?
'suppress' : 'delete';
2359 $log = new LogPage( $logtype );
2360 $log->addEntry( 'delete', $this->mTitle
, $reason );
2366 * Roll back the most recent consecutive set of edits to a page
2367 * from the same user; fails if there are no eligible edits to
2368 * roll back to, e.g. user is the sole contributor. This function
2369 * performs permissions checks on $wgUser, then calls commitRollback()
2370 * to do the dirty work
2372 * @param string $fromP - Name of the user whose edits to rollback.
2373 * @param string $summary - Custom summary. Set to default summary if empty.
2374 * @param string $token - Rollback token.
2375 * @param bool $bot - If true, mark all reverted edits as bot.
2377 * @param array $resultDetails contains result-specific array of additional values
2378 * 'alreadyrolled' : 'current' (rev)
2379 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2381 * @return array of errors, each error formatted as
2382 * array(messagekey, param1, param2, ...).
2383 * On success, the array is empty. This array can also be passed to
2384 * OutputPage::showPermissionsErrorPage().
2386 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2388 $resultDetails = null;
2391 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2392 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2393 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2394 $errors[] = array( 'sessionfailure' );
2396 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2397 $errors[] = array( 'actionthrottledtext' );
2399 # If there were errors, bail out now
2403 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2407 * Backend implementation of doRollback(), please refer there for parameter
2408 * and return value documentation
2410 * NOTE: This function does NOT check ANY permissions, it just commits the
2411 * rollback to the DB Therefore, you should only call this function direct-
2412 * ly if you want to use custom permissions checks. If you don't, use
2413 * doRollback() instead.
2415 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2416 global $wgUseRCPatrol, $wgUser;
2417 $dbw = wfGetDB( DB_MASTER
);
2419 if( wfReadOnly() ) {
2420 return array( array( 'readonlytext' ) );
2423 # Get the last editor
2424 $current = Revision
::newFromTitle( $this->mTitle
);
2425 if( is_null( $current ) ) {
2426 # Something wrong... no page?
2427 return array(array('notanarticle'));
2430 $from = str_replace( '_', ' ', $fromP );
2431 if( $from != $current->getUserText() ) {
2432 $resultDetails = array( 'current' => $current );
2433 return array(array('alreadyrolled',
2434 htmlspecialchars($this->mTitle
->getPrefixedText()),
2435 htmlspecialchars($fromP),
2436 htmlspecialchars($current->getUserText())
2440 # Get the last edit not by this guy
2441 $user = intval( $current->getUser() );
2442 $user_text = $dbw->addQuotes( $current->getUserText() );
2443 $s = $dbw->selectRow( 'revision',
2444 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2445 array( 'rev_page' => $current->getPage(),
2446 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2448 array( 'USE INDEX' => 'page_timestamp',
2449 'ORDER BY' => 'rev_timestamp DESC' )
2451 if( $s === false ) {
2452 # No one else ever edited this page
2453 return array(array('cantrollback'));
2454 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2455 # Only admins can see this text
2456 return array(array('notvisiblerev'));
2460 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2461 # Mark all reverted edits as bot
2464 if ( $wgUseRCPatrol ) {
2465 # Mark all reverted edits as patrolled
2466 $set['rc_patrolled'] = 1;
2470 $dbw->update( 'recentchanges', $set,
2472 'rc_cur_id' => $current->getPage(),
2473 'rc_user_text' => $current->getUserText(),
2474 "rc_timestamp > '{$s->rev_timestamp}'",
2479 # Generate the edit summary if necessary
2480 $target = Revision
::newFromId( $s->rev_id
);
2481 if( empty( $summary ) )
2484 $summary = wfMsgForContent( 'revertpage',
2485 $target->getUserText(), $from,
2486 $s->rev_id
, $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2487 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2492 $flags = EDIT_UPDATE
;
2494 if ($wgUser->isAllowed('minoredit'))
2495 $flags |
= EDIT_MINOR
;
2497 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2498 $flags |
= EDIT_FORCE_BOT
;
2499 $this->doEdit( $target->getText(), $summary, $flags );
2501 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2503 $resultDetails = array(
2504 'summary' => $summary,
2505 'current' => $current,
2506 'target' => $target,
2512 * User interface for rollback operations
2514 function rollback() {
2515 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2518 $result = $this->doRollback(
2519 $wgRequest->getVal( 'from' ),
2520 $wgRequest->getText( 'summary' ),
2521 $wgRequest->getVal( 'token' ),
2522 $wgRequest->getBool( 'bot' ),
2526 if( in_array( array( 'blocked' ), $result ) ) {
2527 $wgOut->blockedPage();
2530 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2531 $wgOut->rateLimited();
2534 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2535 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2536 $errArray = $result[0];
2537 $errMsg = array_shift( $errArray );
2538 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2539 if( isset( $details['current'] ) ){
2540 $current = $details['current'];
2541 if( $current->getComment() != '' ) {
2542 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2547 # Display permissions errors before read-only message -- there's no
2548 # point in misleading the user into thinking the inability to rollback
2549 # is only temporary.
2550 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2551 # array_diff is completely broken for arrays of arrays, sigh. Re-
2552 # move any 'readonlytext' error manually.
2554 foreach( $result as $error ) {
2555 if( $error != array( 'readonlytext' ) ) {
2559 $wgOut->showPermissionsErrorPage( $out );
2562 if( $result == array( array('readonlytext') ) ) {
2563 $wgOut->readOnlyPage();
2567 $current = $details['current'];
2568 $target = $details['target'];
2569 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2570 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2571 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2572 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2573 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2574 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2575 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2576 $wgOut->returnToMain( false, $this->mTitle
);
2581 * Do standard deferred updates after page view
2584 function viewUpdates() {
2585 global $wgDeferredUpdateList;
2587 if ( 0 != $this->getID() ) {
2588 global $wgDisableCounters;
2589 if( !$wgDisableCounters ) {
2590 Article
::incViewCount( $this->getID() );
2591 $u = new SiteStatsUpdate( 1, 0, 0 );
2592 array_push( $wgDeferredUpdateList, $u );
2596 # Update newtalk / watchlist notification status
2598 $wgUser->clearNotification( $this->mTitle
);
2602 * Prepare text which is about to be saved.
2603 * Returns a stdclass with source, pst and output members
2605 function prepareTextForEdit( $text, $revid=null ) {
2606 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2608 return $this->mPreparedEdit
;
2611 $edit = (object)array();
2612 $edit->revid
= $revid;
2613 $edit->newText
= $text;
2614 $edit->pst
= $this->preSaveTransform( $text );
2615 $options = new ParserOptions
;
2616 $options->setTidy( true );
2617 $options->enableLimitReport();
2618 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2619 $edit->oldText
= $this->getContent();
2620 $this->mPreparedEdit
= $edit;
2625 * Do standard deferred updates after page edit.
2626 * Update links tables, site stats, search index and message cache.
2627 * Every 100th edit, prune the recent changes table.
2630 * @param $text New text of the article
2631 * @param $summary Edit summary
2632 * @param $minoredit Minor edit
2633 * @param $timestamp_of_pagechange Timestamp associated with the page change
2634 * @param $newid rev_id value of the new revision
2635 * @param $changed Whether or not the content actually changed
2637 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2638 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2640 wfProfileIn( __METHOD__
);
2643 # Be careful not to double-PST: $text is usually already PST-ed once
2644 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2645 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2646 $editInfo = $this->prepareTextForEdit( $text, $newid );
2648 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2649 $editInfo = $this->mPreparedEdit
;
2652 # Save it to the parser cache
2653 if ( $wgEnableParserCache ) {
2654 $parserCache = ParserCache
::singleton();
2655 $parserCache->save( $editInfo->output
, $this, $wgUser );
2658 # Update the links tables
2659 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2662 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2663 if ( 0 == mt_rand( 0, 99 ) ) {
2664 // Flush old entries from the `recentchanges` table; we do this on
2665 // random requests so as to avoid an increase in writes for no good reason
2667 $dbw = wfGetDB( DB_MASTER
);
2668 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2669 $recentchanges = $dbw->tableName( 'recentchanges' );
2670 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2671 $dbw->query( $sql );
2675 $id = $this->getID();
2676 $title = $this->mTitle
->getPrefixedDBkey();
2677 $shortTitle = $this->mTitle
->getDBkey();
2680 wfProfileOut( __METHOD__
);
2684 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2685 array_push( $wgDeferredUpdateList, $u );
2686 $u = new SearchUpdate( $id, $title, $text );
2687 array_push( $wgDeferredUpdateList, $u );
2689 # If this is another user's talk page, update newtalk
2690 # Don't do this if $changed = false otherwise some idiot can null-edit a
2691 # load of user talk pages and piss people off, nor if it's a minor edit
2692 # by a properly-flagged bot.
2693 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2694 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2695 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2696 $other = User
::newFromName( $shortTitle );
2697 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2698 // An anonymous user
2699 $other = new User();
2700 $other->setName( $shortTitle );
2703 $other->setNewtalk( true );
2708 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2709 $wgMessageCache->replace( $shortTitle, $text );
2712 wfProfileOut( __METHOD__
);
2716 * Perform article updates on a special page creation.
2718 * @param Revision $rev
2720 * @todo This is a shitty interface function. Kill it and replace the
2721 * other shitty functions like editUpdates and such so it's not needed
2724 function createUpdates( $rev ) {
2725 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2726 $this->mTotalAdjustment
= 1;
2727 $this->editUpdates( $rev->getText(), $rev->getComment(),
2728 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2732 * Generate the navigation links when browsing through an article revisions
2733 * It shows the information as:
2734 * Revision as of \<date\>; view current revision
2735 * \<- Previous version | Next Version -\>
2738 * @param string $oldid Revision ID of this article revision
2740 function setOldSubtitle( $oldid=0 ) {
2741 global $wgLang, $wgOut, $wgUser;
2743 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2747 $revision = Revision
::newFromId( $oldid );
2749 $current = ( $oldid == $this->mLatest
);
2750 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2751 $sk = $wgUser->getSkin();
2753 ?
wfMsg( 'currentrevisionlink' )
2754 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2757 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2758 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2760 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2761 : wfMsg( 'previousrevision' );
2763 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2765 $nextlink = $current
2766 ?
wfMsg( 'nextrevision' )
2767 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2768 $nextdiff = $current
2770 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2773 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2774 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2775 if( $revision->isCurrent() ) {
2776 // We don't handle top deleted edits too well
2777 $cdel = wfMsgHtml('rev-delundel');
2778 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2779 // If revision was hidden from sysops
2780 $cdel = wfMsgHtml('rev-delundel');
2782 $cdel = $sk->makeKnownLinkObj( $revdel,
2783 wfMsgHtml('rev-delundel'),
2784 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2785 '&oldid=' . urlencode( $oldid ) );
2786 // Bolden oversighted content
2787 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2788 $cdel = "<strong>$cdel</strong>";
2790 $cdel = "(<small>$cdel</small>) ";
2792 # Show user links if allowed to see them. Normally they
2793 # are hidden regardless, but since we can already see the text here...
2794 $userlinks = $sk->revUserTools( $revision, false );
2796 $m = wfMsg( 'revision-info-current' );
2797 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2798 ?
'revision-info-current'
2801 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2803 "\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";
2804 $wgOut->setSubtitle( $r );
2808 * This function is called right before saving the wikitext,
2809 * so we can do things like signatures and links-in-context.
2811 * @param string $text
2813 function preSaveTransform( $text ) {
2814 global $wgParser, $wgUser;
2815 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2818 /* Caching functions */
2821 * checkLastModified returns true if it has taken care of all
2822 * output to the client that is necessary for this request.
2823 * (that is, it has sent a cached version of the page)
2825 function tryFileCache() {
2826 static $called = false;
2828 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2832 if($this->isFileCacheable()) {
2833 $touched = $this->mTouched
;
2834 $cache = new HTMLFileCache( $this->mTitle
);
2835 if($cache->isFileCacheGood( $touched )) {
2836 wfDebug( "Article::tryFileCache(): about to load file\n" );
2837 $cache->loadFromFileCache();
2840 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2841 ob_start( array(&$cache, 'saveToFileCache' ) );
2844 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2849 * Check if the page can be cached
2852 function isFileCacheable() {
2853 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2854 $action = $wgRequest->getVal( 'action' );
2855 $oldid = $wgRequest->getVal( 'oldid' );
2856 $diff = $wgRequest->getVal( 'diff' );
2857 $redirect = $wgRequest->getVal( 'redirect' );
2858 $printable = $wgRequest->getVal( 'printable' );
2859 $page = $wgRequest->getVal( 'page' );
2861 //check for non-standard user language; this covers uselang,
2862 //and extensions for auto-detecting user language.
2863 $ulang = $wgLang->getCode();
2864 $clang = $wgContLang->getCode();
2866 $cacheable = $wgUseFileCache
2867 && (!$wgShowIPinHeader)
2868 && ($this->getID() != 0)
2869 && ($wgUser->isAnon())
2870 && (!$wgUser->getNewtalk())
2871 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2872 && (empty( $action ) ||
$action == 'view')
2875 && (!isset($redirect))
2876 && (!isset($printable))
2878 && (!$this->mRedirectedFrom
)
2879 && ($ulang === $clang);
2882 //extension may have reason to disable file caching on some pages.
2883 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2890 * Loads page_touched and returns a value indicating if it should be used
2893 function checkTouched() {
2894 if( !$this->mDataLoaded
) {
2895 $this->loadPageData();
2897 return !$this->mIsRedirect
;
2901 * Get the page_touched field
2903 function getTouched() {
2904 # Ensure that page data has been loaded
2905 if( !$this->mDataLoaded
) {
2906 $this->loadPageData();
2908 return $this->mTouched
;
2912 * Get the page_latest field
2914 function getLatest() {
2915 if ( !$this->mDataLoaded
) {
2916 $this->loadPageData();
2918 return $this->mLatest
;
2922 * Edit an article without doing all that other stuff
2923 * The article must already exist; link tables etc
2924 * are not updated, caches are not flushed.
2926 * @param string $text text submitted
2927 * @param string $comment comment submitted
2928 * @param bool $minor whereas it's a minor modification
2930 function quickEdit( $text, $comment = '', $minor = 0 ) {
2931 wfProfileIn( __METHOD__
);
2933 $dbw = wfGetDB( DB_MASTER
);
2935 $revision = new Revision( array(
2936 'page' => $this->getId(),
2938 'comment' => $comment,
2939 'minor_edit' => $minor ?
1 : 0,
2941 $revision->insertOn( $dbw );
2942 $this->updateRevisionOn( $dbw, $revision );
2945 wfProfileOut( __METHOD__
);
2949 * Used to increment the view counter
2952 * @param integer $id article id
2954 function incViewCount( $id ) {
2955 $id = intval( $id );
2956 global $wgHitcounterUpdateFreq, $wgDBtype;
2958 $dbw = wfGetDB( DB_MASTER
);
2959 $pageTable = $dbw->tableName( 'page' );
2960 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2961 $acchitsTable = $dbw->tableName( 'acchits' );
2963 if( $wgHitcounterUpdateFreq <= 1 ) {
2964 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2968 # Not important enough to warrant an error page in case of failure
2969 $oldignore = $dbw->ignoreErrors( true );
2971 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2973 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2974 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2975 # Most of the time (or on SQL errors), skip row count check
2976 $dbw->ignoreErrors( $oldignore );
2980 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2981 $row = $dbw->fetchObject( $res );
2982 $rown = intval( $row->n
);
2983 if( $rown >= $wgHitcounterUpdateFreq ){
2984 wfProfileIn( 'Article::incViewCount-collect' );
2985 $old_user_abort = ignore_user_abort( true );
2987 if ($wgDBtype == 'mysql')
2988 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2989 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2990 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2991 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2993 $dbw->query("DELETE FROM $hitcounterTable");
2994 if ($wgDBtype == 'mysql') {
2995 $dbw->query('UNLOCK TABLES');
2996 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2997 'WHERE page_id = hc_id');
3000 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3001 "FROM $acchitsTable WHERE page_id = hc_id");
3003 $dbw->query("DROP TABLE $acchitsTable");
3005 ignore_user_abort( $old_user_abort );
3006 wfProfileOut( 'Article::incViewCount-collect' );
3008 $dbw->ignoreErrors( $oldignore );
3012 * The onArticle*() functions are supposed to be a kind of hooks
3013 * which should be called whenever any of the specified actions
3016 * This is a good place to put code to clear caches, for instance.
3018 * This is called on page move and undelete, as well as edit
3020 * @param $title_obj a title object
3023 static function onArticleCreate($title) {
3024 # The talk page isn't in the regular link tables, so we need to update manually:
3025 if ( $title->isTalkPage() ) {
3026 $other = $title->getSubjectPage();
3028 $other = $title->getTalkPage();
3030 $other->invalidateCache();
3031 $other->purgeSquid();
3033 $title->touchLinks();
3034 $title->purgeSquid();
3035 $title->deleteTitleProtection();
3038 static function onArticleDelete( $title ) {
3039 global $wgUseFileCache, $wgMessageCache;
3041 // Update existence markers on article/talk tabs...
3042 if( $title->isTalkPage() ) {
3043 $other = $title->getSubjectPage();
3045 $other = $title->getTalkPage();
3047 $other->invalidateCache();
3048 $other->purgeSquid();
3050 $title->touchLinks();
3051 $title->purgeSquid();
3054 if ( $wgUseFileCache ) {
3055 $cm = new HTMLFileCache( $title );
3056 @unlink
( $cm->fileCacheName() );
3059 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3060 $wgMessageCache->replace( $title->getDBkey(), false );
3062 if( $title->getNamespace() == NS_IMAGE
) {
3063 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3064 $update->doUpdate();
3069 * Purge caches on page update etc
3071 static function onArticleEdit( $title ) {
3072 global $wgDeferredUpdateList, $wgUseFileCache;
3074 // Invalidate caches of articles which include this page
3075 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3077 // Invalidate the caches of all pages which redirect here
3078 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3080 # Purge squid for this page only
3081 $title->purgeSquid();
3084 if ( $wgUseFileCache ) {
3085 $cm = new HTMLFileCache( $title );
3086 @unlink
( $cm->fileCacheName() );
3093 * Overriden by ImagePage class, only present here to avoid a fatal error
3094 * Called for ?action=revert
3096 public function revert(){
3098 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3102 * Info about this page
3103 * Called for ?action=info when $wgAllowPageInfo is on.
3108 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3110 if ( !$wgAllowPageInfo ) {
3111 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3115 $page = $this->mTitle
->getSubjectPage();
3117 $wgOut->setPagetitle( $page->getPrefixedText() );
3118 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3119 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3121 if( !$this->mTitle
->exists() ) {
3122 $wgOut->addHtml( '<div class="noarticletext">' );
3123 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3124 // This doesn't quite make sense; the user is asking for
3125 // information about the _page_, not the message... -- RC
3126 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3128 $msg = $wgUser->isLoggedIn()
3130 : 'noarticletextanon';
3131 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3133 $wgOut->addHtml( '</div>' );
3135 $dbr = wfGetDB( DB_SLAVE
);
3137 'wl_title' => $page->getDBkey(),
3138 'wl_namespace' => $page->getNamespace() );
3139 $numwatchers = $dbr->selectField(
3144 $this->getSelectOptions() );
3146 $pageInfo = $this->pageCountInfo( $page );
3147 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3149 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3150 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3152 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3154 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3156 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3158 $wgOut->addHTML( '</ul>' );
3164 * Return the total number of edits and number of unique editors
3165 * on a given page. If page does not exist, returns false.
3167 * @param Title $title
3171 function pageCountInfo( $title ) {
3172 $id = $title->getArticleId();
3177 $dbr = wfGetDB( DB_SLAVE
);
3179 $rev_clause = array( 'rev_page' => $id );
3181 $edits = $dbr->selectField(
3186 $this->getSelectOptions() );
3188 $authors = $dbr->selectField(
3190 'COUNT(DISTINCT rev_user_text)',
3193 $this->getSelectOptions() );
3195 return array( 'edits' => $edits, 'authors' => $authors );
3199 * Return a list of templates used by this article.
3200 * Uses the templatelinks table
3202 * @return array Array of Title objects
3204 function getUsedTemplates() {
3206 $id = $this->mTitle
->getArticleID();
3211 $dbr = wfGetDB( DB_SLAVE
);
3212 $res = $dbr->select( array( 'templatelinks' ),
3213 array( 'tl_namespace', 'tl_title' ),
3214 array( 'tl_from' => $id ),
3215 'Article:getUsedTemplates' );
3216 if ( false !== $res ) {
3217 if ( $dbr->numRows( $res ) ) {
3218 while ( $row = $dbr->fetchObject( $res ) ) {
3219 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3223 $dbr->freeResult( $res );
3228 * Returns a list of hidden categories this page is a member of.
3229 * Uses the page_props and categorylinks tables.
3231 * @return array Array of Title objects
3233 function getHiddenCategories() {
3235 $id = $this->mTitle
->getArticleID();
3240 $dbr = wfGetDB( DB_SLAVE
);
3241 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3243 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3244 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3245 'Article:getHiddenCategories' );
3246 if ( false !== $res ) {
3247 if ( $dbr->numRows( $res ) ) {
3248 while ( $row = $dbr->fetchObject( $res ) ) {
3249 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3253 $dbr->freeResult( $res );
3258 * Return an auto-generated summary if the text provided is a redirect.
3260 * @param string $text The wikitext to check
3261 * @return string '' or an appropriate summary
3263 public static function getRedirectAutosummary( $text ) {
3264 $rt = Title
::newFromRedirect( $text );
3265 if( is_object( $rt ) )
3266 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3272 * Return an auto-generated summary if the new text is much shorter than
3275 * @param string $oldtext The previous text of the page
3276 * @param string $text The submitted text of the page
3277 * @return string An appropriate autosummary, or an empty string.
3279 public static function getBlankingAutosummary( $oldtext, $text ) {
3280 if ($oldtext!='' && $text=='') {
3281 return wfMsgForContent('autosumm-blank');
3282 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3283 #Removing more than 90% of the article
3285 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3286 return wfMsgForContent('autosumm-replace', $truncatedtext);
3293 * Return an applicable autosummary if one exists for the given edit.
3294 * @param string $oldtext The previous text of the page.
3295 * @param string $newtext The submitted text of the page.
3296 * @param bitmask $flags A bitmask of flags submitted for the edit.
3297 * @return string An appropriate autosummary, or an empty string.
3299 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3301 # This code is UGLY UGLY UGLY.
3302 # Somebody PLEASE come up with a more elegant way to do it.
3304 #Redirect autosummaries
3305 $summary = self
::getRedirectAutosummary( $newtext );
3310 #Blanking autosummaries
3311 if (!($flags & EDIT_NEW
))
3312 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3317 #New page autosummaries
3318 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3319 #If they're making a new article, give its text, truncated, in the summary.
3321 $truncatedtext = $wgContLang->truncate(
3322 str_replace("\n", ' ', $newtext),
3323 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3325 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3335 * Add the primary page-view wikitext to the output buffer
3336 * Saves the text into the parser cache if possible.
3337 * Updates templatelinks if it is out of date.
3339 * @param string $text
3340 * @param bool $cache
3342 public function outputWikiText( $text, $cache = true ) {
3343 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3345 $popts = $wgOut->parserOptions();
3346 $popts->setTidy(true);
3347 $popts->enableLimitReport();
3348 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3349 $popts, true, true, $this->getRevIdFetched() );
3350 $popts->setTidy(false);
3351 $popts->enableLimitReport( false );
3352 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3353 $parserCache = ParserCache
::singleton();
3354 $parserCache->save( $parserOutput, $this, $wgUser );
3357 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3358 // templatelinks table may have become out of sync,
3359 // especially if using variable-based transclusions.
3360 // For paranoia, check if things have changed and if
3361 // so apply updates to the database. This will ensure
3362 // that cascaded protections apply as soon as the changes
3365 # Get templates from templatelinks
3366 $id = $this->mTitle
->getArticleID();
3368 $tlTemplates = array();
3370 $dbr = wfGetDB( DB_SLAVE
);
3371 $res = $dbr->select( array( 'templatelinks' ),
3372 array( 'tl_namespace', 'tl_title' ),
3373 array( 'tl_from' => $id ),
3374 'Article:getUsedTemplates' );
3378 if ( false !== $res ) {
3379 if ( $dbr->numRows( $res ) ) {
3380 while ( $row = $dbr->fetchObject( $res ) ) {
3381 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3386 # Get templates from parser output.
3387 $poTemplates_allns = $parserOutput->getTemplates();
3389 $poTemplates = array ();
3390 foreach ( $poTemplates_allns as $ns_templates ) {
3391 $poTemplates = array_merge( $poTemplates, $ns_templates );
3395 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3397 if ( count( $templates_diff ) > 0 ) {
3398 # Whee, link updates time.
3399 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3401 $dbw = wfGetDb( DB_MASTER
);
3410 $wgOut->addParserOutput( $parserOutput );
3414 * Update all the appropriate counts in the category table, given that
3415 * we've added the categories $added and deleted the categories $deleted.
3417 * @param $added array The names of categories that were added
3418 * @param $deleted array The names of categories that were deleted
3421 public function updateCategoryCounts( $added, $deleted ) {
3422 $ns = $this->mTitle
->getNamespace();
3423 $dbw = wfGetDB( DB_MASTER
);
3425 # First make sure the rows exist. If one of the "deleted" ones didn't
3426 # exist, we might legitimately not create it, but it's simpler to just
3427 # create it and then give it a negative value, since the value is bogus
3430 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3431 $insertCats = array_merge( $added, $deleted );
3432 if( !$insertCats ) {
3433 # Okay, nothing to do
3436 $insertRows = array();
3437 foreach( $insertCats as $cat ) {
3438 $insertRows[] = array( 'cat_title' => $cat );
3440 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3442 $addFields = array( 'cat_pages = cat_pages + 1' );
3443 $removeFields = array( 'cat_pages = cat_pages - 1' );
3444 if( $ns == NS_CATEGORY
) {
3445 $addFields[] = 'cat_subcats = cat_subcats + 1';
3446 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3447 } elseif( $ns == NS_IMAGE
) {
3448 $addFields[] = 'cat_files = cat_files + 1';
3449 $removeFields[] = 'cat_files = cat_files - 1';
3456 array( 'cat_title' => $added ),
3464 array( 'cat_title' => $deleted ),