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' );
1866 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1868 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1872 } # End "changed" check
1878 * Take an array of page restrictions and flatten it to a string
1879 * suitable for insertion into the page_restrictions field.
1880 * @param array $limit
1884 function flattenRestrictions( $limit ) {
1885 if( !is_array( $limit ) ) {
1886 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1890 foreach( $limit as $action => $restrictions ) {
1891 if( $restrictions != '' ) {
1892 $bits[] = "$action=$restrictions";
1895 return implode( ':', $bits );
1899 * Auto-generates a deletion reason
1900 * @param bool &$hasHistory Whether the page has a history
1902 public function generateReason(&$hasHistory)
1905 $dbw = wfGetDB(DB_MASTER
);
1906 // Get the last revision
1907 $rev = Revision
::newFromTitle($this->mTitle
);
1910 // Get the article's contents
1911 $contents = $rev->getText();
1913 // If the page is blank, use the text from the previous revision,
1914 // which can only be blank if there's a move/import/protect dummy revision involved
1917 $prev = $rev->getPrevious();
1920 $contents = $prev->getText();
1925 // Find out if there was only one contributor
1926 // Only scan the last 20 revisions
1928 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1929 array('LIMIT' => $limit));
1931 // This page has no revisions, which is very weird
1933 if($res->numRows() > 1)
1936 $hasHistory = false;
1937 $row = $dbw->fetchObject($res);
1938 $onlyAuthor = $row->rev_user_text
;
1939 // Try to find a second contributor
1940 while( $row = $dbw->fetchObject($res) ) {
1941 if($row->rev_user_text
!= $onlyAuthor) {
1942 $onlyAuthor = false;
1946 $dbw->freeResult($res);
1948 // Generate the summary with a '$1' placeholder
1950 // The current revision is blank and the one before is also
1951 // blank. It's just not our lucky day
1952 $reason = wfMsgForContent('exbeforeblank', '$1');
1955 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1957 $reason = wfMsgForContent('excontent', '$1');
1960 // Replace newlines with spaces to prevent uglyness
1961 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1962 // Calculate the maximum amount of chars to get
1963 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1964 $maxLength = 255 - (strlen($reason) - 2) - 3;
1965 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1966 // Remove possible unfinished links
1967 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1968 // Now replace the '$1' placeholder
1969 $reason = str_replace( '$1', $contents, $reason );
1975 * UI entry point for page deletion
1978 global $wgUser, $wgOut, $wgRequest;
1980 $confirm = $wgRequest->wasPosted() &&
1981 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1983 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1984 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1986 $reason = $this->DeleteReasonList
;
1988 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1989 // Entry from drop down menu + additional comment
1990 $reason .= ': ' . $this->DeleteReason
;
1991 } elseif ( $reason == 'other' ) {
1992 $reason = $this->DeleteReason
;
1994 # Flag to hide all contents of the archived revisions
1995 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
1997 # This code desperately needs to be totally rewritten
1999 # Read-only check...
2000 if ( wfReadOnly() ) {
2001 $wgOut->readOnlyPage();
2006 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2008 if (count($permission_errors)>0) {
2009 $wgOut->showPermissionsErrorPage( $permission_errors );
2013 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2015 # Better double-check that it hasn't been deleted yet!
2016 $dbw = wfGetDB( DB_MASTER
);
2017 $conds = $this->mTitle
->pageCond();
2018 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2019 if ( $latest === false ) {
2020 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2024 # Hack for big sites
2025 $bigHistory = $this->isBigDeletion();
2026 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2027 global $wgLang, $wgDeleteRevisionsLimit;
2028 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2029 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2034 $this->doDelete( $reason, $suppress );
2035 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2037 } elseif( $this->mTitle
->userIsWatching() ) {
2043 // Generate deletion reason
2044 $hasHistory = false;
2045 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2047 // If the page has a history, insert a warning
2048 if( $hasHistory && !$confirm ) {
2049 $skin=$wgUser->getSkin();
2050 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2052 global $wgLang, $wgDeleteRevisionsLimit;
2053 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2054 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2058 return $this->confirmDelete( '', $reason );
2062 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2064 function isBigDeletion() {
2065 global $wgDeleteRevisionsLimit;
2066 if( $wgDeleteRevisionsLimit ) {
2067 $revCount = $this->estimateRevisionCount();
2068 return $revCount > $wgDeleteRevisionsLimit;
2074 * @return int approximate revision count
2076 function estimateRevisionCount() {
2078 // For an exact count...
2079 //return $dbr->selectField( 'revision', 'COUNT(*)',
2080 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2081 return $dbr->estimateRowCount( 'revision', '*',
2082 array( 'rev_page' => $this->getId() ), __METHOD__
);
2086 * Get the last N authors
2087 * @param int $num Number of revisions to get
2088 * @param string $revLatest The latest rev_id, selected from the master (optional)
2089 * @return array Array of authors, duplicates not removed
2091 function getLastNAuthors( $num, $revLatest = 0 ) {
2092 wfProfileIn( __METHOD__
);
2094 // First try the slave
2095 // If that doesn't have the latest revision, try the master
2097 $db = wfGetDB( DB_SLAVE
);
2099 $res = $db->select( array( 'page', 'revision' ),
2100 array( 'rev_id', 'rev_user_text' ),
2102 'page_namespace' => $this->mTitle
->getNamespace(),
2103 'page_title' => $this->mTitle
->getDBkey(),
2104 'rev_page = page_id'
2105 ), __METHOD__
, $this->getSelectOptions( array(
2106 'ORDER BY' => 'rev_timestamp DESC',
2111 wfProfileOut( __METHOD__
);
2114 $row = $db->fetchObject( $res );
2115 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2116 $db = wfGetDB( DB_MASTER
);
2121 } while ( $continue );
2123 $authors = array( $row->rev_user_text
);
2124 while ( $row = $db->fetchObject( $res ) ) {
2125 $authors[] = $row->rev_user_text
;
2127 wfProfileOut( __METHOD__
);
2132 * Output deletion confirmation dialog
2133 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2134 * @param $reason string Prefilled reason
2136 function confirmDelete( $par, $reason ) {
2137 global $wgOut, $wgUser, $wgContLang;
2138 $align = $wgContLang->isRtl() ?
'left' : 'right';
2140 wfDebug( "Article::confirmDelete\n" );
2142 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle
) ) );
2143 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2144 $wgOut->addWikiMsg( 'confirmdeletetext' );
2146 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2147 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2148 $suppress .= Xml
::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2149 $suppress .= "</td></tr>";
2154 $form = Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle
->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2155 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2156 Xml
::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2157 Xml
::openElement( 'table' ) .
2158 "<tr id=\"wpDeleteReasonListRow\">
2159 <td align='$align'>" .
2160 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2163 Xml
::listDropDown( 'wpDeleteReasonList',
2164 wfMsgForContent( 'deletereason-dropdown' ),
2165 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2168 <tr id=\"wpDeleteReasonRow\">
2169 <td align='$align'>" .
2170 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2173 Xml
::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2179 Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '3' ) ) .
2186 Xml
::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2189 Xml
::closeElement( 'table' ) .
2190 Xml
::closeElement( 'fieldset' ) .
2191 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2192 Xml
::closeElement( 'form' );
2194 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2195 $skin = $wgUser->getSkin();
2196 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2197 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2200 $wgOut->addHTML( $form );
2201 $this->showLogExtract( $wgOut );
2206 * Show relevant lines from the deletion log
2208 function showLogExtract( $out ) {
2209 $out->addHtml( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2210 LogEventsList
::showLogExtract( $out, 'delete', $this->mTitle
->getPrefixedText() );
2215 * Perform a deletion and output success or failure messages
2217 function doDelete( $reason, $suppress = false ) {
2218 global $wgOut, $wgUser;
2219 wfDebug( __METHOD__
."\n" );
2221 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2222 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2223 $deleted = $this->mTitle
->getPrefixedText();
2225 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2226 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2228 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2230 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2231 $wgOut->returnToMain( false );
2232 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2234 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2240 * Back-end article deletion
2241 * Deletes the article with database consistency, writes logs, purges caches
2244 function doDeleteArticle( $reason, $suppress = false ) {
2245 global $wgUseSquid, $wgDeferredUpdateList;
2246 global $wgUseTrackbacks;
2248 wfDebug( __METHOD__
."\n" );
2250 $dbw = wfGetDB( DB_MASTER
);
2251 $ns = $this->mTitle
->getNamespace();
2252 $t = $this->mTitle
->getDBkey();
2253 $id = $this->mTitle
->getArticleID();
2255 if ( $t == '' ||
$id == 0 ) {
2259 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2260 array_push( $wgDeferredUpdateList, $u );
2262 // Bitfields to further suppress the content
2265 // This should be 15...
2266 $bitfield |
= Revision
::DELETED_TEXT
;
2267 $bitfield |
= Revision
::DELETED_COMMENT
;
2268 $bitfield |
= Revision
::DELETED_USER
;
2269 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2271 $bitfield = 'rev_deleted';
2275 // For now, shunt the revision data into the archive table.
2276 // Text is *not* removed from the text table; bulk storage
2277 // is left intact to avoid breaking block-compression or
2278 // immutable storage schemes.
2280 // For backwards compatibility, note that some older archive
2281 // table entries will have ar_text and ar_flags fields still.
2283 // In the future, we may keep revisions and mark them with
2284 // the rev_deleted field, which is reserved for this purpose.
2285 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2287 'ar_namespace' => 'page_namespace',
2288 'ar_title' => 'page_title',
2289 'ar_comment' => 'rev_comment',
2290 'ar_user' => 'rev_user',
2291 'ar_user_text' => 'rev_user_text',
2292 'ar_timestamp' => 'rev_timestamp',
2293 'ar_minor_edit' => 'rev_minor_edit',
2294 'ar_rev_id' => 'rev_id',
2295 'ar_text_id' => 'rev_text_id',
2296 'ar_text' => '\'\'', // Be explicit to appease
2297 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2298 'ar_len' => 'rev_len',
2299 'ar_page_id' => 'page_id',
2300 'ar_deleted' => $bitfield
2303 'page_id = rev_page'
2307 # Delete restrictions for it
2308 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2310 # Fix category table counts
2312 $res = $dbw->select( 'categorylinks', 'cl_to',
2313 array( 'cl_from' => $id ), __METHOD__
);
2314 foreach( $res as $row ) {
2315 $cats []= $row->cl_to
;
2317 $this->updateCategoryCounts( array(), $cats );
2319 # Now that it's safely backed up, delete it
2320 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2321 $ok = ( $dbw->affectedRows() != 0 ); // getArticleId() uses slave, could be laggy
2327 # If using cascading deletes, we can skip some explicit deletes
2328 if ( !$dbw->cascadingDeletes() ) {
2329 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2331 if ($wgUseTrackbacks)
2332 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2334 # Delete outgoing links
2335 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2336 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2337 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2338 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2339 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2340 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2341 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2344 # If using cleanup triggers, we can skip some manual deletes
2345 if ( !$dbw->cleanupTriggers() ) {
2347 # Clean up recentchanges entries...
2348 $dbw->delete( 'recentchanges',
2349 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG
),
2354 Article
::onArticleDelete( $this->mTitle
);
2356 # Clear the cached article id so the interface doesn't act like we exist
2357 $this->mTitle
->resetArticleID( 0 );
2358 $this->mTitle
->mArticleID
= 0;
2360 # Log the deletion, if the page was suppressed, log it at Oversight instead
2361 $logtype = $suppress ?
'suppress' : 'delete';
2362 $log = new LogPage( $logtype );
2363 # Make sure logging got through
2364 $ok = $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
2375 * Roll back the most recent consecutive set of edits to a page
2376 * from the same user; fails if there are no eligible edits to
2377 * roll back to, e.g. user is the sole contributor. This function
2378 * performs permissions checks on $wgUser, then calls commitRollback()
2379 * to do the dirty work
2381 * @param string $fromP - Name of the user whose edits to rollback.
2382 * @param string $summary - Custom summary. Set to default summary if empty.
2383 * @param string $token - Rollback token.
2384 * @param bool $bot - If true, mark all reverted edits as bot.
2386 * @param array $resultDetails contains result-specific array of additional values
2387 * 'alreadyrolled' : 'current' (rev)
2388 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2390 * @return array of errors, each error formatted as
2391 * array(messagekey, param1, param2, ...).
2392 * On success, the array is empty. This array can also be passed to
2393 * OutputPage::showPermissionsErrorPage().
2395 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2397 $resultDetails = null;
2400 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2401 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2402 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2403 $errors[] = array( 'sessionfailure' );
2405 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2406 $errors[] = array( 'actionthrottledtext' );
2408 # If there were errors, bail out now
2412 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2416 * Backend implementation of doRollback(), please refer there for parameter
2417 * and return value documentation
2419 * NOTE: This function does NOT check ANY permissions, it just commits the
2420 * rollback to the DB Therefore, you should only call this function direct-
2421 * ly if you want to use custom permissions checks. If you don't, use
2422 * doRollback() instead.
2424 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2425 global $wgUseRCPatrol, $wgUser;
2426 $dbw = wfGetDB( DB_MASTER
);
2428 if( wfReadOnly() ) {
2429 return array( array( 'readonlytext' ) );
2432 # Get the last editor
2433 $current = Revision
::newFromTitle( $this->mTitle
);
2434 if( is_null( $current ) ) {
2435 # Something wrong... no page?
2436 return array(array('notanarticle'));
2439 $from = str_replace( '_', ' ', $fromP );
2440 if( $from != $current->getUserText() ) {
2441 $resultDetails = array( 'current' => $current );
2442 return array(array('alreadyrolled',
2443 htmlspecialchars($this->mTitle
->getPrefixedText()),
2444 htmlspecialchars($fromP),
2445 htmlspecialchars($current->getUserText())
2449 # Get the last edit not by this guy
2450 $user = intval( $current->getUser() );
2451 $user_text = $dbw->addQuotes( $current->getUserText() );
2452 $s = $dbw->selectRow( 'revision',
2453 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2454 array( 'rev_page' => $current->getPage(),
2455 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2457 array( 'USE INDEX' => 'page_timestamp',
2458 'ORDER BY' => 'rev_timestamp DESC' )
2460 if( $s === false ) {
2461 # No one else ever edited this page
2462 return array(array('cantrollback'));
2463 } else if( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
2464 # Only admins can see this text
2465 return array(array('notvisiblerev'));
2469 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2470 # Mark all reverted edits as bot
2473 if ( $wgUseRCPatrol ) {
2474 # Mark all reverted edits as patrolled
2475 $set['rc_patrolled'] = 1;
2479 $dbw->update( 'recentchanges', $set,
2481 'rc_cur_id' => $current->getPage(),
2482 'rc_user_text' => $current->getUserText(),
2483 "rc_timestamp > '{$s->rev_timestamp}'",
2488 # Generate the edit summary if necessary
2489 $target = Revision
::newFromId( $s->rev_id
);
2490 if( empty( $summary ) )
2493 $summary = wfMsgForContent( 'revertpage',
2494 $target->getUserText(), $from,
2495 $s->rev_id
, $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2496 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2501 $flags = EDIT_UPDATE
;
2503 if ($wgUser->isAllowed('minoredit'))
2504 $flags |
= EDIT_MINOR
;
2506 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2507 $flags |
= EDIT_FORCE_BOT
;
2508 $this->doEdit( $target->getText(), $summary, $flags );
2510 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2512 $resultDetails = array(
2513 'summary' => $summary,
2514 'current' => $current,
2515 'target' => $target,
2521 * User interface for rollback operations
2523 function rollback() {
2524 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2527 $result = $this->doRollback(
2528 $wgRequest->getVal( 'from' ),
2529 $wgRequest->getText( 'summary' ),
2530 $wgRequest->getVal( 'token' ),
2531 $wgRequest->getBool( 'bot' ),
2535 if( in_array( array( 'blocked' ), $result ) ) {
2536 $wgOut->blockedPage();
2539 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2540 $wgOut->rateLimited();
2543 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ){
2544 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2545 $errArray = $result[0];
2546 $errMsg = array_shift( $errArray );
2547 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2548 if( isset( $details['current'] ) ){
2549 $current = $details['current'];
2550 if( $current->getComment() != '' ) {
2551 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2556 # Display permissions errors before read-only message -- there's no
2557 # point in misleading the user into thinking the inability to rollback
2558 # is only temporary.
2559 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2560 # array_diff is completely broken for arrays of arrays, sigh. Re-
2561 # move any 'readonlytext' error manually.
2563 foreach( $result as $error ) {
2564 if( $error != array( 'readonlytext' ) ) {
2568 $wgOut->showPermissionsErrorPage( $out );
2571 if( $result == array( array('readonlytext') ) ) {
2572 $wgOut->readOnlyPage();
2576 $current = $details['current'];
2577 $target = $details['target'];
2578 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2579 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2580 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2581 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2582 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2583 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2584 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2585 $wgOut->returnToMain( false, $this->mTitle
);
2590 * Do standard deferred updates after page view
2593 function viewUpdates() {
2594 global $wgDeferredUpdateList;
2596 if ( 0 != $this->getID() ) {
2597 global $wgDisableCounters;
2598 if( !$wgDisableCounters ) {
2599 Article
::incViewCount( $this->getID() );
2600 $u = new SiteStatsUpdate( 1, 0, 0 );
2601 array_push( $wgDeferredUpdateList, $u );
2605 # Update newtalk / watchlist notification status
2607 $wgUser->clearNotification( $this->mTitle
);
2611 * Prepare text which is about to be saved.
2612 * Returns a stdclass with source, pst and output members
2614 function prepareTextForEdit( $text, $revid=null ) {
2615 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2617 return $this->mPreparedEdit
;
2620 $edit = (object)array();
2621 $edit->revid
= $revid;
2622 $edit->newText
= $text;
2623 $edit->pst
= $this->preSaveTransform( $text );
2624 $options = new ParserOptions
;
2625 $options->setTidy( true );
2626 $options->enableLimitReport();
2627 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2628 $edit->oldText
= $this->getContent();
2629 $this->mPreparedEdit
= $edit;
2634 * Do standard deferred updates after page edit.
2635 * Update links tables, site stats, search index and message cache.
2636 * Every 100th edit, prune the recent changes table.
2639 * @param $text New text of the article
2640 * @param $summary Edit summary
2641 * @param $minoredit Minor edit
2642 * @param $timestamp_of_pagechange Timestamp associated with the page change
2643 * @param $newid rev_id value of the new revision
2644 * @param $changed Whether or not the content actually changed
2646 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2647 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2649 wfProfileIn( __METHOD__
);
2652 # Be careful not to double-PST: $text is usually already PST-ed once
2653 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2654 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2655 $editInfo = $this->prepareTextForEdit( $text, $newid );
2657 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2658 $editInfo = $this->mPreparedEdit
;
2661 # Save it to the parser cache
2662 if ( $wgEnableParserCache ) {
2663 $parserCache = ParserCache
::singleton();
2664 $parserCache->save( $editInfo->output
, $this, $wgUser );
2667 # Update the links tables
2668 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2671 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2672 if ( 0 == mt_rand( 0, 99 ) ) {
2673 // Flush old entries from the `recentchanges` table; we do this on
2674 // random requests so as to avoid an increase in writes for no good reason
2676 $dbw = wfGetDB( DB_MASTER
);
2677 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2678 $recentchanges = $dbw->tableName( 'recentchanges' );
2679 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2680 $dbw->query( $sql );
2684 $id = $this->getID();
2685 $title = $this->mTitle
->getPrefixedDBkey();
2686 $shortTitle = $this->mTitle
->getDBkey();
2689 wfProfileOut( __METHOD__
);
2693 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2694 array_push( $wgDeferredUpdateList, $u );
2695 $u = new SearchUpdate( $id, $title, $text );
2696 array_push( $wgDeferredUpdateList, $u );
2698 # If this is another user's talk page, update newtalk
2699 # Don't do this if $changed = false otherwise some idiot can null-edit a
2700 # load of user talk pages and piss people off, nor if it's a minor edit
2701 # by a properly-flagged bot.
2702 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2703 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2704 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2705 $other = User
::newFromName( $shortTitle );
2706 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2707 // An anonymous user
2708 $other = new User();
2709 $other->setName( $shortTitle );
2712 $other->setNewtalk( true );
2717 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2718 $wgMessageCache->replace( $shortTitle, $text );
2721 wfProfileOut( __METHOD__
);
2725 * Perform article updates on a special page creation.
2727 * @param Revision $rev
2729 * @todo This is a shitty interface function. Kill it and replace the
2730 * other shitty functions like editUpdates and such so it's not needed
2733 function createUpdates( $rev ) {
2734 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2735 $this->mTotalAdjustment
= 1;
2736 $this->editUpdates( $rev->getText(), $rev->getComment(),
2737 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2741 * Generate the navigation links when browsing through an article revisions
2742 * It shows the information as:
2743 * Revision as of \<date\>; view current revision
2744 * \<- Previous version | Next Version -\>
2747 * @param string $oldid Revision ID of this article revision
2749 function setOldSubtitle( $oldid=0 ) {
2750 global $wgLang, $wgOut, $wgUser;
2752 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2756 $revision = Revision
::newFromId( $oldid );
2758 $current = ( $oldid == $this->mLatest
);
2759 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2760 $sk = $wgUser->getSkin();
2762 ?
wfMsg( 'currentrevisionlink' )
2763 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2766 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2767 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2769 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2770 : wfMsg( 'previousrevision' );
2772 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2774 $nextlink = $current
2775 ?
wfMsg( 'nextrevision' )
2776 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2777 $nextdiff = $current
2779 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2782 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2783 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
2784 if( $revision->isCurrent() ) {
2785 // We don't handle top deleted edits too well
2786 $cdel = wfMsgHtml('rev-delundel');
2787 } else if( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
2788 // If revision was hidden from sysops
2789 $cdel = wfMsgHtml('rev-delundel');
2791 $cdel = $sk->makeKnownLinkObj( $revdel,
2792 wfMsgHtml('rev-delundel'),
2793 'target=' . urlencode( $this->mTitle
->getPrefixedDbkey() ) .
2794 '&oldid=' . urlencode( $oldid ) );
2795 // Bolden oversighted content
2796 if( $revision->isDeleted( Revision
::DELETED_RESTRICTED
) )
2797 $cdel = "<strong>$cdel</strong>";
2799 $cdel = "(<small>$cdel</small>) ";
2801 # Show user links if allowed to see them. Normally they
2802 # are hidden regardless, but since we can already see the text here...
2803 $userlinks = $sk->revUserTools( $revision, false );
2805 $m = wfMsg( 'revision-info-current' );
2806 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2807 ?
'revision-info-current'
2810 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2812 "\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";
2813 $wgOut->setSubtitle( $r );
2817 * This function is called right before saving the wikitext,
2818 * so we can do things like signatures and links-in-context.
2820 * @param string $text
2822 function preSaveTransform( $text ) {
2823 global $wgParser, $wgUser;
2824 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2827 /* Caching functions */
2830 * checkLastModified returns true if it has taken care of all
2831 * output to the client that is necessary for this request.
2832 * (that is, it has sent a cached version of the page)
2834 function tryFileCache() {
2835 static $called = false;
2837 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2841 if($this->isFileCacheable()) {
2842 $touched = $this->mTouched
;
2843 $cache = new HTMLFileCache( $this->mTitle
);
2844 if($cache->isFileCacheGood( $touched )) {
2845 wfDebug( "Article::tryFileCache(): about to load file\n" );
2846 $cache->loadFromFileCache();
2849 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2850 ob_start( array(&$cache, 'saveToFileCache' ) );
2853 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2858 * Check if the page can be cached
2861 function isFileCacheable() {
2862 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2863 $action = $wgRequest->getVal( 'action' );
2864 $oldid = $wgRequest->getVal( 'oldid' );
2865 $diff = $wgRequest->getVal( 'diff' );
2866 $redirect = $wgRequest->getVal( 'redirect' );
2867 $printable = $wgRequest->getVal( 'printable' );
2868 $page = $wgRequest->getVal( 'page' );
2870 //check for non-standard user language; this covers uselang,
2871 //and extensions for auto-detecting user language.
2872 $ulang = $wgLang->getCode();
2873 $clang = $wgContLang->getCode();
2875 $cacheable = $wgUseFileCache
2876 && (!$wgShowIPinHeader)
2877 && ($this->getID() != 0)
2878 && ($wgUser->isAnon())
2879 && (!$wgUser->getNewtalk())
2880 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2881 && (empty( $action ) ||
$action == 'view')
2884 && (!isset($redirect))
2885 && (!isset($printable))
2887 && (!$this->mRedirectedFrom
)
2888 && ($ulang === $clang);
2891 //extension may have reason to disable file caching on some pages.
2892 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2899 * Loads page_touched and returns a value indicating if it should be used
2902 function checkTouched() {
2903 if( !$this->mDataLoaded
) {
2904 $this->loadPageData();
2906 return !$this->mIsRedirect
;
2910 * Get the page_touched field
2912 function getTouched() {
2913 # Ensure that page data has been loaded
2914 if( !$this->mDataLoaded
) {
2915 $this->loadPageData();
2917 return $this->mTouched
;
2921 * Get the page_latest field
2923 function getLatest() {
2924 if ( !$this->mDataLoaded
) {
2925 $this->loadPageData();
2927 return $this->mLatest
;
2931 * Edit an article without doing all that other stuff
2932 * The article must already exist; link tables etc
2933 * are not updated, caches are not flushed.
2935 * @param string $text text submitted
2936 * @param string $comment comment submitted
2937 * @param bool $minor whereas it's a minor modification
2939 function quickEdit( $text, $comment = '', $minor = 0 ) {
2940 wfProfileIn( __METHOD__
);
2942 $dbw = wfGetDB( DB_MASTER
);
2944 $revision = new Revision( array(
2945 'page' => $this->getId(),
2947 'comment' => $comment,
2948 'minor_edit' => $minor ?
1 : 0,
2950 $revision->insertOn( $dbw );
2951 $this->updateRevisionOn( $dbw, $revision );
2954 wfProfileOut( __METHOD__
);
2958 * Used to increment the view counter
2961 * @param integer $id article id
2963 function incViewCount( $id ) {
2964 $id = intval( $id );
2965 global $wgHitcounterUpdateFreq, $wgDBtype;
2967 $dbw = wfGetDB( DB_MASTER
);
2968 $pageTable = $dbw->tableName( 'page' );
2969 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2970 $acchitsTable = $dbw->tableName( 'acchits' );
2972 if( $wgHitcounterUpdateFreq <= 1 ) {
2973 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2977 # Not important enough to warrant an error page in case of failure
2978 $oldignore = $dbw->ignoreErrors( true );
2980 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2982 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2983 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2984 # Most of the time (or on SQL errors), skip row count check
2985 $dbw->ignoreErrors( $oldignore );
2989 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2990 $row = $dbw->fetchObject( $res );
2991 $rown = intval( $row->n
);
2992 if( $rown >= $wgHitcounterUpdateFreq ){
2993 wfProfileIn( 'Article::incViewCount-collect' );
2994 $old_user_abort = ignore_user_abort( true );
2996 if ($wgDBtype == 'mysql')
2997 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2998 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2999 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3000 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3002 $dbw->query("DELETE FROM $hitcounterTable");
3003 if ($wgDBtype == 'mysql') {
3004 $dbw->query('UNLOCK TABLES');
3005 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3006 'WHERE page_id = hc_id');
3009 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3010 "FROM $acchitsTable WHERE page_id = hc_id");
3012 $dbw->query("DROP TABLE $acchitsTable");
3014 ignore_user_abort( $old_user_abort );
3015 wfProfileOut( 'Article::incViewCount-collect' );
3017 $dbw->ignoreErrors( $oldignore );
3021 * The onArticle*() functions are supposed to be a kind of hooks
3022 * which should be called whenever any of the specified actions
3025 * This is a good place to put code to clear caches, for instance.
3027 * This is called on page move and undelete, as well as edit
3029 * @param $title_obj a title object
3032 static function onArticleCreate($title) {
3033 # The talk page isn't in the regular link tables, so we need to update manually:
3034 if ( $title->isTalkPage() ) {
3035 $other = $title->getSubjectPage();
3037 $other = $title->getTalkPage();
3039 $other->invalidateCache();
3040 $other->purgeSquid();
3042 $title->touchLinks();
3043 $title->purgeSquid();
3044 $title->deleteTitleProtection();
3047 static function onArticleDelete( $title ) {
3048 global $wgUseFileCache, $wgMessageCache;
3050 // Update existence markers on article/talk tabs...
3051 if( $title->isTalkPage() ) {
3052 $other = $title->getSubjectPage();
3054 $other = $title->getTalkPage();
3056 $other->invalidateCache();
3057 $other->purgeSquid();
3059 $title->touchLinks();
3060 $title->purgeSquid();
3063 if ( $wgUseFileCache ) {
3064 $cm = new HTMLFileCache( $title );
3065 @unlink
( $cm->fileCacheName() );
3068 if( $title->getNamespace() == NS_MEDIAWIKI
) {
3069 $wgMessageCache->replace( $title->getDBkey(), false );
3071 if( $title->getNamespace() == NS_IMAGE
) {
3072 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3073 $update->doUpdate();
3078 * Purge caches on page update etc
3080 static function onArticleEdit( $title ) {
3081 global $wgDeferredUpdateList, $wgUseFileCache;
3083 // Invalidate caches of articles which include this page
3084 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3086 // Invalidate the caches of all pages which redirect here
3087 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3089 # Purge squid for this page only
3090 $title->purgeSquid();
3093 if ( $wgUseFileCache ) {
3094 $cm = new HTMLFileCache( $title );
3095 @unlink
( $cm->fileCacheName() );
3102 * Overriden by ImagePage class, only present here to avoid a fatal error
3103 * Called for ?action=revert
3105 public function revert(){
3107 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3111 * Info about this page
3112 * Called for ?action=info when $wgAllowPageInfo is on.
3117 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3119 if ( !$wgAllowPageInfo ) {
3120 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3124 $page = $this->mTitle
->getSubjectPage();
3126 $wgOut->setPagetitle( $page->getPrefixedText() );
3127 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3128 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3130 if( !$this->mTitle
->exists() ) {
3131 $wgOut->addHtml( '<div class="noarticletext">' );
3132 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3133 // This doesn't quite make sense; the user is asking for
3134 // information about the _page_, not the message... -- RC
3135 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3137 $msg = $wgUser->isLoggedIn()
3139 : 'noarticletextanon';
3140 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3142 $wgOut->addHtml( '</div>' );
3144 $dbr = wfGetDB( DB_SLAVE
);
3146 'wl_title' => $page->getDBkey(),
3147 'wl_namespace' => $page->getNamespace() );
3148 $numwatchers = $dbr->selectField(
3153 $this->getSelectOptions() );
3155 $pageInfo = $this->pageCountInfo( $page );
3156 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3158 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3159 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3161 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3163 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3165 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3167 $wgOut->addHTML( '</ul>' );
3173 * Return the total number of edits and number of unique editors
3174 * on a given page. If page does not exist, returns false.
3176 * @param Title $title
3180 function pageCountInfo( $title ) {
3181 $id = $title->getArticleId();
3186 $dbr = wfGetDB( DB_SLAVE
);
3188 $rev_clause = array( 'rev_page' => $id );
3190 $edits = $dbr->selectField(
3195 $this->getSelectOptions() );
3197 $authors = $dbr->selectField(
3199 'COUNT(DISTINCT rev_user_text)',
3202 $this->getSelectOptions() );
3204 return array( 'edits' => $edits, 'authors' => $authors );
3208 * Return a list of templates used by this article.
3209 * Uses the templatelinks table
3211 * @return array Array of Title objects
3213 function getUsedTemplates() {
3215 $id = $this->mTitle
->getArticleID();
3220 $dbr = wfGetDB( DB_SLAVE
);
3221 $res = $dbr->select( array( 'templatelinks' ),
3222 array( 'tl_namespace', 'tl_title' ),
3223 array( 'tl_from' => $id ),
3224 'Article:getUsedTemplates' );
3225 if ( false !== $res ) {
3226 if ( $dbr->numRows( $res ) ) {
3227 while ( $row = $dbr->fetchObject( $res ) ) {
3228 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3232 $dbr->freeResult( $res );
3237 * Returns a list of hidden categories this page is a member of.
3238 * Uses the page_props and categorylinks tables.
3240 * @return array Array of Title objects
3242 function getHiddenCategories() {
3244 $id = $this->mTitle
->getArticleID();
3249 $dbr = wfGetDB( DB_SLAVE
);
3250 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3252 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3253 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to'),
3254 'Article:getHiddenCategories' );
3255 if ( false !== $res ) {
3256 if ( $dbr->numRows( $res ) ) {
3257 while ( $row = $dbr->fetchObject( $res ) ) {
3258 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3262 $dbr->freeResult( $res );
3267 * Return an auto-generated summary if the text provided is a redirect.
3269 * @param string $text The wikitext to check
3270 * @return string '' or an appropriate summary
3272 public static function getRedirectAutosummary( $text ) {
3273 $rt = Title
::newFromRedirect( $text );
3274 if( is_object( $rt ) )
3275 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3281 * Return an auto-generated summary if the new text is much shorter than
3284 * @param string $oldtext The previous text of the page
3285 * @param string $text The submitted text of the page
3286 * @return string An appropriate autosummary, or an empty string.
3288 public static function getBlankingAutosummary( $oldtext, $text ) {
3289 if ($oldtext!='' && $text=='') {
3290 return wfMsgForContent('autosumm-blank');
3291 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3292 #Removing more than 90% of the article
3294 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3295 return wfMsgForContent('autosumm-replace', $truncatedtext);
3302 * Return an applicable autosummary if one exists for the given edit.
3303 * @param string $oldtext The previous text of the page.
3304 * @param string $newtext The submitted text of the page.
3305 * @param bitmask $flags A bitmask of flags submitted for the edit.
3306 * @return string An appropriate autosummary, or an empty string.
3308 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3310 # This code is UGLY UGLY UGLY.
3311 # Somebody PLEASE come up with a more elegant way to do it.
3313 #Redirect autosummaries
3314 $summary = self
::getRedirectAutosummary( $newtext );
3319 #Blanking autosummaries
3320 if (!($flags & EDIT_NEW
))
3321 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3326 #New page autosummaries
3327 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3328 #If they're making a new article, give its text, truncated, in the summary.
3330 $truncatedtext = $wgContLang->truncate(
3331 str_replace("\n", ' ', $newtext),
3332 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3334 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3344 * Add the primary page-view wikitext to the output buffer
3345 * Saves the text into the parser cache if possible.
3346 * Updates templatelinks if it is out of date.
3348 * @param string $text
3349 * @param bool $cache
3351 public function outputWikiText( $text, $cache = true ) {
3352 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3354 $popts = $wgOut->parserOptions();
3355 $popts->setTidy(true);
3356 $popts->enableLimitReport();
3357 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3358 $popts, true, true, $this->getRevIdFetched() );
3359 $popts->setTidy(false);
3360 $popts->enableLimitReport( false );
3361 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3362 $parserCache = ParserCache
::singleton();
3363 $parserCache->save( $parserOutput, $this, $wgUser );
3366 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3367 // templatelinks table may have become out of sync,
3368 // especially if using variable-based transclusions.
3369 // For paranoia, check if things have changed and if
3370 // so apply updates to the database. This will ensure
3371 // that cascaded protections apply as soon as the changes
3374 # Get templates from templatelinks
3375 $id = $this->mTitle
->getArticleID();
3377 $tlTemplates = array();
3379 $dbr = wfGetDB( DB_SLAVE
);
3380 $res = $dbr->select( array( 'templatelinks' ),
3381 array( 'tl_namespace', 'tl_title' ),
3382 array( 'tl_from' => $id ),
3383 'Article:getUsedTemplates' );
3387 if ( false !== $res ) {
3388 if ( $dbr->numRows( $res ) ) {
3389 while ( $row = $dbr->fetchObject( $res ) ) {
3390 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3395 # Get templates from parser output.
3396 $poTemplates_allns = $parserOutput->getTemplates();
3398 $poTemplates = array ();
3399 foreach ( $poTemplates_allns as $ns_templates ) {
3400 $poTemplates = array_merge( $poTemplates, $ns_templates );
3404 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3406 if ( count( $templates_diff ) > 0 ) {
3407 # Whee, link updates time.
3408 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3410 $dbw = wfGetDb( DB_MASTER
);
3419 $wgOut->addParserOutput( $parserOutput );
3423 * Update all the appropriate counts in the category table, given that
3424 * we've added the categories $added and deleted the categories $deleted.
3426 * @param $added array The names of categories that were added
3427 * @param $deleted array The names of categories that were deleted
3430 public function updateCategoryCounts( $added, $deleted ) {
3431 $ns = $this->mTitle
->getNamespace();
3432 $dbw = wfGetDB( DB_MASTER
);
3434 # First make sure the rows exist. If one of the "deleted" ones didn't
3435 # exist, we might legitimately not create it, but it's simpler to just
3436 # create it and then give it a negative value, since the value is bogus
3439 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3440 $insertCats = array_merge( $added, $deleted );
3441 if( !$insertCats ) {
3442 # Okay, nothing to do
3445 $insertRows = array();
3446 foreach( $insertCats as $cat ) {
3447 $insertRows[] = array( 'cat_title' => $cat );
3449 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3451 $addFields = array( 'cat_pages = cat_pages + 1' );
3452 $removeFields = array( 'cat_pages = cat_pages - 1' );
3453 if( $ns == NS_CATEGORY
) {
3454 $addFields[] = 'cat_subcats = cat_subcats + 1';
3455 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3456 } elseif( $ns == NS_IMAGE
) {
3457 $addFields[] = 'cat_files = cat_files + 1';
3458 $removeFields[] = 'cat_files = cat_files - 1';
3465 array( 'cat_title' => $added ),
3473 array( 'cat_title' => $deleted ),