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 $moverestr = $this->mTitle
->getRestrictions('move');
746 $this->addProtectionNotice( $editrestr, $moverestr );
750 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
752 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
753 // Ensure that UI elements requiring revision ID have
754 // the correct version information.
755 $wgOut->setRevisionId( $this->mLatest
);
759 if ( !$outputDone ) {
760 $text = $this->getContent();
761 if ( $text === false ) {
762 # Failed to load, replace text with error message
763 $t = $this->mTitle
->getPrefixedText();
765 $t .= ',oldid='.$oldid;
766 $text = wfMsg( 'missingarticle', $t );
768 $text = wfMsg( 'noarticletext', $t );
772 # Another whitelist check in case oldid is altering the title
773 if ( !$this->mTitle
->userCanRead() ) {
774 $wgOut->loginToUse();
779 # We're looking at an old revision
781 if ( !empty( $oldid ) ) {
782 $wgOut->setRobotpolicy( 'noindex,nofollow' );
783 if( is_null( $this->mRevision
) ) {
784 // FIXME: This would be a nice place to load the 'no such page' text.
786 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
787 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
788 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
789 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
790 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
793 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
794 // and we are allowed to see...
802 $wgOut->setRevisionId( $this->getRevIdFetched() );
804 // Pages containing custom CSS or JavaScript get special treatment
805 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
806 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
808 // Give hooks a chance to customise the output
809 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
810 // Wrap the whole lot in a <pre> and don't parse
812 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
813 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
814 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
815 $wgOut->addHtml( "\n</pre>\n" );
820 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
822 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
823 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
824 # Don't overwrite the subtitle if this was an old revision
825 if( !$wasRedirected && $this->isCurrent() ) {
826 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
828 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
830 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
831 '<span class="redirectText">'.$link.'</span>' );
833 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
834 $wgOut->addParserOutputNoText( $parseout );
835 } else if ( $pcache ) {
836 # Display content and save to parser cache
837 $this->outputWikiText( $text );
839 # Display content, don't attempt to save to parser cache
840 # Don't show section-edit links on old revisions... this way lies madness.
841 if( !$this->isCurrent() ) {
842 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
844 # Display content and don't save to parser cache
845 # With timing hack -- TS 2006-07-26
847 $this->outputWikiText( $text, false );
852 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
853 $this->mTitle
->getPrefixedDBkey()));
856 if( !$this->isCurrent() ) {
857 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
862 /* title may have been set from the cache */
863 $t = $wgOut->getPageTitle();
865 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
868 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
869 if( $ns == NS_USER_TALK
&&
870 User
::isIP( $this->mTitle
->getText() ) ) {
871 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
874 # If we have been passed an &rcid= parameter, we want to give the user a
875 # chance to mark this new article as patrolled.
876 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
878 "<div class='patrollink'>" .
879 wfMsgHtml( 'markaspatrolledlink',
880 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
881 "action=markpatrolled&rcid=$rcid" )
888 if ($wgUseTrackbacks)
889 $this->addTrackbacks();
891 $this->viewUpdates();
892 wfProfileOut( __METHOD__
);
896 * Output a notice that a page is protected. Only give details for move/edit
897 * restrictions. Cares only about the first permission in the arrays, which is
898 * part of a larger shitty inconsistency about requiring several permissions...
899 * @param Array $editrestr, edit restrictions
900 * @param Array $moverestr, move restrictions
902 function addProtectionNotice( $editrestr, $moverestr ) {
905 $editGroups = $moveGroups = wfMsg('protected-anyone');
906 # Get groups that have each right
907 if( !empty( $editrestr ) ) {
908 $permission = ($editrestr[0]=='sysop') ?
'protect' : $editrestr[0];
909 $editGroups = $wgOut->getGroupsWithPermission( $permission );
910 $editGroups = implode( ', ', $editGroups );
912 if( !empty( $moverestr ) ) {
913 $permission = ($moverestr[0]=='sysop') ?
'protect' : $moverestr[0];
914 $moveGroups = $wgOut->getGroupsWithPermission( $permission );
915 $moveGroups = implode( ', ', $moveGroups );
917 # Use general messages if no groups found for a type
918 if( !$editGroups ||
!$moveGroups ) {
919 $msg = wfMsg( 'protected-subtitle' );
920 } else if( $editGroups == $moveGroups ) {
921 $msg = wfMsg( 'protected-subtitle-same', $editGroups, $moveGroups );
923 $msg = wfMsg( 'protected-subtitle-each', $editGroups, $moveGroups );
925 if( $wgOut->getSubtitle() )
928 $wgOut->setSubtitle( $wgOut->getSubtitle() . $msg );
931 function addTrackbacks() {
932 global $wgOut, $wgUser;
934 $dbr = wfGetDB(DB_SLAVE
);
936 /* FROM */ 'trackbacks',
937 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
938 /* WHERE */ array('tb_page' => $this->getID())
941 if (!$dbr->numrows($tbs))
945 while ($o = $dbr->fetchObject($tbs)) {
947 if ($wgUser->isAllowed( 'trackback' )) {
948 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
949 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
950 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
952 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
959 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
962 function deletetrackback() {
963 global $wgUser, $wgRequest, $wgOut, $wgTitle;
965 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
966 $wgOut->addWikitext(wfMsg('sessionfailure'));
970 if ((!$wgUser->isAllowed('delete'))) {
971 $wgOut->permissionRequired( 'delete' );
976 $wgOut->readOnlyPage();
980 $db = wfGetDB(DB_MASTER
);
981 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
982 $wgTitle->invalidateCache();
983 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
989 $wgOut->setArticleBodyOnly(true);
994 * Handle action=purge
997 global $wgUser, $wgRequest, $wgOut;
999 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1000 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1004 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1005 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1006 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1007 $msg = str_replace( '$1',
1008 "<form method=\"post\" action=\"$action\">\n" .
1009 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1010 "</form>\n", $msg );
1012 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1013 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1014 $wgOut->addHTML( $msg );
1019 * Perform the actions of a page purging
1021 function doPurge() {
1023 // Invalidate the cache
1024 $this->mTitle
->invalidateCache();
1026 if ( $wgUseSquid ) {
1027 // Commit the transaction before the purge is sent
1028 $dbw = wfGetDB( DB_MASTER
);
1029 $dbw->immediateCommit();
1032 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1033 $update->doUpdate();
1039 * Insert a new empty page record for this article.
1040 * This *must* be followed up by creating a revision
1041 * and running $this->updateToLatest( $rev_id );
1042 * or else the record will be left in a funky state.
1043 * Best if all done inside a transaction.
1045 * @param Database $dbw
1046 * @return int The newly created page_id key
1049 function insertOn( $dbw ) {
1050 wfProfileIn( __METHOD__
);
1052 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1053 $dbw->insert( 'page', array(
1054 'page_id' => $page_id,
1055 'page_namespace' => $this->mTitle
->getNamespace(),
1056 'page_title' => $this->mTitle
->getDBkey(),
1057 'page_counter' => 0,
1058 'page_restrictions' => '',
1059 'page_is_redirect' => 0, # Will set this shortly...
1061 'page_random' => wfRandom(),
1062 'page_touched' => $dbw->timestamp(),
1063 'page_latest' => 0, # Fill this in shortly...
1064 'page_len' => 0, # Fill this in shortly...
1066 $newid = $dbw->insertId();
1068 $this->mTitle
->resetArticleId( $newid );
1070 wfProfileOut( __METHOD__
);
1075 * Update the page record to point to a newly saved revision.
1077 * @param Database $dbw
1078 * @param Revision $revision For ID number, and text used to set
1079 length and redirect status fields
1080 * @param int $lastRevision If given, will not overwrite the page field
1081 * when different from the currently set value.
1082 * Giving 0 indicates the new page flag should
1084 * @param bool $lastRevIsRedirect If given, will optimize adding and
1085 * removing rows in redirect table.
1086 * @return bool true on success, false on failure
1089 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1090 wfProfileIn( __METHOD__
);
1092 $text = $revision->getText();
1093 $rt = Title
::newFromRedirect( $text );
1095 $conditions = array( 'page_id' => $this->getId() );
1096 if( !is_null( $lastRevision ) ) {
1097 # An extra check against threads stepping on each other
1098 $conditions['page_latest'] = $lastRevision;
1101 $dbw->update( 'page',
1103 'page_latest' => $revision->getId(),
1104 'page_touched' => $dbw->timestamp(),
1105 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1106 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1107 'page_len' => strlen( $text ),
1112 $result = $dbw->affectedRows() != 0;
1115 // FIXME: Should the result from updateRedirectOn() be returned instead?
1116 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1119 wfProfileOut( __METHOD__
);
1124 * Add row to the redirect table if this is a redirect, remove otherwise.
1126 * @param Database $dbw
1127 * @param $redirectTitle a title object pointing to the redirect target,
1128 * or NULL if this is not a redirect
1129 * @param bool $lastRevIsRedirect If given, will optimize adding and
1130 * removing rows in redirect table.
1131 * @return bool true on success, false on failure
1134 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1136 // Always update redirects (target link might have changed)
1137 // Update/Insert if we don't know if the last revision was a redirect or not
1138 // Delete if changing from redirect to non-redirect
1139 $isRedirect = !is_null($redirectTitle);
1140 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1142 wfProfileIn( __METHOD__
);
1146 // This title is a redirect, Add/Update row in the redirect table
1147 $set = array( /* SET */
1148 'rd_namespace' => $redirectTitle->getNamespace(),
1149 'rd_title' => $redirectTitle->getDBkey(),
1150 'rd_from' => $this->getId(),
1153 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1155 // This is not a redirect, remove row from redirect table
1156 $where = array( 'rd_from' => $this->getId() );
1157 $dbw->delete( 'redirect', $where, __METHOD__
);
1160 wfProfileOut( __METHOD__
);
1161 return ( $dbw->affectedRows() != 0 );
1168 * If the given revision is newer than the currently set page_latest,
1169 * update the page record. Otherwise, do nothing.
1171 * @param Database $dbw
1172 * @param Revision $revision
1174 function updateIfNewerOn( &$dbw, $revision ) {
1175 wfProfileIn( __METHOD__
);
1177 $row = $dbw->selectRow(
1178 array( 'revision', 'page' ),
1179 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1181 'page_id' => $this->getId(),
1182 'page_latest=rev_id' ),
1185 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1186 wfProfileOut( __METHOD__
);
1189 $prev = $row->rev_id
;
1190 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1192 # No or missing previous revision; mark the page as new
1194 $lastRevIsRedirect = null;
1197 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1198 wfProfileOut( __METHOD__
);
1203 * @return string Complete article text, or null if error
1205 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1206 wfProfileIn( __METHOD__
);
1208 if( $section == '' ) {
1209 // Whole-page edit; let the text through unmolested.
1211 if( is_null( $edittime ) ) {
1212 $rev = Revision
::newFromTitle( $this->mTitle
);
1214 $dbw = wfGetDB( DB_MASTER
);
1215 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1217 if( is_null( $rev ) ) {
1218 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1219 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1222 $oldtext = $rev->getText();
1224 if( $section == 'new' ) {
1225 # Inserting a new section
1226 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1227 $text = strlen( trim( $oldtext ) ) > 0
1228 ?
"{$oldtext}\n\n{$subject}{$text}"
1229 : "{$subject}{$text}";
1231 # Replacing an existing section; roll out the big guns
1233 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1238 wfProfileOut( __METHOD__
);
1243 * @deprecated use Article::doEdit()
1245 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1246 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1247 ( $isminor ? EDIT_MINOR
: 0 ) |
1248 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1250 # If this is a comment, add the summary as headline
1251 if ( $comment && $summary != "" ) {
1252 $text = "== {$summary} ==\n\n".$text;
1255 $this->doEdit( $text, $summary, $flags );
1257 $dbw = wfGetDB( DB_MASTER
);
1259 if (!$this->mTitle
->userIsWatching()) {
1265 if ( $this->mTitle
->userIsWatching() ) {
1271 $this->doRedirect( $this->isRedirect( $text ) );
1275 * @deprecated use Article::doEdit()
1277 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1278 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1279 ( $minor ? EDIT_MINOR
: 0 ) |
1280 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1282 $good = $this->doEdit( $text, $summary, $flags );
1284 $dbw = wfGetDB( DB_MASTER
);
1286 if (!$this->mTitle
->userIsWatching()) {
1292 if ( $this->mTitle
->userIsWatching() ) {
1299 $extraq = ''; // Give extensions a chance to modify URL query on update
1300 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1302 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1310 * Change an existing article or create a new article. Updates RC and all necessary caches,
1311 * optionally via the deferred update array.
1313 * $wgUser must be set before calling this function.
1315 * @param string $text New text
1316 * @param string $summary Edit summary
1317 * @param integer $flags bitfield:
1319 * Article is known or assumed to be non-existent, create a new one
1321 * Article is known or assumed to be pre-existing, update it
1323 * Mark this edit minor, if the user is allowed to do so
1325 * Do not log the change in recentchanges
1327 * Mark the edit a "bot" edit regardless of user rights
1328 * EDIT_DEFER_UPDATES
1329 * Defer some of the updates until the end of index.php
1331 * Fill in blank summaries with generated text where possible
1333 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1334 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1335 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1336 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1337 * to MediaWiki's performance-optimised locking strategy.
1339 * @return bool success
1341 function doEdit( $text, $summary, $flags = 0 ) {
1342 global $wgUser, $wgDBtransactions;
1344 wfProfileIn( __METHOD__
);
1347 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1348 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1350 $flags |
= EDIT_UPDATE
;
1356 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1357 &$summary, $flags & EDIT_MINOR
,
1358 null, null, &$flags ) ) )
1360 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1361 wfProfileOut( __METHOD__
);
1365 # Silently ignore EDIT_MINOR if not allowed
1366 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1367 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1369 $oldtext = $this->getContent();
1370 $oldsize = strlen( $oldtext );
1372 # Provide autosummaries if one is not provided.
1373 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1374 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1376 $text = $this->preSaveTransform( $text );
1377 $newsize = strlen( $text );
1379 $dbw = wfGetDB( DB_MASTER
);
1380 $now = wfTimestampNow();
1382 if ( $flags & EDIT_UPDATE
) {
1383 # Update article, but only if changed.
1385 # Make sure the revision is either completely inserted or not inserted at all
1386 if( !$wgDBtransactions ) {
1387 $userAbort = ignore_user_abort( true );
1393 if ( 0 != strcmp( $text, $oldtext ) ) {
1394 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1395 - (int)$this->isCountable( $oldtext );
1396 $this->mTotalAdjustment
= 0;
1398 $lastRevision = $dbw->selectField(
1399 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1401 if ( !$lastRevision ) {
1402 # Article gone missing
1403 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1404 wfProfileOut( __METHOD__
);
1408 $revision = new Revision( array(
1409 'page' => $this->getId(),
1410 'comment' => $summary,
1411 'minor_edit' => $isminor,
1416 $revisionId = $revision->insertOn( $dbw );
1419 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1422 /* Belated edit conflict! Run away!! */
1426 # Update recentchanges
1427 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1428 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1429 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1432 # Mark as patrolled if the user can do so
1433 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1434 RecentChange
::markPatrolled( $rcid );
1435 PatrolLog
::record( $rcid, true );
1438 $wgUser->incEditCount();
1443 // Keep the same revision ID, but do some updates on it
1444 $revisionId = $this->getRevIdFetched();
1445 // Update page_touched, this is usually implicit in the page update
1446 // Other cache updates are done in onArticleEdit()
1447 $this->mTitle
->invalidateCache();
1450 if( !$wgDBtransactions ) {
1451 ignore_user_abort( $userAbort );
1455 # Invalidate cache of this article and all pages using this article
1456 # as a template. Partly deferred.
1457 Article
::onArticleEdit( $this->mTitle
);
1459 # Update links tables, site stats, etc.
1460 $changed = ( strcmp( $oldtext, $text ) != 0 );
1461 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1464 # Create new article
1466 # Set statistics members
1467 # We work out if it's countable after PST to avoid counter drift
1468 # when articles are created with {{subst:}}
1469 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1470 $this->mTotalAdjustment
= 1;
1474 # Add the page record; stake our claim on this title!
1475 # This will fail with a database query exception if the article already exists
1476 $newid = $this->insertOn( $dbw );
1478 # Save the revision text...
1479 $revision = new Revision( array(
1481 'comment' => $summary,
1482 'minor_edit' => $isminor,
1485 $revisionId = $revision->insertOn( $dbw );
1487 $this->mTitle
->resetArticleID( $newid );
1489 # Update the page record with revision data
1490 $this->updateRevisionOn( $dbw, $revision, 0 );
1492 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1493 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1494 '', strlen( $text ), $revisionId );
1495 # Mark as patrolled if the user can
1496 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1497 RecentChange
::markPatrolled( $rcid );
1498 PatrolLog
::record( $rcid, true );
1501 $wgUser->incEditCount();
1504 # Update links, etc.
1505 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1508 Article
::onArticleCreate( $this->mTitle
);
1510 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1511 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1514 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1518 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1519 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1521 wfProfileOut( __METHOD__
);
1526 * @deprecated wrapper for doRedirect
1528 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1529 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1533 * Output a redirect back to the article.
1534 * This is typically used after an edit.
1536 * @param boolean $noRedir Add redirect=no
1537 * @param string $sectionAnchor section to redirect to, including "#"
1539 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1542 $query = 'redirect=no';
1544 $query .= "&$query";
1548 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1552 * Mark this particular edit as patrolled
1554 function markpatrolled() {
1555 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1556 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1558 # Check RC patrol config. option
1559 if( !$wgUseRCPatrol ) {
1560 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1565 if( !$wgUser->isAllowed( 'patrol' ) ) {
1566 $wgOut->permissionRequired( 'patrol' );
1570 # If we haven't been given an rc_id value, we can't do anything
1571 $rcid = $wgRequest->getVal( 'rcid' );
1573 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1577 # Handle the 'MarkPatrolled' hook
1578 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1582 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1583 # If it's left up to us, check that the user is allowed to patrol this edit
1584 # If the user has the "autopatrol" right, then we'll assume there are no
1585 # other conditions stopping them doing so
1586 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1587 $rc = RecentChange
::newFromId( $rcid );
1588 # Graceful error handling, as we've done before here...
1589 # (If the recent change doesn't exist, then it doesn't matter whether
1590 # the user is allowed to patrol it or not; nothing is going to happen
1591 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1592 # The user made this edit, and can't patrol it
1593 # Tell them so, and then back off
1594 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1595 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1596 $wgOut->returnToMain( false, $return );
1601 # Mark the edit as patrolled
1602 RecentChange
::markPatrolled( $rcid );
1603 PatrolLog
::record( $rcid );
1604 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1607 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1608 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1609 $wgOut->returnToMain( false, $return );
1613 * User-interface handler for the "watch" action
1618 global $wgUser, $wgOut;
1620 if ( $wgUser->isAnon() ) {
1621 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1624 if ( wfReadOnly() ) {
1625 $wgOut->readOnlyPage();
1629 if( $this->doWatch() ) {
1630 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1631 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1633 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1634 $text = wfMsg( 'addedwatchtext', $link );
1635 $wgOut->addWikiText( $text );
1638 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1642 * Add this page to $wgUser's watchlist
1643 * @return bool true on successful watch operation
1645 function doWatch() {
1647 if( $wgUser->isAnon() ) {
1651 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1652 $wgUser->addWatch( $this->mTitle
);
1654 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1661 * User interface handler for the "unwatch" action.
1663 function unwatch() {
1665 global $wgUser, $wgOut;
1667 if ( $wgUser->isAnon() ) {
1668 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1671 if ( wfReadOnly() ) {
1672 $wgOut->readOnlyPage();
1676 if( $this->doUnwatch() ) {
1677 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1678 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1680 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1681 $text = wfMsg( 'removedwatchtext', $link );
1682 $wgOut->addWikiText( $text );
1685 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1689 * Stop watching a page
1690 * @return bool true on successful unwatch
1692 function doUnwatch() {
1694 if( $wgUser->isAnon() ) {
1698 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1699 $wgUser->removeWatch( $this->mTitle
);
1701 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1708 * action=protect handler
1710 function protect() {
1711 $form = new ProtectionForm( $this );
1716 * action=unprotect handler (alias)
1718 function unprotect() {
1723 * Update the article's restriction field, and leave a log entry.
1725 * @param array $limit set of restriction keys
1726 * @param string $reason
1727 * @return bool true on success
1729 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1730 global $wgUser, $wgRestrictionTypes, $wgContLang;
1732 $id = $this->mTitle
->getArticleID();
1733 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1741 // Take this opportunity to purge out expired restrictions
1742 Title
::purgeExpiredRestrictions();
1744 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1745 # we expect a single selection, but the schema allows otherwise.
1747 foreach( $wgRestrictionTypes as $action )
1748 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1750 $current = Article
::flattenRestrictions( $current );
1751 $updated = Article
::flattenRestrictions( $limit );
1753 $changed = ( $current != $updated );
1754 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1755 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1756 $protect = ( $updated != '' );
1758 # If nothing's changed, do nothing
1760 global $wgGroupPermissions;
1761 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1763 $dbw = wfGetDB( DB_MASTER
);
1765 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1767 $expiry_description = '';
1768 if ( $encodedExpiry != 'infinity' ) {
1769 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1772 # Prepare a null revision to be added to the history
1773 $modified = $current != '' && $protect;
1775 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1777 $comment_type = 'unprotectedarticle';
1779 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1781 foreach( $limit as $action => $restrictions ) {
1782 # Check if the group level required to edit also can protect pages
1783 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1784 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1787 $cascade_description = '';
1789 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1793 $comment .= ": $reason";
1795 $comment .= " [$updated]";
1796 if ( $expiry_description && $protect )
1797 $comment .= "$expiry_description";
1799 $comment .= "$cascade_description";
1801 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1802 $nullRevId = $nullRevision->insertOn( $dbw );
1804 # Update restrictions table
1805 foreach( $limit as $action => $restrictions ) {
1806 if ($restrictions != '' ) {
1807 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1808 array( 'pr_page' => $id, 'pr_type' => $action
1809 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1810 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1812 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1813 'pr_type' => $action ), __METHOD__
);
1817 # Update page record
1818 $dbw->update( 'page',
1820 'page_touched' => $dbw->timestamp(),
1821 'page_restrictions' => '',
1822 'page_latest' => $nullRevId
1823 ), array( /* WHERE */
1825 ), 'Article::protect'
1827 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1829 # Update the protection log
1830 $log = new LogPage( 'protect' );
1833 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1835 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1839 } # End "changed" check
1845 * Take an array of page restrictions and flatten it to a string
1846 * suitable for insertion into the page_restrictions field.
1847 * @param array $limit
1851 function flattenRestrictions( $limit ) {
1852 if( !is_array( $limit ) ) {
1853 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1857 foreach( $limit as $action => $restrictions ) {
1858 if( $restrictions != '' ) {
1859 $bits[] = "$action=$restrictions";
1862 return implode( ':', $bits );
1866 * UI entry point for page deletion
1869 global $wgUser, $wgOut, $wgRequest;
1870 $confirm = $wgRequest->wasPosted() &&
1871 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1872 $reason = $wgRequest->getText( 'wpReason' );
1874 # This code desperately needs to be totally rewritten
1877 if( $wgUser->isAllowed( 'delete' ) ) {
1878 if( $wgUser->isBlocked( !$confirm ) ) {
1879 $wgOut->blockedPage();
1883 $wgOut->permissionRequired( 'delete' );
1887 if( wfReadOnly() ) {
1888 $wgOut->readOnlyPage();
1892 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1894 # Better double-check that it hasn't been deleted yet!
1895 $dbw = wfGetDB( DB_MASTER
);
1896 $conds = $this->mTitle
->pageCond();
1897 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1898 if ( $latest === false ) {
1899 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1904 $this->doDelete( $reason );
1905 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1907 } elseif( $this->mTitle
->userIsWatching() ) {
1913 # determine whether this page has earlier revisions
1914 # and insert a warning if it does
1916 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1918 if( count( $authors ) > 1 && !$confirm ) {
1919 $skin=$wgUser->getSkin();
1920 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1923 # If a single user is responsible for all revisions, find out who they are
1924 if ( count( $authors ) == $maxRevisions ) {
1925 // Query bailed out, too many revisions to find out if they're all the same
1926 $authorOfAll = false;
1928 $authorOfAll = reset( $authors );
1929 foreach ( $authors as $author ) {
1930 if ( $authorOfAll != $author ) {
1931 $authorOfAll = false;
1936 # Fetch article text
1937 $rev = Revision
::newFromTitle( $this->mTitle
);
1939 if( !is_null( $rev ) ) {
1940 # if this is a mini-text, we can paste part of it into the deletion reason
1941 $text = $rev->getText();
1943 #if this is empty, an earlier revision may contain "useful" text
1946 $prev = $rev->getPrevious();
1948 $text = $prev->getText();
1953 $length = strlen( $text );
1955 # this should not happen, since it is not possible to store an empty, new
1956 # page. Let's insert a standard text in case it does, though
1957 if( $length == 0 && $reason === '' ) {
1958 $reason = wfMsgForContent( 'exblank' );
1961 if( $reason === '' ) {
1962 # comment field=255, let's grep the first 150 to have some user
1965 $text = $wgContLang->truncate( $text, 150, '...' );
1967 # let's strip out newlines
1968 $text = preg_replace( "/[\n\r]/", '', $text );
1971 if( $authorOfAll === false ) {
1972 $reason = wfMsgForContent( 'excontent', $text );
1974 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1977 $reason = wfMsgForContent( 'exbeforeblank', $text );
1982 return $this->confirmDelete( '', $reason );
1986 * Get the last N authors
1987 * @param int $num Number of revisions to get
1988 * @param string $revLatest The latest rev_id, selected from the master (optional)
1989 * @return array Array of authors, duplicates not removed
1991 function getLastNAuthors( $num, $revLatest = 0 ) {
1992 wfProfileIn( __METHOD__
);
1994 // First try the slave
1995 // If that doesn't have the latest revision, try the master
1997 $db = wfGetDB( DB_SLAVE
);
1999 $res = $db->select( array( 'page', 'revision' ),
2000 array( 'rev_id', 'rev_user_text' ),
2002 'page_namespace' => $this->mTitle
->getNamespace(),
2003 'page_title' => $this->mTitle
->getDBkey(),
2004 'rev_page = page_id'
2005 ), __METHOD__
, $this->getSelectOptions( array(
2006 'ORDER BY' => 'rev_timestamp DESC',
2011 wfProfileOut( __METHOD__
);
2014 $row = $db->fetchObject( $res );
2015 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2016 $db = wfGetDB( DB_MASTER
);
2021 } while ( $continue );
2023 $authors = array( $row->rev_user_text
);
2024 while ( $row = $db->fetchObject( $res ) ) {
2025 $authors[] = $row->rev_user_text
;
2027 wfProfileOut( __METHOD__
);
2032 * Output deletion confirmation dialog
2034 function confirmDelete( $par, $reason ) {
2035 global $wgOut, $wgUser;
2037 wfDebug( "Article::confirmDelete\n" );
2039 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
2040 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
2041 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2042 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
2044 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
2046 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
2047 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
2048 $token = htmlspecialchars( $wgUser->editToken() );
2049 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
2052 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2056 <label for='wpReason'>{$delcom}:</label>
2059 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2069 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2073 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2076 $wgOut->returnToMain( false );
2078 $this->showLogExtract( $wgOut );
2083 * Show relevant lines from the deletion log
2085 function showLogExtract( $out ) {
2086 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2087 $logViewer = new LogViewer(
2090 array( 'page' => $this->mTitle
->getPrefixedText(),
2091 'type' => 'delete' ) ) ) );
2092 $logViewer->showList( $out );
2097 * Perform a deletion and output success or failure messages
2099 function doDelete( $reason ) {
2100 global $wgOut, $wgUser;
2101 wfDebug( __METHOD__
."\n" );
2103 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2104 if ( $this->doDeleteArticle( $reason ) ) {
2105 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2107 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2108 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2110 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2111 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2113 $wgOut->addWikiText( $text );
2114 $wgOut->returnToMain( false );
2115 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2117 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2123 * Back-end article deletion
2124 * Deletes the article with database consistency, writes logs, purges caches
2127 function doDeleteArticle( $reason ) {
2128 global $wgUseSquid, $wgDeferredUpdateList;
2129 global $wgUseTrackbacks;
2131 wfDebug( __METHOD__
."\n" );
2133 $dbw = wfGetDB( DB_MASTER
);
2134 $ns = $this->mTitle
->getNamespace();
2135 $t = $this->mTitle
->getDBkey();
2136 $id = $this->mTitle
->getArticleID();
2138 if ( $t == '' ||
$id == 0 ) {
2142 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2143 array_push( $wgDeferredUpdateList, $u );
2145 // For now, shunt the revision data into the archive table.
2146 // Text is *not* removed from the text table; bulk storage
2147 // is left intact to avoid breaking block-compression or
2148 // immutable storage schemes.
2150 // For backwards compatibility, note that some older archive
2151 // table entries will have ar_text and ar_flags fields still.
2153 // In the future, we may keep revisions and mark them with
2154 // the rev_deleted field, which is reserved for this purpose.
2155 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2157 'ar_namespace' => 'page_namespace',
2158 'ar_title' => 'page_title',
2159 'ar_comment' => 'rev_comment',
2160 'ar_user' => 'rev_user',
2161 'ar_user_text' => 'rev_user_text',
2162 'ar_timestamp' => 'rev_timestamp',
2163 'ar_minor_edit' => 'rev_minor_edit',
2164 'ar_rev_id' => 'rev_id',
2165 'ar_text_id' => 'rev_text_id',
2166 'ar_text' => '\'\'', // Be explicit to appease
2167 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2168 'ar_len' => 'rev_len',
2169 'ar_page_id' => 'page_id',
2172 'page_id = rev_page'
2176 # Delete restrictions for it
2177 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2179 # Now that it's safely backed up, delete it
2180 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2182 # If using cascading deletes, we can skip some explicit deletes
2183 if ( !$dbw->cascadingDeletes() ) {
2185 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2187 if ($wgUseTrackbacks)
2188 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2190 # Delete outgoing links
2191 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2192 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2193 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2194 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2195 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2196 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2197 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2200 # If using cleanup triggers, we can skip some manual deletes
2201 if ( !$dbw->cleanupTriggers() ) {
2203 # Clean up recentchanges entries...
2204 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2208 Article
::onArticleDelete( $this->mTitle
);
2211 $log = new LogPage( 'delete' );
2212 $log->addEntry( 'delete', $this->mTitle
, $reason );
2214 # Clear the cached article id so the interface doesn't act like we exist
2215 $this->mTitle
->resetArticleID( 0 );
2216 $this->mTitle
->mArticleID
= 0;
2221 * Roll back the most recent consecutive set of edits to a page
2222 * from the same user; fails if there are no eligible edits to
2223 * roll back to, e.g. user is the sole contributor
2225 * @param string $fromP - Name of the user whose edits to rollback.
2226 * @param string $summary - Custom summary. Set to default summary if empty.
2227 * @param string $token - Rollback token.
2228 * @param bool $bot - If true, mark all reverted edits as bot.
2230 * @param array $resultDetails contains result-specific dict of additional values
2231 * ALREADY_ROLLED : 'current' (rev)
2232 * SUCCESS : 'summary' (str), 'current' (rev), 'target' (rev)
2234 * @return self::SUCCESS on succes, self::* on failure
2236 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2237 global $wgUser, $wgUseRCPatrol;
2238 $resultDetails = null;
2240 if( $wgUser->isAllowed( 'rollback' ) ) {
2241 if( $wgUser->isBlocked() ) {
2242 return self
::BLOCKED
;
2245 return self
::PERM_DENIED
;
2248 if ( wfReadOnly() ) {
2249 return self
::READONLY
;
2251 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2252 return self
::BAD_TOKEN
;
2254 $dbw = wfGetDB( DB_MASTER
);
2256 # Get the last editor
2257 $current = Revision
::newFromTitle( $this->mTitle
);
2258 if( is_null( $current ) ) {
2259 # Something wrong... no page?
2260 return self
::BAD_TITLE
;
2263 $from = str_replace( '_', ' ', $fromP );
2264 if( $from != $current->getUserText() ) {
2265 $resultDetails = array( 'current' => $current );
2266 return self
::ALREADY_ROLLED
;
2269 # Get the last edit not by this guy
2270 $user = intval( $current->getUser() );
2271 $user_text = $dbw->addQuotes( $current->getUserText() );
2272 $s = $dbw->selectRow( 'revision',
2273 array( 'rev_id', 'rev_timestamp' ),
2275 'rev_page' => $current->getPage(),
2276 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2279 'USE INDEX' => 'page_timestamp',
2280 'ORDER BY' => 'rev_timestamp DESC' )
2282 if( $s === false ) {
2284 return self
::ONLY_AUTHOR
;
2289 # Mark all reverted edits as bot
2292 if ( $wgUseRCPatrol ) {
2293 # Mark all reverted edits as patrolled
2294 $set['rc_patrolled'] = 1;
2298 $dbw->update( 'recentchanges', $set,
2300 'rc_cur_id' => $current->getPage(),
2301 'rc_user_text' => $current->getUserText(),
2302 "rc_timestamp > '{$s->rev_timestamp}'",
2307 # Get the edit summary
2308 $target = Revision
::newFromId( $s->rev_id
);
2309 if( empty( $summary ) )
2310 $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2313 $flags = EDIT_UPDATE | EDIT_MINOR
;
2315 $flags |
= EDIT_FORCE_BOT
;
2316 $this->doEdit( $target->getText(), $summary, $flags );
2318 $resultDetails = array(
2319 'summary' => $summary,
2320 'current' => $current,
2321 'target' => $target,
2323 return self
::SUCCESS
;
2327 * User interface for rollback operations
2329 function rollback() {
2330 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2333 $result = $this->doRollback(
2334 $wgRequest->getVal( 'from' ),
2335 $wgRequest->getText( 'summary' ),
2336 $wgRequest->getVal( 'token' ),
2337 $wgRequest->getBool( 'bot' ),
2343 $wgOut->blockedPage();
2345 case self
::PERM_DENIED
:
2346 $wgOut->permissionRequired( 'rollback' );
2348 case self
::READONLY
:
2349 $wgOut->readOnlyPage( $this->getContent() );
2351 case self
::BAD_TOKEN
:
2352 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2353 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2355 case self
::BAD_TITLE
:
2356 $wgOut->addHtml( wfMsg( 'notanarticle' ) );
2358 case self
::ALREADY_ROLLED
:
2359 $current = $details['current'];
2360 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2361 $wgOut->addWikiText(
2362 wfMsg( 'alreadyrolled',
2363 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2364 htmlspecialchars( $wgRequest->getVal( 'from' ) ),
2365 htmlspecialchars( $current->getUserText() )
2368 if( $current->getComment() != '' ) {
2369 $wgOut->addHtml( wfMsg( 'editcomment',
2370 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2373 case self
::ONLY_AUTHOR
:
2374 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2375 $wgOut->addHtml( wfMsg( 'cantrollback' ) );
2378 $current = $details['current'];
2379 $target = $details['target'];
2380 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2381 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2382 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2383 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2384 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2385 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2386 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2387 $wgOut->returnToMain( false, $this->mTitle
);
2390 throw new MWException( __METHOD__
. ": Unknown return value `{$result}`" );
2397 * Do standard deferred updates after page view
2400 function viewUpdates() {
2401 global $wgDeferredUpdateList;
2403 if ( 0 != $this->getID() ) {
2404 global $wgDisableCounters;
2405 if( !$wgDisableCounters ) {
2406 Article
::incViewCount( $this->getID() );
2407 $u = new SiteStatsUpdate( 1, 0, 0 );
2408 array_push( $wgDeferredUpdateList, $u );
2412 # Update newtalk / watchlist notification status
2414 $wgUser->clearNotification( $this->mTitle
);
2418 * Do standard deferred updates after page edit.
2419 * Update links tables, site stats, search index and message cache.
2420 * Every 1000th edit, prune the recent changes table.
2423 * @param $text New text of the article
2424 * @param $summary Edit summary
2425 * @param $minoredit Minor edit
2426 * @param $timestamp_of_pagechange Timestamp associated with the page change
2427 * @param $newid rev_id value of the new revision
2428 * @param $changed Whether or not the content actually changed
2430 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2431 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2433 wfProfileIn( __METHOD__
);
2436 $options = new ParserOptions
;
2437 $options->setTidy(true);
2438 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2440 # Save it to the parser cache
2441 $parserCache =& ParserCache
::singleton();
2442 $parserCache->save( $poutput, $this, $wgUser );
2444 # Update the links tables
2445 $u = new LinksUpdate( $this->mTitle
, $poutput );
2448 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2449 if ( 0 == mt_rand( 0, 99 ) ) {
2450 // Flush old entries from the `recentchanges` table; we do this on
2451 // random requests so as to avoid an increase in writes for no good reason
2453 $dbw = wfGetDB( DB_MASTER
);
2454 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2455 $recentchanges = $dbw->tableName( 'recentchanges' );
2456 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2457 $dbw->query( $sql );
2461 $id = $this->getID();
2462 $title = $this->mTitle
->getPrefixedDBkey();
2463 $shortTitle = $this->mTitle
->getDBkey();
2466 wfProfileOut( __METHOD__
);
2470 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2471 array_push( $wgDeferredUpdateList, $u );
2472 $u = new SearchUpdate( $id, $title, $text );
2473 array_push( $wgDeferredUpdateList, $u );
2475 # If this is another user's talk page, update newtalk
2476 # Don't do this if $changed = false otherwise some idiot can null-edit a
2477 # load of user talk pages and piss people off, nor if it's a minor edit
2478 # by a properly-flagged bot.
2479 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2480 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2481 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2482 $other = User
::newFromName( $shortTitle );
2483 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2484 // An anonymous user
2485 $other = new User();
2486 $other->setName( $shortTitle );
2489 $other->setNewtalk( true );
2494 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2495 $wgMessageCache->replace( $shortTitle, $text );
2498 wfProfileOut( __METHOD__
);
2502 * Perform article updates on a special page creation.
2504 * @param Revision $rev
2506 * @todo This is a shitty interface function. Kill it and replace the
2507 * other shitty functions like editUpdates and such so it's not needed
2510 function createUpdates( $rev ) {
2511 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2512 $this->mTotalAdjustment
= 1;
2513 $this->editUpdates( $rev->getText(), $rev->getComment(),
2514 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2518 * Generate the navigation links when browsing through an article revisions
2519 * It shows the information as:
2520 * Revision as of \<date\>; view current revision
2521 * \<- Previous version | Next Version -\>
2524 * @param string $oldid Revision ID of this article revision
2526 function setOldSubtitle( $oldid=0 ) {
2527 global $wgLang, $wgOut, $wgUser;
2529 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2533 $revision = Revision
::newFromId( $oldid );
2535 $current = ( $oldid == $this->mLatest
);
2536 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2537 $sk = $wgUser->getSkin();
2539 ?
wfMsg( 'currentrevisionlink' )
2540 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2543 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2544 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2546 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2547 : wfMsg( 'previousrevision' );
2549 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2551 $nextlink = $current
2552 ?
wfMsg( 'nextrevision' )
2553 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2554 $nextdiff = $current
2556 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2558 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2559 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2561 $m = wfMsg( 'revision-info-current' );
2562 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2563 ?
'revision-info-current'
2566 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2567 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2568 $wgOut->setSubtitle( $r );
2572 * This function is called right before saving the wikitext,
2573 * so we can do things like signatures and links-in-context.
2575 * @param string $text
2577 function preSaveTransform( $text ) {
2578 global $wgParser, $wgUser;
2579 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2582 /* Caching functions */
2585 * checkLastModified returns true if it has taken care of all
2586 * output to the client that is necessary for this request.
2587 * (that is, it has sent a cached version of the page)
2589 function tryFileCache() {
2590 static $called = false;
2592 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2596 if($this->isFileCacheable()) {
2597 $touched = $this->mTouched
;
2598 $cache = new HTMLFileCache( $this->mTitle
);
2599 if($cache->isFileCacheGood( $touched )) {
2600 wfDebug( "Article::tryFileCache(): about to load file\n" );
2601 $cache->loadFromFileCache();
2604 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2605 ob_start( array(&$cache, 'saveToFileCache' ) );
2608 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2613 * Check if the page can be cached
2616 function isFileCacheable() {
2617 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2618 $action = $wgRequest->getVal( 'action' );
2619 $oldid = $wgRequest->getVal( 'oldid' );
2620 $diff = $wgRequest->getVal( 'diff' );
2621 $redirect = $wgRequest->getVal( 'redirect' );
2622 $printable = $wgRequest->getVal( 'printable' );
2623 $page = $wgRequest->getVal( 'page' );
2625 //check for non-standard user language; this covers uselang,
2626 //and extensions for auto-detecting user language.
2627 $ulang = $wgLang->getCode();
2628 $clang = $wgContLang->getCode();
2630 $cacheable = $wgUseFileCache
2631 && (!$wgShowIPinHeader)
2632 && ($this->getID() != 0)
2633 && ($wgUser->isAnon())
2634 && (!$wgUser->getNewtalk())
2635 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2636 && (empty( $action ) ||
$action == 'view')
2639 && (!isset($redirect))
2640 && (!isset($printable))
2642 && (!$this->mRedirectedFrom
)
2643 && ($ulang === $clang);
2646 //extension may have reason to disable file caching on some pages.
2647 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2654 * Loads page_touched and returns a value indicating if it should be used
2657 function checkTouched() {
2658 if( !$this->mDataLoaded
) {
2659 $this->loadPageData();
2661 return !$this->mIsRedirect
;
2665 * Get the page_touched field
2667 function getTouched() {
2668 # Ensure that page data has been loaded
2669 if( !$this->mDataLoaded
) {
2670 $this->loadPageData();
2672 return $this->mTouched
;
2676 * Get the page_latest field
2678 function getLatest() {
2679 if ( !$this->mDataLoaded
) {
2680 $this->loadPageData();
2682 return $this->mLatest
;
2686 * Edit an article without doing all that other stuff
2687 * The article must already exist; link tables etc
2688 * are not updated, caches are not flushed.
2690 * @param string $text text submitted
2691 * @param string $comment comment submitted
2692 * @param bool $minor whereas it's a minor modification
2694 function quickEdit( $text, $comment = '', $minor = 0 ) {
2695 wfProfileIn( __METHOD__
);
2697 $dbw = wfGetDB( DB_MASTER
);
2699 $revision = new Revision( array(
2700 'page' => $this->getId(),
2702 'comment' => $comment,
2703 'minor_edit' => $minor ?
1 : 0,
2705 $revision->insertOn( $dbw );
2706 $this->updateRevisionOn( $dbw, $revision );
2709 wfProfileOut( __METHOD__
);
2713 * Used to increment the view counter
2716 * @param integer $id article id
2718 function incViewCount( $id ) {
2719 $id = intval( $id );
2720 global $wgHitcounterUpdateFreq, $wgDBtype;
2722 $dbw = wfGetDB( DB_MASTER
);
2723 $pageTable = $dbw->tableName( 'page' );
2724 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2725 $acchitsTable = $dbw->tableName( 'acchits' );
2727 if( $wgHitcounterUpdateFreq <= 1 ) {
2728 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2732 # Not important enough to warrant an error page in case of failure
2733 $oldignore = $dbw->ignoreErrors( true );
2735 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2737 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2738 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2739 # Most of the time (or on SQL errors), skip row count check
2740 $dbw->ignoreErrors( $oldignore );
2744 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2745 $row = $dbw->fetchObject( $res );
2746 $rown = intval( $row->n
);
2747 if( $rown >= $wgHitcounterUpdateFreq ){
2748 wfProfileIn( 'Article::incViewCount-collect' );
2749 $old_user_abort = ignore_user_abort( true );
2751 if ($wgDBtype == 'mysql')
2752 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2753 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2754 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2755 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2757 $dbw->query("DELETE FROM $hitcounterTable");
2758 if ($wgDBtype == 'mysql') {
2759 $dbw->query('UNLOCK TABLES');
2760 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2761 'WHERE page_id = hc_id');
2764 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2765 "FROM $acchitsTable WHERE page_id = hc_id");
2767 $dbw->query("DROP TABLE $acchitsTable");
2769 ignore_user_abort( $old_user_abort );
2770 wfProfileOut( 'Article::incViewCount-collect' );
2772 $dbw->ignoreErrors( $oldignore );
2776 * The onArticle*() functions are supposed to be a kind of hooks
2777 * which should be called whenever any of the specified actions
2780 * This is a good place to put code to clear caches, for instance.
2782 * This is called on page move and undelete, as well as edit
2784 * @param $title_obj a title object
2787 static function onArticleCreate($title) {
2788 # The talk page isn't in the regular link tables, so we need to update manually:
2789 if ( $title->isTalkPage() ) {
2790 $other = $title->getSubjectPage();
2792 $other = $title->getTalkPage();
2794 $other->invalidateCache();
2795 $other->purgeSquid();
2797 $title->touchLinks();
2798 $title->purgeSquid();
2801 static function onArticleDelete( $title ) {
2802 global $wgUseFileCache, $wgMessageCache;
2804 $title->touchLinks();
2805 $title->purgeSquid();
2808 if ( $wgUseFileCache ) {
2809 $cm = new HTMLFileCache( $title );
2810 @unlink
( $cm->fileCacheName() );
2813 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2814 $wgMessageCache->replace( $title->getDBkey(), false );
2819 * Purge caches on page update etc
2821 static function onArticleEdit( $title ) {
2822 global $wgDeferredUpdateList, $wgUseFileCache;
2824 // Invalidate caches of articles which include this page
2825 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2826 $wgDeferredUpdateList[] = $update;
2828 # Purge squid for this page only
2829 $title->purgeSquid();
2832 if ( $wgUseFileCache ) {
2833 $cm = new HTMLFileCache( $title );
2834 @unlink
( $cm->fileCacheName() );
2841 * Info about this page
2842 * Called for ?action=info when $wgAllowPageInfo is on.
2847 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2849 if ( !$wgAllowPageInfo ) {
2850 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2854 $page = $this->mTitle
->getSubjectPage();
2856 $wgOut->setPagetitle( $page->getPrefixedText() );
2857 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2858 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
2860 if( !$this->mTitle
->exists() ) {
2861 $wgOut->addHtml( '<div class="noarticletext">' );
2862 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2863 // This doesn't quite make sense; the user is asking for
2864 // information about the _page_, not the message... -- RC
2865 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
2867 $msg = $wgUser->isLoggedIn()
2869 : 'noarticletextanon';
2870 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
2872 $wgOut->addHtml( '</div>' );
2874 $dbr = wfGetDB( DB_SLAVE
);
2876 'wl_title' => $page->getDBkey(),
2877 'wl_namespace' => $page->getNamespace() );
2878 $numwatchers = $dbr->selectField(
2883 $this->getSelectOptions() );
2885 $pageInfo = $this->pageCountInfo( $page );
2886 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2888 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2889 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2891 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2893 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2895 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2897 $wgOut->addHTML( '</ul>' );
2903 * Return the total number of edits and number of unique editors
2904 * on a given page. If page does not exist, returns false.
2906 * @param Title $title
2910 function pageCountInfo( $title ) {
2911 $id = $title->getArticleId();
2916 $dbr = wfGetDB( DB_SLAVE
);
2918 $rev_clause = array( 'rev_page' => $id );
2920 $edits = $dbr->selectField(
2925 $this->getSelectOptions() );
2927 $authors = $dbr->selectField(
2929 'COUNT(DISTINCT rev_user_text)',
2932 $this->getSelectOptions() );
2934 return array( 'edits' => $edits, 'authors' => $authors );
2938 * Return a list of templates used by this article.
2939 * Uses the templatelinks table
2941 * @return array Array of Title objects
2943 function getUsedTemplates() {
2945 $id = $this->mTitle
->getArticleID();
2950 $dbr = wfGetDB( DB_SLAVE
);
2951 $res = $dbr->select( array( 'templatelinks' ),
2952 array( 'tl_namespace', 'tl_title' ),
2953 array( 'tl_from' => $id ),
2954 'Article:getUsedTemplates' );
2955 if ( false !== $res ) {
2956 if ( $dbr->numRows( $res ) ) {
2957 while ( $row = $dbr->fetchObject( $res ) ) {
2958 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2962 $dbr->freeResult( $res );
2967 * Return an auto-generated summary if the text provided is a redirect.
2969 * @param string $text The wikitext to check
2970 * @return string '' or an appropriate summary
2972 public static function getRedirectAutosummary( $text ) {
2973 $rt = Title
::newFromRedirect( $text );
2974 if( is_object( $rt ) )
2975 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2981 * Return an auto-generated summary if the new text is much shorter than
2984 * @param string $oldtext The previous text of the page
2985 * @param string $text The submitted text of the page
2986 * @return string An appropriate autosummary, or an empty string.
2988 public static function getBlankingAutosummary( $oldtext, $text ) {
2989 if ($oldtext!='' && $text=='') {
2990 return wfMsgForContent('autosumm-blank');
2991 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2992 #Removing more than 90% of the article
2994 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2995 return wfMsgForContent('autosumm-replace', $truncatedtext);
3002 * Return an applicable autosummary if one exists for the given edit.
3003 * @param string $oldtext The previous text of the page.
3004 * @param string $newtext The submitted text of the page.
3005 * @param bitmask $flags A bitmask of flags submitted for the edit.
3006 * @return string An appropriate autosummary, or an empty string.
3008 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3010 # This code is UGLY UGLY UGLY.
3011 # Somebody PLEASE come up with a more elegant way to do it.
3013 #Redirect autosummaries
3014 $summary = self
::getRedirectAutosummary( $newtext );
3019 #Blanking autosummaries
3020 if (!($flags & EDIT_NEW
))
3021 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3026 #New page autosummaries
3027 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3028 #If they're making a new article, give its text, truncated, in the summary.
3030 $truncatedtext = $wgContLang->truncate(
3031 str_replace("\n", ' ', $newtext),
3032 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3034 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3044 * Add the primary page-view wikitext to the output buffer
3045 * Saves the text into the parser cache if possible.
3046 * Updates templatelinks if it is out of date.
3048 * @param string $text
3049 * @param bool $cache
3051 public function outputWikiText( $text, $cache = true ) {
3052 global $wgParser, $wgUser, $wgOut;
3054 $popts = $wgOut->parserOptions();
3055 $popts->setTidy(true);
3056 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3057 $popts, true, true, $this->getRevIdFetched() );
3058 $popts->setTidy(false);
3059 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3060 $parserCache =& ParserCache
::singleton();
3061 $parserCache->save( $parserOutput, $this, $wgUser );
3064 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3065 // templatelinks table may have become out of sync,
3066 // especially if using variable-based transclusions.
3067 // For paranoia, check if things have changed and if
3068 // so apply updates to the database. This will ensure
3069 // that cascaded protections apply as soon as the changes
3072 # Get templates from templatelinks
3073 $id = $this->mTitle
->getArticleID();
3075 $tlTemplates = array();
3077 $dbr = wfGetDB( DB_SLAVE
);
3078 $res = $dbr->select( array( 'templatelinks' ),
3079 array( 'tl_namespace', 'tl_title' ),
3080 array( 'tl_from' => $id ),
3081 'Article:getUsedTemplates' );
3085 if ( false !== $res ) {
3086 if ( $dbr->numRows( $res ) ) {
3087 while ( $row = $dbr->fetchObject( $res ) ) {
3088 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3093 # Get templates from parser output.
3094 $poTemplates_allns = $parserOutput->getTemplates();
3096 $poTemplates = array ();
3097 foreach ( $poTemplates_allns as $ns_templates ) {
3098 $poTemplates = array_merge( $poTemplates, $ns_templates );
3102 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3104 if ( count( $templates_diff ) > 0 ) {
3105 # Whee, link updates time.
3106 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3108 $dbw = wfGetDb( DB_MASTER
);
3117 $wgOut->addParserOutput( $parserOutput );