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; //!<
40 * Constants used by internal components to get rollback results
42 const SUCCESS
= 0; // Operation successful
43 const PERM_DENIED
= 1; // Permission denied
44 const BLOCKED
= 2; // User has been blocked
45 const READONLY
= 3; // Wiki is in read-only mode
46 const BAD_TOKEN
= 4; // Invalid token specified
47 const BAD_TITLE
= 5; // $this is not a valid Article
48 const ALREADY_ROLLED
= 6; // Someone else already rolled this back. $from and $summary will be set
49 const ONLY_AUTHOR
= 7; // User is the only author of the page
52 * Constructor and clear the article
53 * @param $title Reference to a Title object.
54 * @param $oldId Integer revision ID, null to fetch from request, zero for current
56 function __construct( &$title, $oldId = null ) {
57 $this->mTitle
=& $title;
58 $this->mOldId
= $oldId;
63 * Tell the page view functions that this view was redirected
64 * from another page on the wiki.
65 * @param $from Title object.
67 function setRedirectedFrom( $from ) {
68 $this->mRedirectedFrom
= $from;
72 * @return mixed false, Title of in-wiki target, or string with URL
74 function followRedirect() {
75 $text = $this->getContent();
76 $rt = Title
::newFromRedirect( $text );
78 # process if title object is valid and not special:userlogout
80 if( $rt->getInterwiki() != '' ) {
81 if( $rt->isLocal() ) {
82 // Offsite wikis need an HTTP redirect.
84 // This can be hard to reverse and may produce loops,
85 // so they may be disabled in the site configuration.
87 $source = $this->mTitle
->getFullURL( 'redirect=no' );
88 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
91 if( $rt->getNamespace() == NS_SPECIAL
) {
92 // Gotta handle redirects to special pages differently:
93 // Fill the HTTP response "Location" header and ignore
94 // the rest of the page we're on.
96 // This can be hard to reverse, so they may be disabled.
98 if( $rt->isSpecial( 'Userlogout' ) ) {
101 return $rt->getFullURL();
108 // No or invalid redirect
113 * get the title object of the article
115 function getTitle() {
116 return $this->mTitle
;
124 $this->mDataLoaded
= false;
125 $this->mContentLoaded
= false;
127 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
128 $this->mRedirectedFrom
= null; # Title object if set
130 $this->mTimestamp
= $this->mComment
= '';
131 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
132 $this->mTouched
= '19700101000000';
133 $this->mForUpdate
= false;
134 $this->mIsRedirect
= false;
135 $this->mRevIdFetched
= 0;
136 $this->mRedirectUrl
= false;
137 $this->mLatest
= false;
141 * Note that getContent/loadContent do not follow redirects anymore.
142 * If you need to fetch redirectable content easily, try
143 * the shortcut in Article::followContent()
145 * @todo There are still side-effects in this!
146 * In general, you should use the Revision class, not Article,
147 * to fetch text for purposes other than page views.
149 * @return Return the text of this revision
151 function getContent() {
152 global $wgUser, $wgOut;
154 wfProfileIn( __METHOD__
);
156 if ( 0 == $this->getID() ) {
157 wfProfileOut( __METHOD__
);
158 $wgOut->setRobotpolicy( 'noindex,nofollow' );
160 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
161 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
163 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
166 return "<div class='noarticletext'>$ret</div>";
168 $this->loadContent();
169 wfProfileOut( __METHOD__
);
170 return $this->mContent
;
175 * This function returns the text of a section, specified by a number ($section).
176 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
177 * the first section before any such heading (section 0).
179 * If a section contains subsections, these are also returned.
181 * @param $text String: text to look in
182 * @param $section Integer: section number
183 * @return string text of the requested section
186 function getSection($text,$section) {
188 return $wgParser->getSection( $text, $section );
192 * @return int The oldid of the article that is to be shown, 0 for the
195 function getOldID() {
196 if ( is_null( $this->mOldId
) ) {
197 $this->mOldId
= $this->getOldIDFromRequest();
199 return $this->mOldId
;
203 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
205 * @return int The old id for the request
207 function getOldIDFromRequest() {
209 $this->mRedirectUrl
= false;
210 $oldid = $wgRequest->getVal( 'oldid' );
211 if ( isset( $oldid ) ) {
212 $oldid = intval( $oldid );
213 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
214 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
218 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
220 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
221 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
239 * Load the revision (including text) into this object
241 function loadContent() {
242 if ( $this->mContentLoaded
) return;
245 $oldid = $this->getOldID();
247 # Pre-fill content with error message so that if something
248 # fails we'll have something telling us what we intended.
249 $this->mOldId
= $oldid;
250 $this->fetchContent( $oldid );
255 * Fetch a page record with the given conditions
256 * @param Database $dbr
257 * @param array $conditions
260 function pageData( $dbr, $conditions ) {
274 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
275 $row = $dbr->selectRow(
281 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
286 * @param Database $dbr
287 * @param Title $title
289 function pageDataFromTitle( $dbr, $title ) {
290 return $this->pageData( $dbr, array(
291 'page_namespace' => $title->getNamespace(),
292 'page_title' => $title->getDBkey() ) );
296 * @param Database $dbr
299 function pageDataFromId( $dbr, $id ) {
300 return $this->pageData( $dbr, array( 'page_id' => $id ) );
304 * Set the general counter, title etc data loaded from
307 * @param object $data
310 function loadPageData( $data = 'fromdb' ) {
311 if ( $data === 'fromdb' ) {
312 $dbr = $this->getDB();
313 $data = $this->pageDataFromId( $dbr, $this->getId() );
316 $lc =& LinkCache
::singleton();
318 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
320 $this->mTitle
->mArticleID
= $data->page_id
;
322 # Old-fashioned restrictions.
323 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
325 $this->mCounter
= $data->page_counter
;
326 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
327 $this->mIsRedirect
= $data->page_is_redirect
;
328 $this->mLatest
= $data->page_latest
;
330 if ( is_object( $this->mTitle
) ) {
331 $lc->addBadLinkObj( $this->mTitle
);
333 $this->mTitle
->mArticleID
= 0;
336 $this->mDataLoaded
= true;
340 * Get text of an article from database
341 * Does *NOT* follow redirects.
342 * @param int $oldid 0 for whatever the latest revision is
345 function fetchContent( $oldid = 0 ) {
346 if ( $this->mContentLoaded
) {
347 return $this->mContent
;
350 $dbr = $this->getDB();
352 # Pre-fill content with error message so that if something
353 # fails we'll have something telling us what we intended.
354 $t = $this->mTitle
->getPrefixedText();
356 $t .= ',oldid='.$oldid;
358 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
361 $revision = Revision
::newFromId( $oldid );
362 if( is_null( $revision ) ) {
363 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
366 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
368 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
371 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
372 $this->loadPageData( $data );
374 if( !$this->mDataLoaded
) {
375 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
377 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
380 $this->loadPageData( $data );
382 $revision = Revision
::newFromId( $this->mLatest
);
383 if( is_null( $revision ) ) {
384 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
389 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
390 // We should instead work with the Revision object when we need it...
391 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
392 //$this->mContent = $revision->getText();
394 $this->mUser
= $revision->getUser();
395 $this->mUserText
= $revision->getUserText();
396 $this->mComment
= $revision->getComment();
397 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
399 $this->mRevIdFetched
= $revision->getID();
400 $this->mContentLoaded
= true;
401 $this->mRevision
=& $revision;
403 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
405 return $this->mContent
;
409 * Read/write accessor to select FOR UPDATE
411 * @param $x Mixed: FIXME
413 function forUpdate( $x = NULL ) {
414 return wfSetVar( $this->mForUpdate
, $x );
418 * Get the database which should be used for reads
423 return wfGetDB( DB_MASTER
);
427 * Get options for all SELECT statements
429 * @param $options Array: an optional options array which'll be appended to
431 * @return Array: options
433 function getSelectOptions( $options = '' ) {
434 if ( $this->mForUpdate
) {
435 if ( is_array( $options ) ) {
436 $options[] = 'FOR UPDATE';
438 $options = 'FOR UPDATE';
445 * @return int Page ID
448 if( $this->mTitle
) {
449 return $this->mTitle
->getArticleID();
456 * @return bool Whether or not the page exists in the database
459 return $this->getId() != 0;
463 * @return int The view count for the page
465 function getCount() {
466 if ( -1 == $this->mCounter
) {
467 $id = $this->getID();
471 $dbr = wfGetDB( DB_SLAVE
);
472 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
473 'Article::getCount', $this->getSelectOptions() );
476 return $this->mCounter
;
480 * Determine whether a page would be suitable for being counted as an
481 * article in the site_stats table based on the title & its content
483 * @param $text String: text to analyze
486 function isCountable( $text ) {
487 global $wgUseCommaCount;
489 $token = $wgUseCommaCount ?
',' : '[[';
491 $this->mTitle
->isContentPage()
492 && !$this->isRedirect( $text )
493 && in_string( $token, $text );
497 * Tests if the article text represents a redirect
499 * @param $text String: FIXME
502 function isRedirect( $text = false ) {
503 if ( $text === false ) {
504 $this->loadContent();
505 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
507 $titleObj = Title
::newFromRedirect( $text );
509 return $titleObj !== NULL;
513 * Returns true if the currently-referenced revision is the current edit
514 * to this page (and it exists).
517 function isCurrent() {
518 # If no oldid, this is the current version.
519 if ($this->getOldID() == 0)
522 return $this->exists() &&
523 isset( $this->mRevision
) &&
524 $this->mRevision
->isCurrent();
528 * Loads everything except the text
529 * This isn't necessary for all uses, so it's only done if needed.
532 function loadLastEdit() {
533 if ( -1 != $this->mUser
)
536 # New or non-existent articles have no user information
537 $id = $this->getID();
538 if ( 0 == $id ) return;
540 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
541 if( !is_null( $this->mLastRevision
) ) {
542 $this->mUser
= $this->mLastRevision
->getUser();
543 $this->mUserText
= $this->mLastRevision
->getUserText();
544 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
545 $this->mComment
= $this->mLastRevision
->getComment();
546 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
547 $this->mRevIdFetched
= $this->mLastRevision
->getID();
551 function getTimestamp() {
552 // Check if the field has been filled by ParserCache::get()
553 if ( !$this->mTimestamp
) {
554 $this->loadLastEdit();
556 return wfTimestamp(TS_MW
, $this->mTimestamp
);
560 $this->loadLastEdit();
564 function getUserText() {
565 $this->loadLastEdit();
566 return $this->mUserText
;
569 function getComment() {
570 $this->loadLastEdit();
571 return $this->mComment
;
574 function getMinorEdit() {
575 $this->loadLastEdit();
576 return $this->mMinorEdit
;
579 function getRevIdFetched() {
580 $this->loadLastEdit();
581 return $this->mRevIdFetched
;
585 * @todo Document, fixme $offset never used.
586 * @param $limit Integer: default 0.
587 * @param $offset Integer: default 0.
589 function getContributors($limit = 0, $offset = 0) {
590 # XXX: this is expensive; cache this info somewhere.
593 $dbr = wfGetDB( DB_SLAVE
);
594 $revTable = $dbr->tableName( 'revision' );
595 $userTable = $dbr->tableName( 'user' );
596 $user = $this->getUser();
597 $pageId = $this->getId();
599 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
600 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
601 WHERE rev_page = $pageId
602 AND rev_user != $user
603 GROUP BY rev_user, rev_user_text, user_real_name
604 ORDER BY timestamp DESC";
606 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
607 $sql .= ' '. $this->getSelectOptions();
609 $res = $dbr->query($sql, __METHOD__
);
611 while ( $line = $dbr->fetchObject( $res ) ) {
612 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
615 $dbr->freeResult($res);
620 * This is the default action of the script: just view the page of
624 global $wgUser, $wgOut, $wgRequest, $wgContLang;
625 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
626 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
627 $sk = $wgUser->getSkin();
629 wfProfileIn( __METHOD__
);
631 $parserCache =& ParserCache
::singleton();
632 $ns = $this->mTitle
->getNamespace(); # shortcut
634 # Get variables from query string
635 $oldid = $this->getOldID();
637 # getOldID may want us to redirect somewhere else
638 if ( $this->mRedirectUrl
) {
639 $wgOut->redirect( $this->mRedirectUrl
);
640 wfProfileOut( __METHOD__
);
644 $diff = $wgRequest->getVal( 'diff' );
645 $rcid = $wgRequest->getVal( 'rcid' );
646 $rdfrom = $wgRequest->getVal( 'rdfrom' );
647 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
649 $wgOut->setArticleFlag( true );
651 # Discourage indexing of printable versions, but encourage following
652 if( $wgOut->isPrintable() ) {
653 $policy = 'noindex,follow';
654 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
655 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
656 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
657 # Honour customised robot policies for this namespace
658 $policy = $wgNamespaceRobotPolicies[$ns];
660 # Default to encourage indexing and following links
661 $policy = 'index,follow';
663 $wgOut->setRobotPolicy( $policy );
665 # If we got diff and oldid in the query, we want to see a
666 # diff page instead of the article.
668 if ( !is_null( $diff ) ) {
669 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
671 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
672 // DifferenceEngine directly fetched the revision:
673 $this->mRevIdFetched
= $de->mNewid
;
674 $de->showDiffPage( $diffOnly );
676 // Needed to get the page's current revision
677 $this->loadPageData();
678 if( $diff == 0 ||
$diff == $this->mLatest
) {
679 # Run view updates for current revision only
680 $this->viewUpdates();
682 wfProfileOut( __METHOD__
);
686 if ( empty( $oldid ) && $this->checkTouched() ) {
687 $wgOut->setETag($parserCache->getETag($this, $wgUser));
689 if( $wgOut->checkLastModified( $this->mTouched
) ){
690 wfProfileOut( __METHOD__
);
692 } else if ( $this->tryFileCache() ) {
693 # tell wgOut that output is taken care of
695 $this->viewUpdates();
696 wfProfileOut( __METHOD__
);
701 # Should the parser cache be used?
702 $pcache = $wgEnableParserCache
703 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
706 && !$this->mTitle
->isCssOrJsPage()
707 && !$this->mTitle
->isCssJsSubpage();
708 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
709 if ( $wgUser->getOption( 'stubthreshold' ) ) {
710 wfIncrStats( 'pcache_miss_stub' );
713 $wasRedirected = false;
714 if ( isset( $this->mRedirectedFrom
) ) {
715 // This is an internally redirected page view.
716 // We'll need a backlink to the source page for navigation.
717 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
718 $sk = $wgUser->getSkin();
719 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
720 $s = wfMsg( 'redirectedfrom', $redir );
721 $wgOut->setSubtitle( $s );
723 // Set the fragment if one was specified in the redirect
724 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
725 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
726 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
728 $wasRedirected = true;
730 } elseif ( !empty( $rdfrom ) ) {
731 // This is an externally redirected view, from some other wiki.
732 // If it was reported from a trusted site, supply a backlink.
733 global $wgRedirectSources;
734 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
735 $sk = $wgUser->getSkin();
736 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
737 $s = wfMsg( 'redirectedfrom', $redir );
738 $wgOut->setSubtitle( $s );
739 $wasRedirected = true;
743 if ( $this->mTitle
->isProtected() ) {
744 $editrestr = $this->mTitle
->getRestrictions('edit');
745 $this->addProtectionNotice( $editrestr );
749 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
751 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
752 // Ensure that UI elements requiring revision ID have
753 // the correct version information.
754 $wgOut->setRevisionId( $this->mLatest
);
758 if ( !$outputDone ) {
759 $text = $this->getContent();
760 if ( $text === false ) {
761 # Failed to load, replace text with error message
762 $t = $this->mTitle
->getPrefixedText();
764 $t .= ',oldid='.$oldid;
765 $text = wfMsg( 'missingarticle', $t );
767 $text = wfMsg( 'noarticletext', $t );
771 # Another whitelist check in case oldid is altering the title
772 if ( !$this->mTitle
->userCanRead() ) {
773 $wgOut->loginToUse();
778 # We're looking at an old revision
780 if ( !empty( $oldid ) ) {
781 $wgOut->setRobotpolicy( 'noindex,nofollow' );
782 if( is_null( $this->mRevision
) ) {
783 // FIXME: This would be a nice place to load the 'no such page' text.
785 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
786 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
787 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
788 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
789 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
792 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
793 // and we are allowed to see...
801 $wgOut->setRevisionId( $this->getRevIdFetched() );
803 // Pages containing custom CSS or JavaScript get special treatment
804 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
805 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
807 // Give hooks a chance to customise the output
808 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
809 // Wrap the whole lot in a <pre> and don't parse
811 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
812 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
813 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
814 $wgOut->addHtml( "\n</pre>\n" );
819 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
821 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
822 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
823 # Don't overwrite the subtitle if this was an old revision
824 if( !$wasRedirected && $this->isCurrent() ) {
825 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
827 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
829 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
830 '<span class="redirectText">'.$link.'</span>' );
832 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
833 $wgOut->addParserOutputNoText( $parseout );
834 } else if ( $pcache ) {
835 # Display content and save to parser cache
836 $this->outputWikiText( $text );
838 # Display content, don't attempt to save to parser cache
839 # Don't show section-edit links on old revisions... this way lies madness.
840 if( !$this->isCurrent() ) {
841 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
843 # Display content and don't save to parser cache
844 # With timing hack -- TS 2006-07-26
846 $this->outputWikiText( $text, false );
851 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
852 $this->mTitle
->getPrefixedDBkey()));
855 if( !$this->isCurrent() ) {
856 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
861 /* title may have been set from the cache */
862 $t = $wgOut->getPageTitle();
864 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
867 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
868 if( $ns == NS_USER_TALK
&&
869 User
::isIP( $this->mTitle
->getText() ) ) {
870 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
873 # If we have been passed an &rcid= parameter, we want to give the user a
874 # chance to mark this new article as patrolled.
875 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
877 "<div class='patrollink'>" .
878 wfMsgHtml( 'markaspatrolledlink',
879 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
880 "action=markpatrolled&rcid=$rcid" )
887 if ($wgUseTrackbacks)
888 $this->addTrackbacks();
890 $this->viewUpdates();
891 wfProfileOut( __METHOD__
);
895 * Output a notice that a page is protected. Only give details for edit
896 * restrictions. Cares only about the first permission in the arrays, which is
897 * part of a larger shitty inconsistency about requiring several permissions...
898 * @param Array $editrestr, edit restrictions
900 function addProtectionNotice( $editrestr ) {
903 if( empty($editrestr) )
906 $permission = $editrestr[0];
907 $permission = ($permission=='sysop') ?
'protect' : $permission;
910 # Get groups that have each right
912 $editGroups = $wgOut->getGroupsWithPermission( $permission );
913 $editGroups = implode( ', ', $editGroups );
915 # Use general messages if no groups found for a type
917 $msg = wfMsgExt( 'protected-subtitle', array('parsemag'), $editrestr );
919 $msg = wfMsgExt( 'protected-subtitle-edit', array('parsemag'), $editGroups, $editrestr );
921 if( $wgOut->getSubtitle() )
924 $wgOut->setSubtitle( $wgOut->getSubtitle() . $msg );
927 function addTrackbacks() {
928 global $wgOut, $wgUser;
930 $dbr = wfGetDB(DB_SLAVE
);
932 /* FROM */ 'trackbacks',
933 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
934 /* WHERE */ array('tb_page' => $this->getID())
937 if (!$dbr->numrows($tbs))
941 while ($o = $dbr->fetchObject($tbs)) {
943 if ($wgUser->isAllowed( 'trackback' )) {
944 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
945 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
946 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
948 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
955 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
958 function deletetrackback() {
959 global $wgUser, $wgRequest, $wgOut, $wgTitle;
961 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
962 $wgOut->addWikitext(wfMsg('sessionfailure'));
966 if ((!$wgUser->isAllowed('delete'))) {
967 $wgOut->permissionRequired( 'delete' );
972 $wgOut->readOnlyPage();
976 $db = wfGetDB(DB_MASTER
);
977 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
978 $wgTitle->invalidateCache();
979 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
985 $wgOut->setArticleBodyOnly(true);
990 * Handle action=purge
993 global $wgUser, $wgRequest, $wgOut;
995 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
996 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1000 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1001 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1002 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1003 $msg = str_replace( '$1',
1004 "<form method=\"post\" action=\"$action\">\n" .
1005 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1006 "</form>\n", $msg );
1008 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1009 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1010 $wgOut->addHTML( $msg );
1015 * Perform the actions of a page purging
1017 function doPurge() {
1019 // Invalidate the cache
1020 $this->mTitle
->invalidateCache();
1022 if ( $wgUseSquid ) {
1023 // Commit the transaction before the purge is sent
1024 $dbw = wfGetDB( DB_MASTER
);
1025 $dbw->immediateCommit();
1028 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1029 $update->doUpdate();
1035 * Insert a new empty page record for this article.
1036 * This *must* be followed up by creating a revision
1037 * and running $this->updateToLatest( $rev_id );
1038 * or else the record will be left in a funky state.
1039 * Best if all done inside a transaction.
1041 * @param Database $dbw
1042 * @return int The newly created page_id key
1045 function insertOn( $dbw ) {
1046 wfProfileIn( __METHOD__
);
1048 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1049 $dbw->insert( 'page', array(
1050 'page_id' => $page_id,
1051 'page_namespace' => $this->mTitle
->getNamespace(),
1052 'page_title' => $this->mTitle
->getDBkey(),
1053 'page_counter' => 0,
1054 'page_restrictions' => '',
1055 'page_is_redirect' => 0, # Will set this shortly...
1057 'page_random' => wfRandom(),
1058 'page_touched' => $dbw->timestamp(),
1059 'page_latest' => 0, # Fill this in shortly...
1060 'page_len' => 0, # Fill this in shortly...
1062 $newid = $dbw->insertId();
1064 $this->mTitle
->resetArticleId( $newid );
1066 wfProfileOut( __METHOD__
);
1071 * Update the page record to point to a newly saved revision.
1073 * @param Database $dbw
1074 * @param Revision $revision For ID number, and text used to set
1075 length and redirect status fields
1076 * @param int $lastRevision If given, will not overwrite the page field
1077 * when different from the currently set value.
1078 * Giving 0 indicates the new page flag should
1080 * @param bool $lastRevIsRedirect If given, will optimize adding and
1081 * removing rows in redirect table.
1082 * @return bool true on success, false on failure
1085 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1086 wfProfileIn( __METHOD__
);
1088 $text = $revision->getText();
1089 $rt = Title
::newFromRedirect( $text );
1091 $conditions = array( 'page_id' => $this->getId() );
1092 if( !is_null( $lastRevision ) ) {
1093 # An extra check against threads stepping on each other
1094 $conditions['page_latest'] = $lastRevision;
1097 $dbw->update( 'page',
1099 'page_latest' => $revision->getId(),
1100 'page_touched' => $dbw->timestamp(),
1101 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1102 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1103 'page_len' => strlen( $text ),
1108 $result = $dbw->affectedRows() != 0;
1111 // FIXME: Should the result from updateRedirectOn() be returned instead?
1112 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1115 wfProfileOut( __METHOD__
);
1120 * Add row to the redirect table if this is a redirect, remove otherwise.
1122 * @param Database $dbw
1123 * @param $redirectTitle a title object pointing to the redirect target,
1124 * or NULL if this is not a redirect
1125 * @param bool $lastRevIsRedirect If given, will optimize adding and
1126 * removing rows in redirect table.
1127 * @return bool true on success, false on failure
1130 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1132 // Always update redirects (target link might have changed)
1133 // Update/Insert if we don't know if the last revision was a redirect or not
1134 // Delete if changing from redirect to non-redirect
1135 $isRedirect = !is_null($redirectTitle);
1136 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1138 wfProfileIn( __METHOD__
);
1142 // This title is a redirect, Add/Update row in the redirect table
1143 $set = array( /* SET */
1144 'rd_namespace' => $redirectTitle->getNamespace(),
1145 'rd_title' => $redirectTitle->getDBkey(),
1146 'rd_from' => $this->getId(),
1149 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1151 // This is not a redirect, remove row from redirect table
1152 $where = array( 'rd_from' => $this->getId() );
1153 $dbw->delete( 'redirect', $where, __METHOD__
);
1156 wfProfileOut( __METHOD__
);
1157 return ( $dbw->affectedRows() != 0 );
1164 * If the given revision is newer than the currently set page_latest,
1165 * update the page record. Otherwise, do nothing.
1167 * @param Database $dbw
1168 * @param Revision $revision
1170 function updateIfNewerOn( &$dbw, $revision ) {
1171 wfProfileIn( __METHOD__
);
1173 $row = $dbw->selectRow(
1174 array( 'revision', 'page' ),
1175 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1177 'page_id' => $this->getId(),
1178 'page_latest=rev_id' ),
1181 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1182 wfProfileOut( __METHOD__
);
1185 $prev = $row->rev_id
;
1186 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1188 # No or missing previous revision; mark the page as new
1190 $lastRevIsRedirect = null;
1193 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1194 wfProfileOut( __METHOD__
);
1199 * @return string Complete article text, or null if error
1201 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1202 wfProfileIn( __METHOD__
);
1204 if( $section == '' ) {
1205 // Whole-page edit; let the text through unmolested.
1207 if( is_null( $edittime ) ) {
1208 $rev = Revision
::newFromTitle( $this->mTitle
);
1210 $dbw = wfGetDB( DB_MASTER
);
1211 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1213 if( is_null( $rev ) ) {
1214 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1215 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1218 $oldtext = $rev->getText();
1220 if( $section == 'new' ) {
1221 # Inserting a new section
1222 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1223 $text = strlen( trim( $oldtext ) ) > 0
1224 ?
"{$oldtext}\n\n{$subject}{$text}"
1225 : "{$subject}{$text}";
1227 # Replacing an existing section; roll out the big guns
1229 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1234 wfProfileOut( __METHOD__
);
1239 * @deprecated use Article::doEdit()
1241 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1242 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1243 ( $isminor ? EDIT_MINOR
: 0 ) |
1244 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1246 # If this is a comment, add the summary as headline
1247 if ( $comment && $summary != "" ) {
1248 $text = "== {$summary} ==\n\n".$text;
1251 $this->doEdit( $text, $summary, $flags );
1253 $dbw = wfGetDB( DB_MASTER
);
1255 if (!$this->mTitle
->userIsWatching()) {
1261 if ( $this->mTitle
->userIsWatching() ) {
1267 $this->doRedirect( $this->isRedirect( $text ) );
1271 * @deprecated use Article::doEdit()
1273 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1274 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1275 ( $minor ? EDIT_MINOR
: 0 ) |
1276 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1278 $good = $this->doEdit( $text, $summary, $flags );
1280 $dbw = wfGetDB( DB_MASTER
);
1282 if (!$this->mTitle
->userIsWatching()) {
1288 if ( $this->mTitle
->userIsWatching() ) {
1295 $extraq = ''; // Give extensions a chance to modify URL query on update
1296 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1298 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1306 * Change an existing article or create a new article. Updates RC and all necessary caches,
1307 * optionally via the deferred update array.
1309 * $wgUser must be set before calling this function.
1311 * @param string $text New text
1312 * @param string $summary Edit summary
1313 * @param integer $flags bitfield:
1315 * Article is known or assumed to be non-existent, create a new one
1317 * Article is known or assumed to be pre-existing, update it
1319 * Mark this edit minor, if the user is allowed to do so
1321 * Do not log the change in recentchanges
1323 * Mark the edit a "bot" edit regardless of user rights
1324 * EDIT_DEFER_UPDATES
1325 * Defer some of the updates until the end of index.php
1327 * Fill in blank summaries with generated text where possible
1329 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1330 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1331 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1332 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1333 * to MediaWiki's performance-optimised locking strategy.
1335 * @return bool success
1337 function doEdit( $text, $summary, $flags = 0 ) {
1338 global $wgUser, $wgDBtransactions;
1340 wfProfileIn( __METHOD__
);
1343 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1344 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1346 $flags |
= EDIT_UPDATE
;
1352 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1353 &$summary, $flags & EDIT_MINOR
,
1354 null, null, &$flags ) ) )
1356 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1357 wfProfileOut( __METHOD__
);
1361 # Silently ignore EDIT_MINOR if not allowed
1362 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1363 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1365 $oldtext = $this->getContent();
1366 $oldsize = strlen( $oldtext );
1368 # Provide autosummaries if one is not provided.
1369 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1370 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1372 $text = $this->preSaveTransform( $text );
1373 $newsize = strlen( $text );
1375 $dbw = wfGetDB( DB_MASTER
);
1376 $now = wfTimestampNow();
1378 if ( $flags & EDIT_UPDATE
) {
1379 # Update article, but only if changed.
1381 # Make sure the revision is either completely inserted or not inserted at all
1382 if( !$wgDBtransactions ) {
1383 $userAbort = ignore_user_abort( true );
1389 if ( 0 != strcmp( $text, $oldtext ) ) {
1390 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1391 - (int)$this->isCountable( $oldtext );
1392 $this->mTotalAdjustment
= 0;
1394 $lastRevision = $dbw->selectField(
1395 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1397 if ( !$lastRevision ) {
1398 # Article gone missing
1399 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1400 wfProfileOut( __METHOD__
);
1404 $revision = new Revision( array(
1405 'page' => $this->getId(),
1406 'comment' => $summary,
1407 'minor_edit' => $isminor,
1412 $revisionId = $revision->insertOn( $dbw );
1415 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1418 /* Belated edit conflict! Run away!! */
1422 # Update recentchanges
1423 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1424 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1425 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1428 # Mark as patrolled if the user can do so
1429 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1430 RecentChange
::markPatrolled( $rcid );
1431 PatrolLog
::record( $rcid, true );
1434 $wgUser->incEditCount();
1439 // Keep the same revision ID, but do some updates on it
1440 $revisionId = $this->getRevIdFetched();
1441 // Update page_touched, this is usually implicit in the page update
1442 // Other cache updates are done in onArticleEdit()
1443 $this->mTitle
->invalidateCache();
1446 if( !$wgDBtransactions ) {
1447 ignore_user_abort( $userAbort );
1451 # Invalidate cache of this article and all pages using this article
1452 # as a template. Partly deferred.
1453 Article
::onArticleEdit( $this->mTitle
);
1455 # Update links tables, site stats, etc.
1456 $changed = ( strcmp( $oldtext, $text ) != 0 );
1457 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1460 # Create new article
1462 # Set statistics members
1463 # We work out if it's countable after PST to avoid counter drift
1464 # when articles are created with {{subst:}}
1465 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1466 $this->mTotalAdjustment
= 1;
1470 # Add the page record; stake our claim on this title!
1471 # This will fail with a database query exception if the article already exists
1472 $newid = $this->insertOn( $dbw );
1474 # Save the revision text...
1475 $revision = new Revision( array(
1477 'comment' => $summary,
1478 'minor_edit' => $isminor,
1481 $revisionId = $revision->insertOn( $dbw );
1483 $this->mTitle
->resetArticleID( $newid );
1485 # Update the page record with revision data
1486 $this->updateRevisionOn( $dbw, $revision, 0 );
1488 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1489 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1490 '', strlen( $text ), $revisionId );
1491 # Mark as patrolled if the user can
1492 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1493 RecentChange
::markPatrolled( $rcid );
1494 PatrolLog
::record( $rcid, true );
1497 $wgUser->incEditCount();
1500 # Update links, etc.
1501 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1504 Article
::onArticleCreate( $this->mTitle
);
1506 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1507 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1510 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1514 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1515 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1517 wfProfileOut( __METHOD__
);
1522 * @deprecated wrapper for doRedirect
1524 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1525 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1529 * Output a redirect back to the article.
1530 * This is typically used after an edit.
1532 * @param boolean $noRedir Add redirect=no
1533 * @param string $sectionAnchor section to redirect to, including "#"
1535 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1538 $query = 'redirect=no';
1540 $query .= "&$query";
1544 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1548 * Mark this particular edit as patrolled
1550 function markpatrolled() {
1551 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1552 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1554 # Check RC patrol config. option
1555 if( !$wgUseRCPatrol ) {
1556 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1561 if( !$wgUser->isAllowed( 'patrol' ) ) {
1562 $wgOut->permissionRequired( 'patrol' );
1566 # If we haven't been given an rc_id value, we can't do anything
1567 $rcid = $wgRequest->getVal( 'rcid' );
1569 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1573 # Handle the 'MarkPatrolled' hook
1574 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1578 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1579 # If it's left up to us, check that the user is allowed to patrol this edit
1580 # If the user has the "autopatrol" right, then we'll assume there are no
1581 # other conditions stopping them doing so
1582 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1583 $rc = RecentChange
::newFromId( $rcid );
1584 # Graceful error handling, as we've done before here...
1585 # (If the recent change doesn't exist, then it doesn't matter whether
1586 # the user is allowed to patrol it or not; nothing is going to happen
1587 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1588 # The user made this edit, and can't patrol it
1589 # Tell them so, and then back off
1590 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1591 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1592 $wgOut->returnToMain( false, $return );
1597 # Mark the edit as patrolled
1598 RecentChange
::markPatrolled( $rcid );
1599 PatrolLog
::record( $rcid );
1600 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1603 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1604 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1605 $wgOut->returnToMain( false, $return );
1609 * User-interface handler for the "watch" action
1614 global $wgUser, $wgOut;
1616 if ( $wgUser->isAnon() ) {
1617 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1620 if ( wfReadOnly() ) {
1621 $wgOut->readOnlyPage();
1625 if( $this->doWatch() ) {
1626 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1627 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1629 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1630 $text = wfMsg( 'addedwatchtext', $link );
1631 $wgOut->addWikiText( $text );
1634 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1638 * Add this page to $wgUser's watchlist
1639 * @return bool true on successful watch operation
1641 function doWatch() {
1643 if( $wgUser->isAnon() ) {
1647 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1648 $wgUser->addWatch( $this->mTitle
);
1650 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1657 * User interface handler for the "unwatch" action.
1659 function unwatch() {
1661 global $wgUser, $wgOut;
1663 if ( $wgUser->isAnon() ) {
1664 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1667 if ( wfReadOnly() ) {
1668 $wgOut->readOnlyPage();
1672 if( $this->doUnwatch() ) {
1673 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1674 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1676 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1677 $text = wfMsg( 'removedwatchtext', $link );
1678 $wgOut->addWikiText( $text );
1681 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1685 * Stop watching a page
1686 * @return bool true on successful unwatch
1688 function doUnwatch() {
1690 if( $wgUser->isAnon() ) {
1694 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1695 $wgUser->removeWatch( $this->mTitle
);
1697 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1704 * action=protect handler
1706 function protect() {
1707 $form = new ProtectionForm( $this );
1712 * action=unprotect handler (alias)
1714 function unprotect() {
1719 * Update the article's restriction field, and leave a log entry.
1721 * @param array $limit set of restriction keys
1722 * @param string $reason
1723 * @return bool true on success
1725 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1726 global $wgUser, $wgRestrictionTypes, $wgContLang;
1728 $id = $this->mTitle
->getArticleID();
1729 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1737 // Take this opportunity to purge out expired restrictions
1738 Title
::purgeExpiredRestrictions();
1740 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1741 # we expect a single selection, but the schema allows otherwise.
1743 foreach( $wgRestrictionTypes as $action )
1744 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1746 $current = Article
::flattenRestrictions( $current );
1747 $updated = Article
::flattenRestrictions( $limit );
1749 $changed = ( $current != $updated );
1750 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1751 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1752 $protect = ( $updated != '' );
1754 # If nothing's changed, do nothing
1756 global $wgGroupPermissions;
1757 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1759 $dbw = wfGetDB( DB_MASTER
);
1761 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1763 $expiry_description = '';
1764 if ( $encodedExpiry != 'infinity' ) {
1765 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1768 # Prepare a null revision to be added to the history
1769 $modified = $current != '' && $protect;
1771 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1773 $comment_type = 'unprotectedarticle';
1775 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1777 foreach( $limit as $action => $restrictions ) {
1778 # Check if the group level required to edit also can protect pages
1779 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1780 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1783 $cascade_description = '';
1785 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1789 $comment .= ": $reason";
1791 $comment .= " [$updated]";
1792 if ( $expiry_description && $protect )
1793 $comment .= "$expiry_description";
1795 $comment .= "$cascade_description";
1797 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1798 $nullRevId = $nullRevision->insertOn( $dbw );
1800 # Update restrictions table
1801 foreach( $limit as $action => $restrictions ) {
1802 if ($restrictions != '' ) {
1803 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1804 array( 'pr_page' => $id, 'pr_type' => $action
1805 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1806 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1808 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1809 'pr_type' => $action ), __METHOD__
);
1813 # Update page record
1814 $dbw->update( 'page',
1816 'page_touched' => $dbw->timestamp(),
1817 'page_restrictions' => '',
1818 'page_latest' => $nullRevId
1819 ), array( /* WHERE */
1821 ), 'Article::protect'
1823 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1825 # Update the protection log
1826 $log = new LogPage( 'protect' );
1829 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1831 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1835 } # End "changed" check
1841 * Take an array of page restrictions and flatten it to a string
1842 * suitable for insertion into the page_restrictions field.
1843 * @param array $limit
1847 function flattenRestrictions( $limit ) {
1848 if( !is_array( $limit ) ) {
1849 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1853 foreach( $limit as $action => $restrictions ) {
1854 if( $restrictions != '' ) {
1855 $bits[] = "$action=$restrictions";
1858 return implode( ':', $bits );
1862 * UI entry point for page deletion
1865 global $wgUser, $wgOut, $wgRequest;
1866 $confirm = $wgRequest->wasPosted() &&
1867 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1868 $reason = $wgRequest->getText( 'wpReason' );
1870 # This code desperately needs to be totally rewritten
1873 if( $wgUser->isAllowed( 'delete' ) ) {
1874 if( $wgUser->isBlocked( !$confirm ) ) {
1875 $wgOut->blockedPage();
1879 $wgOut->permissionRequired( 'delete' );
1883 if( wfReadOnly() ) {
1884 $wgOut->readOnlyPage();
1888 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1890 # Better double-check that it hasn't been deleted yet!
1891 $dbw = wfGetDB( DB_MASTER
);
1892 $conds = $this->mTitle
->pageCond();
1893 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1894 if ( $latest === false ) {
1895 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1900 $this->doDelete( $reason );
1901 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1903 } elseif( $this->mTitle
->userIsWatching() ) {
1909 # determine whether this page has earlier revisions
1910 # and insert a warning if it does
1912 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1914 if( count( $authors ) > 1 && !$confirm ) {
1915 $skin=$wgUser->getSkin();
1916 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1919 # If a single user is responsible for all revisions, find out who they are
1920 if ( count( $authors ) == $maxRevisions ) {
1921 // Query bailed out, too many revisions to find out if they're all the same
1922 $authorOfAll = false;
1924 $authorOfAll = reset( $authors );
1925 foreach ( $authors as $author ) {
1926 if ( $authorOfAll != $author ) {
1927 $authorOfAll = false;
1932 # Fetch article text
1933 $rev = Revision
::newFromTitle( $this->mTitle
);
1935 if( !is_null( $rev ) ) {
1936 # if this is a mini-text, we can paste part of it into the deletion reason
1937 $text = $rev->getText();
1939 #if this is empty, an earlier revision may contain "useful" text
1942 $prev = $rev->getPrevious();
1944 $text = $prev->getText();
1949 $length = strlen( $text );
1951 # this should not happen, since it is not possible to store an empty, new
1952 # page. Let's insert a standard text in case it does, though
1953 if( $length == 0 && $reason === '' ) {
1954 $reason = wfMsgForContent( 'exblank' );
1957 if( $reason === '' ) {
1958 # comment field=255, let's grep the first 150 to have some user
1961 $text = $wgContLang->truncate( $text, 150, '...' );
1963 # let's strip out newlines
1964 $text = preg_replace( "/[\n\r]/", '', $text );
1967 if( $authorOfAll === false ) {
1968 $reason = wfMsgForContent( 'excontent', $text );
1970 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1973 $reason = wfMsgForContent( 'exbeforeblank', $text );
1978 return $this->confirmDelete( '', $reason );
1982 * Get the last N authors
1983 * @param int $num Number of revisions to get
1984 * @param string $revLatest The latest rev_id, selected from the master (optional)
1985 * @return array Array of authors, duplicates not removed
1987 function getLastNAuthors( $num, $revLatest = 0 ) {
1988 wfProfileIn( __METHOD__
);
1990 // First try the slave
1991 // If that doesn't have the latest revision, try the master
1993 $db = wfGetDB( DB_SLAVE
);
1995 $res = $db->select( array( 'page', 'revision' ),
1996 array( 'rev_id', 'rev_user_text' ),
1998 'page_namespace' => $this->mTitle
->getNamespace(),
1999 'page_title' => $this->mTitle
->getDBkey(),
2000 'rev_page = page_id'
2001 ), __METHOD__
, $this->getSelectOptions( array(
2002 'ORDER BY' => 'rev_timestamp DESC',
2007 wfProfileOut( __METHOD__
);
2010 $row = $db->fetchObject( $res );
2011 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2012 $db = wfGetDB( DB_MASTER
);
2017 } while ( $continue );
2019 $authors = array( $row->rev_user_text
);
2020 while ( $row = $db->fetchObject( $res ) ) {
2021 $authors[] = $row->rev_user_text
;
2023 wfProfileOut( __METHOD__
);
2028 * Output deletion confirmation dialog
2030 function confirmDelete( $par, $reason ) {
2031 global $wgOut, $wgUser;
2033 wfDebug( "Article::confirmDelete\n" );
2035 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
2036 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
2037 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2038 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
2040 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
2042 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
2043 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
2044 $token = htmlspecialchars( $wgUser->editToken() );
2045 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
2048 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2052 <label for='wpReason'>{$delcom}:</label>
2055 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2065 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2069 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2072 $wgOut->returnToMain( false );
2074 $this->showLogExtract( $wgOut );
2079 * Show relevant lines from the deletion log
2081 function showLogExtract( $out ) {
2082 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2083 $logViewer = new LogViewer(
2086 array( 'page' => $this->mTitle
->getPrefixedText(),
2087 'type' => 'delete' ) ) ) );
2088 $logViewer->showList( $out );
2093 * Perform a deletion and output success or failure messages
2095 function doDelete( $reason ) {
2096 global $wgOut, $wgUser;
2097 wfDebug( __METHOD__
."\n" );
2099 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2100 if ( $this->doDeleteArticle( $reason ) ) {
2101 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2103 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2104 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2106 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2107 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2109 $wgOut->addWikiText( $text );
2110 $wgOut->returnToMain( false );
2111 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2113 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2119 * Back-end article deletion
2120 * Deletes the article with database consistency, writes logs, purges caches
2123 function doDeleteArticle( $reason ) {
2124 global $wgUseSquid, $wgDeferredUpdateList;
2125 global $wgUseTrackbacks;
2127 wfDebug( __METHOD__
."\n" );
2129 $dbw = wfGetDB( DB_MASTER
);
2130 $ns = $this->mTitle
->getNamespace();
2131 $t = $this->mTitle
->getDBkey();
2132 $id = $this->mTitle
->getArticleID();
2134 if ( $t == '' ||
$id == 0 ) {
2138 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2139 array_push( $wgDeferredUpdateList, $u );
2141 // For now, shunt the revision data into the archive table.
2142 // Text is *not* removed from the text table; bulk storage
2143 // is left intact to avoid breaking block-compression or
2144 // immutable storage schemes.
2146 // For backwards compatibility, note that some older archive
2147 // table entries will have ar_text and ar_flags fields still.
2149 // In the future, we may keep revisions and mark them with
2150 // the rev_deleted field, which is reserved for this purpose.
2151 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2153 'ar_namespace' => 'page_namespace',
2154 'ar_title' => 'page_title',
2155 'ar_comment' => 'rev_comment',
2156 'ar_user' => 'rev_user',
2157 'ar_user_text' => 'rev_user_text',
2158 'ar_timestamp' => 'rev_timestamp',
2159 'ar_minor_edit' => 'rev_minor_edit',
2160 'ar_rev_id' => 'rev_id',
2161 'ar_text_id' => 'rev_text_id',
2162 'ar_text' => '\'\'', // Be explicit to appease
2163 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2164 'ar_len' => 'rev_len',
2165 'ar_page_id' => 'page_id',
2168 'page_id = rev_page'
2172 # Delete restrictions for it
2173 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2175 # Now that it's safely backed up, delete it
2176 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2178 # If using cascading deletes, we can skip some explicit deletes
2179 if ( !$dbw->cascadingDeletes() ) {
2181 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2183 if ($wgUseTrackbacks)
2184 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2186 # Delete outgoing links
2187 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2188 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2189 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2190 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2191 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2192 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2193 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2196 # If using cleanup triggers, we can skip some manual deletes
2197 if ( !$dbw->cleanupTriggers() ) {
2199 # Clean up recentchanges entries...
2200 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2204 Article
::onArticleDelete( $this->mTitle
);
2207 $log = new LogPage( 'delete' );
2208 $log->addEntry( 'delete', $this->mTitle
, $reason );
2210 # Clear the cached article id so the interface doesn't act like we exist
2211 $this->mTitle
->resetArticleID( 0 );
2212 $this->mTitle
->mArticleID
= 0;
2217 * Roll back the most recent consecutive set of edits to a page
2218 * from the same user; fails if there are no eligible edits to
2219 * roll back to, e.g. user is the sole contributor
2221 * @param string $fromP - Name of the user whose edits to rollback.
2222 * @param string $summary - Custom summary. Set to default summary if empty.
2223 * @param string $token - Rollback token.
2224 * @param bool $bot - If true, mark all reverted edits as bot.
2226 * @param array $resultDetails contains result-specific dict of additional values
2227 * ALREADY_ROLLED : 'current' (rev)
2228 * SUCCESS : 'summary' (str), 'current' (rev), 'target' (rev)
2230 * @return self::SUCCESS on succes, self::* on failure
2232 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2233 global $wgUser, $wgUseRCPatrol;
2234 $resultDetails = null;
2236 if( $wgUser->isAllowed( 'rollback' ) ) {
2237 if( $wgUser->isBlocked() ) {
2238 return self
::BLOCKED
;
2241 return self
::PERM_DENIED
;
2244 if ( wfReadOnly() ) {
2245 return self
::READONLY
;
2247 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2248 return self
::BAD_TOKEN
;
2250 $dbw = wfGetDB( DB_MASTER
);
2252 # Get the last editor
2253 $current = Revision
::newFromTitle( $this->mTitle
);
2254 if( is_null( $current ) ) {
2255 # Something wrong... no page?
2256 return self
::BAD_TITLE
;
2259 $from = str_replace( '_', ' ', $fromP );
2260 if( $from != $current->getUserText() ) {
2261 $resultDetails = array( 'current' => $current );
2262 return self
::ALREADY_ROLLED
;
2265 # Get the last edit not by this guy
2266 $user = intval( $current->getUser() );
2267 $user_text = $dbw->addQuotes( $current->getUserText() );
2268 $s = $dbw->selectRow( 'revision',
2269 array( 'rev_id', 'rev_timestamp' ),
2271 'rev_page' => $current->getPage(),
2272 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2275 'USE INDEX' => 'page_timestamp',
2276 'ORDER BY' => 'rev_timestamp DESC' )
2278 if( $s === false ) {
2280 return self
::ONLY_AUTHOR
;
2285 # Mark all reverted edits as bot
2288 if ( $wgUseRCPatrol ) {
2289 # Mark all reverted edits as patrolled
2290 $set['rc_patrolled'] = 1;
2294 $dbw->update( 'recentchanges', $set,
2296 'rc_cur_id' => $current->getPage(),
2297 'rc_user_text' => $current->getUserText(),
2298 "rc_timestamp > '{$s->rev_timestamp}'",
2303 # Get the edit summary
2304 $target = Revision
::newFromId( $s->rev_id
);
2305 if( empty( $summary ) )
2306 $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2309 $flags = EDIT_UPDATE | EDIT_MINOR
;
2311 $flags |
= EDIT_FORCE_BOT
;
2312 $this->doEdit( $target->getText(), $summary, $flags );
2314 $resultDetails = array(
2315 'summary' => $summary,
2316 'current' => $current,
2317 'target' => $target,
2319 return self
::SUCCESS
;
2323 * User interface for rollback operations
2325 function rollback() {
2326 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2329 $result = $this->doRollback(
2330 $wgRequest->getVal( 'from' ),
2331 $wgRequest->getText( 'summary' ),
2332 $wgRequest->getVal( 'token' ),
2333 $wgRequest->getBool( 'bot' ),
2339 $wgOut->blockedPage();
2341 case self
::PERM_DENIED
:
2342 $wgOut->permissionRequired( 'rollback' );
2344 case self
::READONLY
:
2345 $wgOut->readOnlyPage( $this->getContent() );
2347 case self
::BAD_TOKEN
:
2348 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2349 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2351 case self
::BAD_TITLE
:
2352 $wgOut->addHtml( wfMsg( 'notanarticle' ) );
2354 case self
::ALREADY_ROLLED
:
2355 $current = $details['current'];
2356 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2357 $wgOut->addWikiText(
2358 wfMsg( 'alreadyrolled',
2359 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2360 htmlspecialchars( $wgRequest->getVal( 'from' ) ),
2361 htmlspecialchars( $current->getUserText() )
2364 if( $current->getComment() != '' ) {
2365 $wgOut->addHtml( wfMsg( 'editcomment',
2366 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2369 case self
::ONLY_AUTHOR
:
2370 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2371 $wgOut->addHtml( wfMsg( 'cantrollback' ) );
2374 $current = $details['current'];
2375 $target = $details['target'];
2376 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2377 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2378 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2379 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2380 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2381 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2382 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2383 $wgOut->returnToMain( false, $this->mTitle
);
2386 throw new MWException( __METHOD__
. ": Unknown return value `{$result}`" );
2393 * Do standard deferred updates after page view
2396 function viewUpdates() {
2397 global $wgDeferredUpdateList;
2399 if ( 0 != $this->getID() ) {
2400 global $wgDisableCounters;
2401 if( !$wgDisableCounters ) {
2402 Article
::incViewCount( $this->getID() );
2403 $u = new SiteStatsUpdate( 1, 0, 0 );
2404 array_push( $wgDeferredUpdateList, $u );
2408 # Update newtalk / watchlist notification status
2410 $wgUser->clearNotification( $this->mTitle
);
2414 * Do standard deferred updates after page edit.
2415 * Update links tables, site stats, search index and message cache.
2416 * Every 1000th edit, prune the recent changes table.
2419 * @param $text New text of the article
2420 * @param $summary Edit summary
2421 * @param $minoredit Minor edit
2422 * @param $timestamp_of_pagechange Timestamp associated with the page change
2423 * @param $newid rev_id value of the new revision
2424 * @param $changed Whether or not the content actually changed
2426 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2427 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2429 wfProfileIn( __METHOD__
);
2432 $options = new ParserOptions
;
2433 $options->setTidy(true);
2434 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2436 # Save it to the parser cache
2437 $parserCache =& ParserCache
::singleton();
2438 $parserCache->save( $poutput, $this, $wgUser );
2440 # Update the links tables
2441 $u = new LinksUpdate( $this->mTitle
, $poutput );
2444 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2445 if ( 0 == mt_rand( 0, 99 ) ) {
2446 // Flush old entries from the `recentchanges` table; we do this on
2447 // random requests so as to avoid an increase in writes for no good reason
2449 $dbw = wfGetDB( DB_MASTER
);
2450 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2451 $recentchanges = $dbw->tableName( 'recentchanges' );
2452 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2453 $dbw->query( $sql );
2457 $id = $this->getID();
2458 $title = $this->mTitle
->getPrefixedDBkey();
2459 $shortTitle = $this->mTitle
->getDBkey();
2462 wfProfileOut( __METHOD__
);
2466 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2467 array_push( $wgDeferredUpdateList, $u );
2468 $u = new SearchUpdate( $id, $title, $text );
2469 array_push( $wgDeferredUpdateList, $u );
2471 # If this is another user's talk page, update newtalk
2472 # Don't do this if $changed = false otherwise some idiot can null-edit a
2473 # load of user talk pages and piss people off, nor if it's a minor edit
2474 # by a properly-flagged bot.
2475 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2476 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2477 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2478 $other = User
::newFromName( $shortTitle );
2479 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2480 // An anonymous user
2481 $other = new User();
2482 $other->setName( $shortTitle );
2485 $other->setNewtalk( true );
2490 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2491 $wgMessageCache->replace( $shortTitle, $text );
2494 wfProfileOut( __METHOD__
);
2498 * Perform article updates on a special page creation.
2500 * @param Revision $rev
2502 * @todo This is a shitty interface function. Kill it and replace the
2503 * other shitty functions like editUpdates and such so it's not needed
2506 function createUpdates( $rev ) {
2507 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2508 $this->mTotalAdjustment
= 1;
2509 $this->editUpdates( $rev->getText(), $rev->getComment(),
2510 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2514 * Generate the navigation links when browsing through an article revisions
2515 * It shows the information as:
2516 * Revision as of \<date\>; view current revision
2517 * \<- Previous version | Next Version -\>
2520 * @param string $oldid Revision ID of this article revision
2522 function setOldSubtitle( $oldid=0 ) {
2523 global $wgLang, $wgOut, $wgUser;
2525 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2529 $revision = Revision
::newFromId( $oldid );
2531 $current = ( $oldid == $this->mLatest
);
2532 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2533 $sk = $wgUser->getSkin();
2535 ?
wfMsg( 'currentrevisionlink' )
2536 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2539 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2540 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2542 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2543 : wfMsg( 'previousrevision' );
2545 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2547 $nextlink = $current
2548 ?
wfMsg( 'nextrevision' )
2549 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2550 $nextdiff = $current
2552 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2554 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2555 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2557 $m = wfMsg( 'revision-info-current' );
2558 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2559 ?
'revision-info-current'
2562 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2563 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2564 $wgOut->setSubtitle( $r );
2568 * This function is called right before saving the wikitext,
2569 * so we can do things like signatures and links-in-context.
2571 * @param string $text
2573 function preSaveTransform( $text ) {
2574 global $wgParser, $wgUser;
2575 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2578 /* Caching functions */
2581 * checkLastModified returns true if it has taken care of all
2582 * output to the client that is necessary for this request.
2583 * (that is, it has sent a cached version of the page)
2585 function tryFileCache() {
2586 static $called = false;
2588 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2592 if($this->isFileCacheable()) {
2593 $touched = $this->mTouched
;
2594 $cache = new HTMLFileCache( $this->mTitle
);
2595 if($cache->isFileCacheGood( $touched )) {
2596 wfDebug( "Article::tryFileCache(): about to load file\n" );
2597 $cache->loadFromFileCache();
2600 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2601 ob_start( array(&$cache, 'saveToFileCache' ) );
2604 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2609 * Check if the page can be cached
2612 function isFileCacheable() {
2613 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2614 $action = $wgRequest->getVal( 'action' );
2615 $oldid = $wgRequest->getVal( 'oldid' );
2616 $diff = $wgRequest->getVal( 'diff' );
2617 $redirect = $wgRequest->getVal( 'redirect' );
2618 $printable = $wgRequest->getVal( 'printable' );
2619 $page = $wgRequest->getVal( 'page' );
2621 //check for non-standard user language; this covers uselang,
2622 //and extensions for auto-detecting user language.
2623 $ulang = $wgLang->getCode();
2624 $clang = $wgContLang->getCode();
2626 $cacheable = $wgUseFileCache
2627 && (!$wgShowIPinHeader)
2628 && ($this->getID() != 0)
2629 && ($wgUser->isAnon())
2630 && (!$wgUser->getNewtalk())
2631 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2632 && (empty( $action ) ||
$action == 'view')
2635 && (!isset($redirect))
2636 && (!isset($printable))
2638 && (!$this->mRedirectedFrom
)
2639 && ($ulang === $clang);
2642 //extension may have reason to disable file caching on some pages.
2643 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2650 * Loads page_touched and returns a value indicating if it should be used
2653 function checkTouched() {
2654 if( !$this->mDataLoaded
) {
2655 $this->loadPageData();
2657 return !$this->mIsRedirect
;
2661 * Get the page_touched field
2663 function getTouched() {
2664 # Ensure that page data has been loaded
2665 if( !$this->mDataLoaded
) {
2666 $this->loadPageData();
2668 return $this->mTouched
;
2672 * Get the page_latest field
2674 function getLatest() {
2675 if ( !$this->mDataLoaded
) {
2676 $this->loadPageData();
2678 return $this->mLatest
;
2682 * Edit an article without doing all that other stuff
2683 * The article must already exist; link tables etc
2684 * are not updated, caches are not flushed.
2686 * @param string $text text submitted
2687 * @param string $comment comment submitted
2688 * @param bool $minor whereas it's a minor modification
2690 function quickEdit( $text, $comment = '', $minor = 0 ) {
2691 wfProfileIn( __METHOD__
);
2693 $dbw = wfGetDB( DB_MASTER
);
2695 $revision = new Revision( array(
2696 'page' => $this->getId(),
2698 'comment' => $comment,
2699 'minor_edit' => $minor ?
1 : 0,
2701 $revision->insertOn( $dbw );
2702 $this->updateRevisionOn( $dbw, $revision );
2705 wfProfileOut( __METHOD__
);
2709 * Used to increment the view counter
2712 * @param integer $id article id
2714 function incViewCount( $id ) {
2715 $id = intval( $id );
2716 global $wgHitcounterUpdateFreq, $wgDBtype;
2718 $dbw = wfGetDB( DB_MASTER
);
2719 $pageTable = $dbw->tableName( 'page' );
2720 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2721 $acchitsTable = $dbw->tableName( 'acchits' );
2723 if( $wgHitcounterUpdateFreq <= 1 ) {
2724 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2728 # Not important enough to warrant an error page in case of failure
2729 $oldignore = $dbw->ignoreErrors( true );
2731 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2733 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2734 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2735 # Most of the time (or on SQL errors), skip row count check
2736 $dbw->ignoreErrors( $oldignore );
2740 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2741 $row = $dbw->fetchObject( $res );
2742 $rown = intval( $row->n
);
2743 if( $rown >= $wgHitcounterUpdateFreq ){
2744 wfProfileIn( 'Article::incViewCount-collect' );
2745 $old_user_abort = ignore_user_abort( true );
2747 if ($wgDBtype == 'mysql')
2748 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2749 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2750 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2751 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2753 $dbw->query("DELETE FROM $hitcounterTable");
2754 if ($wgDBtype == 'mysql') {
2755 $dbw->query('UNLOCK TABLES');
2756 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2757 'WHERE page_id = hc_id');
2760 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2761 "FROM $acchitsTable WHERE page_id = hc_id");
2763 $dbw->query("DROP TABLE $acchitsTable");
2765 ignore_user_abort( $old_user_abort );
2766 wfProfileOut( 'Article::incViewCount-collect' );
2768 $dbw->ignoreErrors( $oldignore );
2772 * The onArticle*() functions are supposed to be a kind of hooks
2773 * which should be called whenever any of the specified actions
2776 * This is a good place to put code to clear caches, for instance.
2778 * This is called on page move and undelete, as well as edit
2780 * @param $title_obj a title object
2783 static function onArticleCreate($title) {
2784 # The talk page isn't in the regular link tables, so we need to update manually:
2785 if ( $title->isTalkPage() ) {
2786 $other = $title->getSubjectPage();
2788 $other = $title->getTalkPage();
2790 $other->invalidateCache();
2791 $other->purgeSquid();
2793 $title->touchLinks();
2794 $title->purgeSquid();
2797 static function onArticleDelete( $title ) {
2798 global $wgUseFileCache, $wgMessageCache;
2800 $title->touchLinks();
2801 $title->purgeSquid();
2804 if ( $wgUseFileCache ) {
2805 $cm = new HTMLFileCache( $title );
2806 @unlink
( $cm->fileCacheName() );
2809 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2810 $wgMessageCache->replace( $title->getDBkey(), false );
2815 * Purge caches on page update etc
2817 static function onArticleEdit( $title ) {
2818 global $wgDeferredUpdateList, $wgUseFileCache;
2820 // Invalidate caches of articles which include this page
2821 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2822 $wgDeferredUpdateList[] = $update;
2824 # Purge squid for this page only
2825 $title->purgeSquid();
2828 if ( $wgUseFileCache ) {
2829 $cm = new HTMLFileCache( $title );
2830 @unlink
( $cm->fileCacheName() );
2837 * Info about this page
2838 * Called for ?action=info when $wgAllowPageInfo is on.
2843 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2845 if ( !$wgAllowPageInfo ) {
2846 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2850 $page = $this->mTitle
->getSubjectPage();
2852 $wgOut->setPagetitle( $page->getPrefixedText() );
2853 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2854 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
2856 if( !$this->mTitle
->exists() ) {
2857 $wgOut->addHtml( '<div class="noarticletext">' );
2858 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2859 // This doesn't quite make sense; the user is asking for
2860 // information about the _page_, not the message... -- RC
2861 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
2863 $msg = $wgUser->isLoggedIn()
2865 : 'noarticletextanon';
2866 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
2868 $wgOut->addHtml( '</div>' );
2870 $dbr = wfGetDB( DB_SLAVE
);
2872 'wl_title' => $page->getDBkey(),
2873 'wl_namespace' => $page->getNamespace() );
2874 $numwatchers = $dbr->selectField(
2879 $this->getSelectOptions() );
2881 $pageInfo = $this->pageCountInfo( $page );
2882 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2884 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2885 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2887 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2889 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2891 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2893 $wgOut->addHTML( '</ul>' );
2899 * Return the total number of edits and number of unique editors
2900 * on a given page. If page does not exist, returns false.
2902 * @param Title $title
2906 function pageCountInfo( $title ) {
2907 $id = $title->getArticleId();
2912 $dbr = wfGetDB( DB_SLAVE
);
2914 $rev_clause = array( 'rev_page' => $id );
2916 $edits = $dbr->selectField(
2921 $this->getSelectOptions() );
2923 $authors = $dbr->selectField(
2925 'COUNT(DISTINCT rev_user_text)',
2928 $this->getSelectOptions() );
2930 return array( 'edits' => $edits, 'authors' => $authors );
2934 * Return a list of templates used by this article.
2935 * Uses the templatelinks table
2937 * @return array Array of Title objects
2939 function getUsedTemplates() {
2941 $id = $this->mTitle
->getArticleID();
2946 $dbr = wfGetDB( DB_SLAVE
);
2947 $res = $dbr->select( array( 'templatelinks' ),
2948 array( 'tl_namespace', 'tl_title' ),
2949 array( 'tl_from' => $id ),
2950 'Article:getUsedTemplates' );
2951 if ( false !== $res ) {
2952 if ( $dbr->numRows( $res ) ) {
2953 while ( $row = $dbr->fetchObject( $res ) ) {
2954 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2958 $dbr->freeResult( $res );
2963 * Return an auto-generated summary if the text provided is a redirect.
2965 * @param string $text The wikitext to check
2966 * @return string '' or an appropriate summary
2968 public static function getRedirectAutosummary( $text ) {
2969 $rt = Title
::newFromRedirect( $text );
2970 if( is_object( $rt ) )
2971 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2977 * Return an auto-generated summary if the new text is much shorter than
2980 * @param string $oldtext The previous text of the page
2981 * @param string $text The submitted text of the page
2982 * @return string An appropriate autosummary, or an empty string.
2984 public static function getBlankingAutosummary( $oldtext, $text ) {
2985 if ($oldtext!='' && $text=='') {
2986 return wfMsgForContent('autosumm-blank');
2987 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2988 #Removing more than 90% of the article
2990 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2991 return wfMsgForContent('autosumm-replace', $truncatedtext);
2998 * Return an applicable autosummary if one exists for the given edit.
2999 * @param string $oldtext The previous text of the page.
3000 * @param string $newtext The submitted text of the page.
3001 * @param bitmask $flags A bitmask of flags submitted for the edit.
3002 * @return string An appropriate autosummary, or an empty string.
3004 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3006 # This code is UGLY UGLY UGLY.
3007 # Somebody PLEASE come up with a more elegant way to do it.
3009 #Redirect autosummaries
3010 $summary = self
::getRedirectAutosummary( $newtext );
3015 #Blanking autosummaries
3016 if (!($flags & EDIT_NEW
))
3017 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3022 #New page autosummaries
3023 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3024 #If they're making a new article, give its text, truncated, in the summary.
3026 $truncatedtext = $wgContLang->truncate(
3027 str_replace("\n", ' ', $newtext),
3028 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3030 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3040 * Add the primary page-view wikitext to the output buffer
3041 * Saves the text into the parser cache if possible.
3042 * Updates templatelinks if it is out of date.
3044 * @param string $text
3045 * @param bool $cache
3047 public function outputWikiText( $text, $cache = true ) {
3048 global $wgParser, $wgUser, $wgOut;
3050 $popts = $wgOut->parserOptions();
3051 $popts->setTidy(true);
3052 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3053 $popts, true, true, $this->getRevIdFetched() );
3054 $popts->setTidy(false);
3055 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3056 $parserCache =& ParserCache
::singleton();
3057 $parserCache->save( $parserOutput, $this, $wgUser );
3060 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3061 // templatelinks table may have become out of sync,
3062 // especially if using variable-based transclusions.
3063 // For paranoia, check if things have changed and if
3064 // so apply updates to the database. This will ensure
3065 // that cascaded protections apply as soon as the changes
3068 # Get templates from templatelinks
3069 $id = $this->mTitle
->getArticleID();
3071 $tlTemplates = array();
3073 $dbr = wfGetDB( DB_SLAVE
);
3074 $res = $dbr->select( array( 'templatelinks' ),
3075 array( 'tl_namespace', 'tl_title' ),
3076 array( 'tl_from' => $id ),
3077 'Article:getUsedTemplates' );
3081 if ( false !== $res ) {
3082 if ( $dbr->numRows( $res ) ) {
3083 while ( $row = $dbr->fetchObject( $res ) ) {
3084 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3089 # Get templates from parser output.
3090 $poTemplates_allns = $parserOutput->getTemplates();
3092 $poTemplates = array ();
3093 foreach ( $poTemplates_allns as $ns_templates ) {
3094 $poTemplates = array_merge( $poTemplates, $ns_templates );
3098 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3100 if ( count( $templates_diff ) > 0 ) {
3101 # Whee, link updates time.
3102 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3104 $dbw = wfGetDb( DB_MASTER
);
3113 $wgOut->addParserOutput( $parserOutput );