8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
14 * @internal documentation reviewed 15 Mar 2010
20 var $mComment = ''; // !<
22 var $mContentLoaded = false; // !<
23 var $mCounter = -1; // !< Not loaded
24 var $mCurID = -1; // !< Not loaded
25 var $mDataLoaded = false; // !<
26 var $mForUpdate = false; // !<
27 var $mGoodAdjustment = 0; // !<
28 var $mIsRedirect = false; // !<
29 var $mLatest = false; // !<
30 var $mMinorEdit; // !<
32 var $mPreparedEdit = false; // !< Title object if set
33 var $mRedirectedFrom = null; // !< Title object if set
34 var $mRedirectTarget = null; // !< Title object if set
35 var $mRedirectUrl = false; // !<
36 var $mRevIdFetched = 0; // !<
37 var $mRevision; // !< Revision object if set
38 var $mTimestamp = ''; // !<
39 var $mTitle; // !< Title object
40 var $mTotalAdjustment = 0; // !<
41 var $mTouched = '19700101000000'; // !<
42 var $mUser = -1; // !< Not loaded
43 var $mUserText = ''; // !< username from Revision if set
44 var $mParserOptions; // !< ParserOptions object
45 var $mParserOutput; // !< ParserCache object if set
49 * Constructor and clear the article
50 * @param $title Reference to a Title object.
51 * @param $oldId Integer revision ID, null to fetch from request, zero for current
53 public function __construct( Title
$title, $oldId = null ) {
54 $this->mTitle
=& $title;
55 $this->mOldId
= $oldId;
59 * Constructor from an article article
60 * @param $id The article ID to load
62 public static function newFromID( $id ) {
63 $t = Title
::newFromID( $id );
64 # FIXME: doesn't inherit right
65 return $t == null ?
null : new self( $t );
66 # return $t == null ? null : new static( $t ); // PHP 5.3
70 * Tell the page view functions that this view was redirected
71 * from another page on the wiki.
72 * @param $from Title object.
74 public function setRedirectedFrom( Title
$from ) {
75 $this->mRedirectedFrom
= $from;
79 * If this page is a redirect, get its target
81 * The target will be fetched from the redirect table if possible.
82 * If this page doesn't have an entry there, call insertRedirect()
83 * @return mixed Title object, or null if this page is not a redirect
85 public function getRedirectTarget() {
86 if ( !$this->mTitle ||
!$this->mTitle
->isRedirect() )
88 if ( !is_null( $this->mRedirectTarget
) )
89 return $this->mRedirectTarget
;
90 # Query the redirect table
91 $dbr = wfGetDB( DB_SLAVE
);
92 $row = $dbr->selectRow( 'redirect',
93 array( 'rd_namespace', 'rd_title' ),
94 array( 'rd_from' => $this->getID() ),
98 return $this->mRedirectTarget
= Title
::makeTitle( $row->rd_namespace
, $row->rd_title
);
100 # This page doesn't have an entry in the redirect table
101 return $this->mRedirectTarget
= $this->insertRedirect();
105 * Insert an entry for this page into the redirect table.
107 * Don't call this function directly unless you know what you're doing.
108 * @return Title object
110 public function insertRedirect() {
111 $retval = Title
::newFromRedirect( $this->getContent() );
115 $dbw = wfGetDB( DB_MASTER
);
116 $dbw->replace( 'redirect', array( 'rd_from' ),
118 'rd_from' => $this->getID(),
119 'rd_namespace' => $retval->getNamespace(),
120 'rd_title' => $retval->getDBkey()
128 * Get the Title object this page redirects to
130 * @return mixed false, Title of in-wiki target, or string with URL
132 public function followRedirect() {
133 $text = $this->getContent();
134 return $this->followRedirectText( $text );
138 * Get the Title object this text redirects to
140 * @param $text string article content containing redirect info
141 * @return mixed false, Title of in-wiki target, or string with URL
143 public function followRedirectText( $text ) {
144 $rt = Title
::newFromRedirectRecurse( $text ); // recurse through to only get the final target
145 # process if title object is valid and not special:userlogout
147 if ( $rt->getInterwiki() != '' ) {
148 if ( $rt->isLocal() ) {
149 // Offsite wikis need an HTTP redirect.
151 // This can be hard to reverse and may produce loops,
152 // so they may be disabled in the site configuration.
153 $source = $this->mTitle
->getFullURL( 'redirect=no' );
154 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
157 if ( $rt->getNamespace() == NS_SPECIAL
) {
158 // Gotta handle redirects to special pages differently:
159 // Fill the HTTP response "Location" header and ignore
160 // the rest of the page we're on.
162 // This can be hard to reverse, so they may be disabled.
163 if ( $rt->isSpecial( 'Userlogout' ) ) {
166 return $rt->getFullURL();
172 // No or invalid redirect
177 * get the title object of the article
178 * @return Title object of current title
180 public function getTitle() {
181 return $this->mTitle
;
188 public function clear() {
189 $this->mDataLoaded
= false;
190 $this->mContentLoaded
= false;
192 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
193 $this->mRedirectedFrom
= null; # Title object if set
194 $this->mRedirectTarget
= null; # Title object if set
196 $this->mTimestamp
= $this->mComment
= '';
197 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
198 $this->mTouched
= '19700101000000';
199 $this->mForUpdate
= false;
200 $this->mIsRedirect
= false;
201 $this->mRevIdFetched
= 0;
202 $this->mRedirectUrl
= false;
203 $this->mLatest
= false;
204 $this->mPreparedEdit
= false;
208 * Note that getContent/loadContent do not follow redirects anymore.
209 * If you need to fetch redirectable content easily, try
210 * the shortcut in Article::followContent()
212 * @return Return the text of this revision
214 public function getContent() {
215 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
216 wfProfileIn( __METHOD__
);
217 if ( $this->getID() === 0 ) {
218 # If this is a MediaWiki:x message, then load the messages
219 # and return the message value for x.
220 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
221 # If this is a system message, get the default text.
222 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
223 $wgMessageCache->loadAllMessages( $lang );
224 $text = wfMsgGetKey( $message, false, $lang, false );
225 if ( wfEmptyMsg( $message, $text ) )
228 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
230 wfProfileOut( __METHOD__
);
233 $this->loadContent();
234 wfProfileOut( __METHOD__
);
235 return $this->mContent
;
240 * Get the text of the current revision. No side-effects...
242 * @return Return the text of the current revision
244 public function getRawText() {
245 // Check process cache for current revision
246 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
247 return $this->mContent
;
249 $rev = Revision
::newFromTitle( $this->mTitle
);
250 $text = $rev ?
$rev->getRawText() : false;
255 * This function returns the text of a section, specified by a number ($section).
256 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
257 * the first section before any such heading (section 0).
259 * If a section contains subsections, these are also returned.
261 * @param $text String: text to look in
262 * @param $section Integer: section number
263 * @return string text of the requested section
266 public function getSection( $text, $section ) {
268 return $wgParser->getSection( $text, $section );
272 * Get the text that needs to be saved in order to undo all revisions
273 * between $undo and $undoafter. Revisions must belong to the same page,
274 * must exist and must not be deleted
275 * @param $undo Revision
276 * @param $undoafter Revision Must be an earlier revision than $undo
277 * @return mixed string on success, false on failure
279 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
280 $undo_text = $undo->getText();
281 $undoafter_text = $undoafter->getText();
282 $cur_text = $this->getContent();
283 if ( $cur_text == $undo_text ) {
284 # No use doing a merge if it's just a straight revert.
285 return $undoafter_text;
288 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
294 * @return int The oldid of the article that is to be shown, 0 for the
297 public function getOldID() {
298 if ( is_null( $this->mOldId
) ) {
299 $this->mOldId
= $this->getOldIDFromRequest();
301 return $this->mOldId
;
305 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
307 * @return int The old id for the request
309 public function getOldIDFromRequest() {
311 $this->mRedirectUrl
= false;
312 $oldid = $wgRequest->getVal( 'oldid' );
313 if ( isset( $oldid ) ) {
314 $oldid = intval( $oldid );
315 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
316 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
320 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
322 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
323 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
336 * Load the revision (including text) into this object
338 function loadContent() {
339 if ( $this->mContentLoaded
) return;
340 wfProfileIn( __METHOD__
);
342 $oldid = $this->getOldID();
343 # Pre-fill content with error message so that if something
344 # fails we'll have something telling us what we intended.
345 $this->mOldId
= $oldid;
346 $this->fetchContent( $oldid );
347 wfProfileOut( __METHOD__
);
352 * Fetch a page record with the given conditions
353 * @param $dbr Database object
354 * @param $conditions Array
355 * @return mixed Database result resource, or false on failure
357 protected function pageData( $dbr, $conditions ) {
371 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
372 $row = $dbr->selectRow(
378 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
383 * Fetch a page record matching the Title object's namespace and title
384 * using a sanitized title string
386 * @param $dbr Database object
387 * @param $title Title object
388 * @return mixed Database result resource, or false on failure
390 public function pageDataFromTitle( $dbr, $title ) {
391 return $this->pageData( $dbr, array(
392 'page_namespace' => $title->getNamespace(),
393 'page_title' => $title->getDBkey() ) );
397 * Fetch a page record matching the requested ID
399 * @param $dbr Database
402 protected function pageDataFromId( $dbr, $id ) {
403 return $this->pageData( $dbr, array( 'page_id' => $id ) );
407 * Set the general counter, title etc data loaded from
410 * @param $data Database row object or "fromdb"
412 public function loadPageData( $data = 'fromdb' ) {
413 if ( $data === 'fromdb' ) {
414 $dbr = wfGetDB( DB_MASTER
);
415 $data = $this->pageDataFromId( $dbr, $this->getId() );
418 $lc = LinkCache
::singleton();
420 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
422 $this->mTitle
->mArticleID
= intval( $data->page_id
);
424 # Old-fashioned restrictions
425 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
427 $this->mCounter
= intval( $data->page_counter
);
428 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
429 $this->mIsRedirect
= intval( $data->page_is_redirect
);
430 $this->mLatest
= intval( $data->page_latest
);
432 if ( is_object( $this->mTitle
) ) {
433 $lc->addBadLinkObj( $this->mTitle
);
435 $this->mTitle
->mArticleID
= 0;
438 $this->mDataLoaded
= true;
442 * Get text of an article from database
443 * Does *NOT* follow redirects.
445 * @param $oldid Int: 0 for whatever the latest revision is
446 * @return mixed string containing article contents, or false if null
448 function fetchContent( $oldid = 0 ) {
449 if ( $this->mContentLoaded
) {
450 return $this->mContent
;
453 $dbr = wfGetDB( DB_MASTER
);
455 # Pre-fill content with error message so that if something
456 # fails we'll have something telling us what we intended.
457 $t = $this->mTitle
->getPrefixedText();
458 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
459 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
462 $revision = Revision
::newFromId( $oldid );
463 if ( is_null( $revision ) ) {
464 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
467 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
469 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
472 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
473 $this->loadPageData( $data );
475 if ( !$this->mDataLoaded
) {
476 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
478 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
481 $this->loadPageData( $data );
483 $revision = Revision
::newFromId( $this->mLatest
);
484 if ( is_null( $revision ) ) {
485 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
490 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
491 // We should instead work with the Revision object when we need it...
492 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
494 $this->mUser
= $revision->getUser();
495 $this->mUserText
= $revision->getUserText();
496 $this->mComment
= $revision->getComment();
497 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
499 $this->mRevIdFetched
= $revision->getId();
500 $this->mContentLoaded
= true;
501 $this->mRevision
=& $revision;
503 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
505 return $this->mContent
;
509 * Read/write accessor to select FOR UPDATE
511 * @param $x Mixed: FIXME
512 * @return mixed value of $x, or value stored in Article::mForUpdate
514 public function forUpdate( $x = null ) {
515 return wfSetVar( $this->mForUpdate
, $x );
519 * Get the database which should be used for reads
522 * @deprecated - just call wfGetDB( DB_MASTER ) instead
525 wfDeprecated( __METHOD__
);
526 return wfGetDB( DB_MASTER
);
530 * Get options for all SELECT statements
532 * @param $options Array: an optional options array which'll be appended to
534 * @return Array: options
536 protected function getSelectOptions( $options = '' ) {
537 if ( $this->mForUpdate
) {
538 if ( is_array( $options ) ) {
539 $options[] = 'FOR UPDATE';
541 $options = 'FOR UPDATE';
548 * @return int Page ID
550 public function getID() {
551 if ( $this->mTitle
) {
552 return $this->mTitle
->getArticleID();
559 * @return bool Whether or not the page exists in the database
561 public function exists() {
562 return $this->getId() > 0;
566 * Check if this page is something we're going to be showing
567 * some sort of sensible content for. If we return false, page
568 * views (plain action=view) will return an HTTP 404 response,
569 * so spiders and robots can know they're following a bad link.
573 public function hasViewableContent() {
574 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
578 * @return int The view count for the page
580 public function getCount() {
581 if ( -1 == $this->mCounter
) {
582 $id = $this->getID();
586 $dbr = wfGetDB( DB_SLAVE
);
587 $this->mCounter
= $dbr->selectField( 'page',
589 array( 'page_id' => $id ),
591 $this->getSelectOptions()
595 return $this->mCounter
;
599 * Determine whether a page would be suitable for being counted as an
600 * article in the site_stats table based on the title & its content
602 * @param $text String: text to analyze
605 public function isCountable( $text ) {
606 global $wgUseCommaCount;
608 $token = $wgUseCommaCount ?
',' : '[[';
609 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
613 * Tests if the article text represents a redirect
615 * @param $text mixed string containing article contents, or boolean
618 public function isRedirect( $text = false ) {
619 if ( $text === false ) {
620 if ( $this->mDataLoaded
) {
621 return $this->mIsRedirect
;
623 // Apparently loadPageData was never called
624 $this->loadContent();
625 $titleObj = Title
::newFromRedirectRecurse( $this->fetchContent() );
627 $titleObj = Title
::newFromRedirect( $text );
629 return $titleObj !== null;
633 * Returns true if the currently-referenced revision is the current edit
634 * to this page (and it exists).
637 public function isCurrent() {
638 # If no oldid, this is the current version.
639 if ( $this->getOldID() == 0 ) {
642 return $this->exists() && isset( $this->mRevision
) && $this->mRevision
->isCurrent();
646 * Loads everything except the text
647 * This isn't necessary for all uses, so it's only done if needed.
649 protected function loadLastEdit() {
650 if ( -1 != $this->mUser
)
653 # New or non-existent articles have no user information
654 $id = $this->getID();
655 if ( 0 == $id ) return;
657 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
658 if ( !is_null( $this->mLastRevision
) ) {
659 $this->mUser
= $this->mLastRevision
->getUser();
660 $this->mUserText
= $this->mLastRevision
->getUserText();
661 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
662 $this->mComment
= $this->mLastRevision
->getComment();
663 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
664 $this->mRevIdFetched
= $this->mLastRevision
->getId();
669 * @return string GMT timestamp of last article revision
672 public function getTimestamp() {
673 // Check if the field has been filled by ParserCache::get()
674 if ( !$this->mTimestamp
) {
675 $this->loadLastEdit();
677 return wfTimestamp( TS_MW
, $this->mTimestamp
);
681 * @return int user ID for the user that made the last article revision
683 public function getUser() {
684 $this->loadLastEdit();
689 * @return string username of the user that made the last article revision
691 public function getUserText() {
692 $this->loadLastEdit();
693 return $this->mUserText
;
697 * @return string Comment stored for the last article revision
699 public function getComment() {
700 $this->loadLastEdit();
701 return $this->mComment
;
705 * Returns true if last revision was marked as "minor edit"
707 * @return boolean Minor edit indicator for the last article revision.
709 public function getMinorEdit() {
710 $this->loadLastEdit();
711 return $this->mMinorEdit
;
715 * Use this to fetch the rev ID used on page views
717 * @return int revision ID of last article revision
719 public function getRevIdFetched() {
720 $this->loadLastEdit();
721 return $this->mRevIdFetched
;
725 * @param $limit Integer: default 0.
726 * @param $offset Integer: default 0.
727 * @return UserArrayFromResult object with User objects of article contributors for requested range
729 public function getContributors( $limit = 0, $offset = 0 ) {
730 # XXX: this is expensive; cache this info somewhere.
732 $dbr = wfGetDB( DB_SLAVE
);
733 $revTable = $dbr->tableName( 'revision' );
734 $userTable = $dbr->tableName( 'user' );
736 $pageId = $this->getId();
738 $user = $this->getUser();
740 $excludeCond = "AND rev_user != $user";
742 $userText = $dbr->addQuotes( $this->getUserText() );
743 $excludeCond = "AND rev_user_text != $userText";
746 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
); // username hidden?
748 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
749 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
750 WHERE rev_page = $pageId
753 GROUP BY rev_user, rev_user_text
754 ORDER BY timestamp DESC";
757 $sql = $dbr->limitResult( $sql, $limit, $offset );
759 $sql .= ' ' . $this->getSelectOptions();
760 $res = $dbr->query( $sql, __METHOD__
);
762 return new UserArrayFromResult( $res );
766 * This is the default action of the index.php entry point: just view the
767 * page of the given title.
769 public function view() {
770 global $wgUser, $wgOut, $wgRequest, $wgContLang;
771 global $wgEnableParserCache, $wgStylePath, $wgParser;
772 global $wgUseTrackbacks, $wgUseFileCache;
774 wfProfileIn( __METHOD__
);
776 # Get variables from query string
777 $oldid = $this->getOldID();
778 $parserCache = ParserCache
::singleton();
780 $parserOptions = clone $this->getParserOptions();
781 # Render printable version, use printable version cache
782 if ( $wgOut->isPrintable() ) {
783 $parserOptions->setIsPrintable( true );
786 # Try client and file cache
787 if ( $oldid === 0 && $this->checkTouched() ) {
790 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
792 # Is is client cached?
793 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
794 wfDebug( __METHOD__
. ": done 304\n" );
795 wfProfileOut( __METHOD__
);
798 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
799 wfDebug( __METHOD__
. ": done file cache\n" );
800 # tell wgOut that output is taken care of
802 $this->viewUpdates();
803 wfProfileOut( __METHOD__
);
808 # getOldID may want us to redirect somewhere else
809 if ( $this->mRedirectUrl
) {
810 $wgOut->redirect( $this->mRedirectUrl
);
811 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
812 wfProfileOut( __METHOD__
);
816 $wgOut->setArticleFlag( true );
817 # Set page title (may be overridden by DISPLAYTITLE)
818 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
820 # If we got diff in the query, we want to see a diff page instead of the article.
821 if ( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
822 wfDebug( __METHOD__
. ": showing diff page\n" );
823 $this->showDiffPage();
824 wfProfileOut( __METHOD__
);
828 # Should the parser cache be used?
829 $useParserCache = $this->useParserCache( $oldid );
830 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
831 if ( $wgUser->getOption( 'stubthreshold' ) ) {
832 wfIncrStats( 'pcache_miss_stub' );
835 # For the main page, overwrite the <title> element with the con-
836 # tents of 'pagetitle-view-mainpage' instead of the default (if
838 if ( $this->mTitle
->equals( Title
::newMainPage() )
839 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
841 $wgOut->setHTMLTitle( $m );
844 $wasRedirected = $this->showRedirectedFromHeader();
845 $this->showNamespaceHeader();
847 # Iterate through the possible ways of constructing the output text.
848 # Keep going until $outputDone is set, or we run out of things to do.
851 while ( !$outputDone && ++
$pass ) {
854 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
858 # Try the parser cache
859 if ( $useParserCache ) {
860 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
861 if ( $this->mParserOutput
!== false ) {
862 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
863 $wgOut->addParserOutput( $this->mParserOutput
);
864 # Ensure that UI elements requiring revision ID have
865 # the correct version information.
866 $wgOut->setRevisionId( $this->mLatest
);
873 $text = $this->getContent();
874 if ( $text === false ||
$this->getID() == 0 ) {
875 wfDebug( __METHOD__
. ": showing missing article\n" );
876 $this->showMissingArticle();
877 wfProfileOut( __METHOD__
);
881 # Another whitelist check in case oldid is altering the title
882 if ( !$this->mTitle
->userCanRead() ) {
883 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
884 $wgOut->loginToUse();
887 wfProfileOut( __METHOD__
);
891 # Are we looking at an old revision
892 if ( $oldid && !is_null( $this->mRevision
) ) {
893 $this->setOldSubtitle( $oldid );
894 if ( !$this->showDeletedRevisionHeader() ) {
895 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
896 wfProfileOut( __METHOD__
);
899 # If this "old" version is the current, then try the parser cache...
900 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
901 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
902 if ( $this->mParserOutput
) {
903 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
904 $wgOut->addParserOutput( $this->mParserOutput
);
905 $wgOut->setRevisionId( $this->mLatest
);
906 $this->showViewFooter();
907 $this->viewUpdates();
908 wfProfileOut( __METHOD__
);
914 # Ensure that UI elements requiring revision ID have
915 # the correct version information.
916 $wgOut->setRevisionId( $this->getRevIdFetched() );
918 # Pages containing custom CSS or JavaScript get special treatment
919 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
920 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
921 $this->showCssOrJsPage();
923 } else if ( $rt = Title
::newFromRedirectArray( $text ) ) {
924 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
925 # Viewing a redirect page (e.g. with parameter redirect=no)
926 # Don't append the subtitle if this was an old revision
927 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
928 # Parse just to get categories, displaytitle, etc.
929 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
930 $wgOut->addParserOutputNoText( $this->mParserOutput
);
936 # Run the parse, protected by a pool counter
937 wfDebug( __METHOD__
. ": doing uncached parse\n" );
938 $key = $parserCache->getKey( $this, $parserOptions );
939 $poolCounter = PoolCounter
::factory( 'Article::view', $key );
940 $dirtyCallback = $useParserCache ?
array( $this, 'tryDirtyCache' ) : false;
941 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
943 if ( !$status->isOK() ) {
944 # Connection or timeout error
945 $this->showPoolError( $status );
946 wfProfileOut( __METHOD__
);
953 # Should be unreachable, but just in case...
959 # Now that we've filled $this->mParserOutput, we know whether
960 # there are any __NOINDEX__ tags on the page
961 $policy = $this->getRobotPolicy( 'view' );
962 $wgOut->setIndexPolicy( $policy['index'] );
963 $wgOut->setFollowPolicy( $policy['follow'] );
965 $this->showViewFooter();
966 $this->viewUpdates();
967 wfProfileOut( __METHOD__
);
971 * Show a diff page according to current request variables. For use within
972 * Article::view() only, other callers should use the DifferenceEngine class.
974 public function showDiffPage() {
975 global $wgOut, $wgRequest, $wgUser;
977 $diff = $wgRequest->getVal( 'diff' );
978 $rcid = $wgRequest->getVal( 'rcid' );
979 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
980 $purge = $wgRequest->getVal( 'action' ) == 'purge';
981 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
982 $oldid = $this->getOldID();
984 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
985 // DifferenceEngine directly fetched the revision:
986 $this->mRevIdFetched
= $de->mNewid
;
987 $de->showDiffPage( $diffOnly );
989 // Needed to get the page's current revision
990 $this->loadPageData();
991 if ( $diff == 0 ||
$diff == $this->mLatest
) {
992 # Run view updates for current revision only
993 $this->viewUpdates();
998 * Show a page view for a page formatted as CSS or JavaScript. To be called by
999 * Article::view() only.
1001 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1004 public function showCssOrJsPage() {
1006 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
1007 // Give hooks a chance to customise the output
1008 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1009 // Wrap the whole lot in a <pre> and don't parse
1011 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1012 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1013 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1014 $wgOut->addHTML( "\n</pre>\n" );
1019 * Get the robot policy to be used for the current action=view request.
1020 * @return String the policy that should be set
1021 * @deprecated use getRobotPolicy() instead, which returns an associative
1024 public function getRobotPolicyForView() {
1025 wfDeprecated( __FUNCTION__
);
1026 $policy = $this->getRobotPolicy( 'view' );
1027 return $policy['index'] . ',' . $policy['follow'];
1031 * Get the robot policy to be used for the current view
1032 * @param $action String the action= GET parameter
1033 * @return Array the policy that should be set
1034 * TODO: actions other than 'view'
1036 public function getRobotPolicy( $action ) {
1038 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1039 global $wgDefaultRobotPolicy, $wgRequest;
1041 $ns = $this->mTitle
->getNamespace();
1042 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1043 # Don't index user and user talk pages for blocked users (bug 11443)
1044 if ( !$this->mTitle
->isSubpage() ) {
1045 $block = new Block();
1046 if ( $block->load( $this->mTitle
->getText() ) ) {
1047 return array( 'index' => 'noindex',
1048 'follow' => 'nofollow' );
1053 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1054 # Non-articles (special pages etc), and old revisions
1055 return array( 'index' => 'noindex',
1056 'follow' => 'nofollow' );
1057 } elseif ( $wgOut->isPrintable() ) {
1058 # Discourage indexing of printable versions, but encourage following
1059 return array( 'index' => 'noindex',
1060 'follow' => 'follow' );
1061 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1062 # For ?curid=x urls, disallow indexing
1063 return array( 'index' => 'noindex',
1064 'follow' => 'follow' );
1067 # Otherwise, construct the policy based on the various config variables.
1068 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1070 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1071 # Honour customised robot policies for this namespace
1072 $policy = array_merge( $policy,
1073 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] ) );
1075 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1076 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1077 # a final sanity check that we have really got the parser output.
1078 $policy = array_merge( $policy,
1079 array( 'index' => $this->mParserOutput
->getIndexPolicy() ) );
1082 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1083 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1084 $policy = array_merge( $policy,
1085 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) );
1093 * Converts a String robot policy into an associative array, to allow
1094 * merging of several policies using array_merge().
1095 * @param $policy Mixed, returns empty array on null/false/'', transparent
1096 * to already-converted arrays, converts String.
1097 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1099 public static function formatRobotPolicy( $policy ) {
1100 if ( is_array( $policy ) ) {
1102 } elseif ( !$policy ) {
1106 $policy = explode( ',', $policy );
1107 $policy = array_map( 'trim', $policy );
1110 foreach ( $policy as $var ) {
1111 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1112 $arr['index'] = $var;
1113 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1114 $arr['follow'] = $var;
1121 * If this request is a redirect view, send "redirected from" subtitle to
1122 * $wgOut. Returns true if the header was needed, false if this is not a
1123 * redirect view. Handles both local and remote redirects.
1127 public function showRedirectedFromHeader() {
1128 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1130 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1131 $sk = $wgUser->getSkin();
1132 if ( isset( $this->mRedirectedFrom
) ) {
1133 // This is an internally redirected page view.
1134 // We'll need a backlink to the source page for navigation.
1135 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1137 $this->mRedirectedFrom
,
1140 array( 'redirect' => 'no' ),
1141 array( 'known', 'noclasses' )
1143 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1144 $wgOut->setSubtitle( $s );
1146 // Set the fragment if one was specified in the redirect
1147 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1148 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1149 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1152 // Add a <link rel="canonical"> tag
1153 $wgOut->addLink( array( 'rel' => 'canonical',
1154 'href' => $this->mTitle
->getLocalURL() )
1158 } elseif ( $rdfrom ) {
1159 // This is an externally redirected view, from some other wiki.
1160 // If it was reported from a trusted site, supply a backlink.
1161 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1162 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1163 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1164 $wgOut->setSubtitle( $s );
1172 * Show a header specific to the namespace currently being viewed, like
1173 * [[MediaWiki:Talkpagetext]]. For Article::view().
1175 public function showNamespaceHeader() {
1177 if ( $this->mTitle
->isTalkPage() ) {
1178 $msg = wfMsgNoTrans( 'talkpageheader' );
1179 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1180 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1186 * Show the footer section of an ordinary page view
1188 public function showViewFooter() {
1189 global $wgOut, $wgUseTrackbacks, $wgRequest;
1190 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1191 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1192 $wgOut->addWikiMsg( 'anontalkpagetext' );
1195 # If we have been passed an &rcid= parameter, we want to give the user a
1196 # chance to mark this new article as patrolled.
1197 $this->showPatrolFooter();
1200 if ( $wgUseTrackbacks ) {
1201 $this->addTrackbacks();
1206 * If patrol is possible, output a patrol UI box. This is called from the
1207 * footer section of ordinary page views. If patrol is not possible or not
1208 * desired, does nothing.
1210 public function showPatrolFooter() {
1211 global $wgOut, $wgRequest, $wgUser;
1212 $rcid = $wgRequest->getVal( 'rcid' );
1214 if ( !$rcid ||
!$this->mTitle
->exists() ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1218 $sk = $wgUser->getSkin();
1221 "<div class='patrollink'>" .
1223 'markaspatrolledlink',
1226 wfMsgHtml( 'markaspatrolledtext' ),
1229 'action' => 'markpatrolled',
1232 array( 'known', 'noclasses' )
1240 * Show the error text for a missing article. For articles in the MediaWiki
1241 * namespace, show the default message text. To be called from Article::view().
1243 public function showMissingArticle() {
1244 global $wgOut, $wgRequest, $wgUser;
1246 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1247 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1248 $parts = explode( '/', $this->mTitle
->getText() );
1249 $rootPart = $parts[0];
1250 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1251 $ip = User
::isIP( $rootPart );
1252 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1253 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1</div>",
1254 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1255 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1256 LogEventsList
::showLogExtract(
1259 $user->getUserPage()->getPrefixedText(),
1263 'showIfEmpty' => false,
1265 'blocked-notice-logextract',
1266 $user->getName() # Support GENDER in notice
1272 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1273 # Show delete and move logs
1274 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1276 'conds' => array( "log_action != 'revision'" ),
1277 'showIfEmpty' => false,
1278 'msgKey' => array( 'moveddeleted-notice' ) )
1281 # Show error message
1282 $oldid = $this->getOldID();
1284 $text = wfMsgNoTrans( 'missing-article',
1285 $this->mTitle
->getPrefixedText(),
1286 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1287 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1288 // Use the default message text
1289 $text = $this->getContent();
1291 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1292 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1293 $errors = array_merge( $createErrors, $editErrors );
1295 if ( !count( $errors ) )
1296 $text = wfMsgNoTrans( 'noarticletext' );
1298 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1300 $text = "<div class='noarticletext'>\n$text\n</div>";
1301 if ( !$this->hasViewableContent() ) {
1302 // If there's no backing content, send a 404 Not Found
1303 // for better machine handling of broken links.
1304 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1306 $wgOut->addWikiText( $text );
1310 * If the revision requested for view is deleted, check permissions.
1311 * Send either an error message or a warning header to $wgOut.
1313 * @return boolean true if the view is allowed, false if not.
1315 public function showDeletedRevisionHeader() {
1316 global $wgOut, $wgRequest;
1317 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1321 // If the user is not allowed to see it...
1322 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1323 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1324 'rev-deleted-text-permission' );
1326 // If the user needs to confirm that they want to see it...
1327 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1328 # Give explanation and add a link to view the revision...
1329 $oldid = intval( $this->getOldID() );
1330 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1331 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1332 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1333 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1334 array( $msg, $link ) );
1336 // We are allowed to see...
1338 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1339 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1340 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
1346 * Should the parser cache be used?
1350 public function useParserCache( $oldid ) {
1351 global $wgUser, $wgEnableParserCache;
1353 return $wgEnableParserCache
1354 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1357 && !$this->mTitle
->isCssOrJsPage()
1358 && !$this->mTitle
->isCssJsSubpage();
1362 * Execute the uncached parse for action=view
1364 public function doViewParse() {
1366 $oldid = $this->getOldID();
1367 $useParserCache = $this->useParserCache( $oldid );
1368 $parserOptions = clone $this->getParserOptions();
1369 # Render printable version, use printable version cache
1370 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1371 # Don't show section-edit links on old revisions... this way lies madness.
1372 $parserOptions->setEditSection( $this->isCurrent() );
1373 $useParserCache = $this->useParserCache( $oldid );
1374 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1378 * Try to fetch an expired entry from the parser cache. If it is present,
1379 * output it and return true. If it is not present, output nothing and
1380 * return false. This is used as a callback function for
1381 * PoolCounter::executeProtected().
1385 public function tryDirtyCache() {
1387 $parserCache = ParserCache
::singleton();
1388 $options = $this->getParserOptions();
1389 $options->setIsPrintable( $wgOut->isPrintable() );
1390 $output = $parserCache->getDirty( $this, $options );
1392 wfDebug( __METHOD__
. ": sending dirty output\n" );
1393 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1394 $wgOut->setSquidMaxage( 0 );
1395 $this->mParserOutput
= $output;
1396 $wgOut->addParserOutput( $output );
1397 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1400 wfDebugLog( 'dirty', "dirty missing\n" );
1401 wfDebug( __METHOD__
. ": no dirty cache\n" );
1407 * Show an error page for an error from the pool counter.
1408 * @param $status Status
1410 public function showPoolError( $status ) {
1412 $wgOut->clearHTML(); // for release() errors
1413 $wgOut->enableClientCache( false );
1414 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1415 $wgOut->addWikiText(
1416 '<div class="errorbox">' .
1417 $status->getWikiText( false, 'view-pool-error' ) .
1425 * @param $target Title object or Array of destination(s) to redirect
1426 * @param $appendSubtitle Boolean [optional]
1427 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1428 * @return string containing HMTL with redirect link
1430 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1431 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1433 if ( !is_array( $target ) ) {
1434 $target = array( $target );
1436 $imageDir = $wgContLang->getDir();
1437 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1438 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1439 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of entities?
1441 if ( $appendSubtitle ) {
1442 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1444 $sk = $wgUser->getSkin();
1445 // the loop prepends the arrow image before the link, so the first case needs to be outside
1446 $title = array_shift( $target );
1447 if ( $forceKnown ) {
1450 htmlspecialchars( $title->getFullText() ),
1453 array( 'known', 'noclasses' )
1456 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1458 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1459 foreach ( $target as $rt ) {
1460 if ( $forceKnown ) {
1461 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1464 htmlspecialchars( $rt->getFullText() ),
1467 array( 'known', 'noclasses' )
1470 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1471 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1474 return '<img src="' . $imageUrl . '" alt="#REDIRECT " />' .
1475 '<span class="redirectText">' . $link . '</span>';
1480 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1482 public function addTrackbacks() {
1483 global $wgOut, $wgUser;
1484 $dbr = wfGetDB( DB_SLAVE
);
1485 $tbs = $dbr->select( 'trackbacks',
1486 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1487 array( 'tb_page' => $this->getID() )
1489 if ( !$dbr->numRows( $tbs ) ) return;
1492 while ( $o = $dbr->fetchObject( $tbs ) ) {
1494 if ( $wgUser->isAllowed( 'trackback' ) ) {
1495 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1496 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1497 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1500 $tbtext .= wfMsg( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1507 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1508 $this->mTitle
->invalidateCache();
1512 * Removes trackback record for current article from trackbacks table
1514 public function deletetrackback() {
1515 global $wgUser, $wgRequest, $wgOut;
1516 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1517 $wgOut->addWikiMsg( 'sessionfailure' );
1521 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1522 if ( count( $permission_errors ) ) {
1523 $wgOut->showPermissionsErrorPage( $permission_errors );
1527 $db = wfGetDB( DB_MASTER
);
1528 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1530 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1531 $this->mTitle
->invalidateCache();
1535 * Handle action=render
1538 public function render() {
1540 $wgOut->setArticleBodyOnly( true );
1545 * Handle action=purge
1547 public function purge() {
1548 global $wgUser, $wgRequest, $wgOut;
1549 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1550 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1555 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1556 $button = wfMsgExt( 'confirm_purge_button', array( 'escapenoentities' ) );
1557 $form = "<form method=\"post\" action=\"$action\">\n" .
1558 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1560 $top = wfMsgExt( 'confirm-purge-top', array( 'parse' ) );
1561 $bottom = wfMsgExt( 'confirm-purge-bottom', array( 'parse' ) );
1562 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1563 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1564 $wgOut->addHTML( $top . $form . $bottom );
1569 * Perform the actions of a page purging
1571 public function doPurge() {
1573 // Invalidate the cache
1574 $this->mTitle
->invalidateCache();
1576 if ( $wgUseSquid ) {
1577 // Commit the transaction before the purge is sent
1578 $dbw = wfGetDB( DB_MASTER
);
1582 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1583 $update->doUpdate();
1585 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1586 global $wgMessageCache;
1587 if ( $this->getID() == 0 ) {
1590 $text = $this->getRawText();
1592 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1597 * Insert a new empty page record for this article.
1598 * This *must* be followed up by creating a revision
1599 * and running $this->updateToLatest( $rev_id );
1600 * or else the record will be left in a funky state.
1601 * Best if all done inside a transaction.
1603 * @param $dbw Database
1604 * @return int The newly created page_id key, or false if the title already existed
1607 public function insertOn( $dbw ) {
1608 wfProfileIn( __METHOD__
);
1610 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1611 $dbw->insert( 'page', array(
1612 'page_id' => $page_id,
1613 'page_namespace' => $this->mTitle
->getNamespace(),
1614 'page_title' => $this->mTitle
->getDBkey(),
1615 'page_counter' => 0,
1616 'page_restrictions' => '',
1617 'page_is_redirect' => 0, # Will set this shortly...
1619 'page_random' => wfRandom(),
1620 'page_touched' => $dbw->timestamp(),
1621 'page_latest' => 0, # Fill this in shortly...
1622 'page_len' => 0, # Fill this in shortly...
1623 ), __METHOD__
, 'IGNORE' );
1625 $affected = $dbw->affectedRows();
1627 $newid = $dbw->insertId();
1628 $this->mTitle
->resetArticleId( $newid );
1630 wfProfileOut( __METHOD__
);
1631 return $affected ?
$newid : false;
1635 * Update the page record to point to a newly saved revision.
1637 * @param $dbw Database object
1638 * @param $revision Revision: For ID number, and text used to set
1639 length and redirect status fields
1640 * @param $lastRevision Integer: if given, will not overwrite the page field
1641 * when different from the currently set value.
1642 * Giving 0 indicates the new page flag should be set
1644 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1645 * removing rows in redirect table.
1646 * @return bool true on success, false on failure
1649 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1650 wfProfileIn( __METHOD__
);
1652 $text = $revision->getText();
1653 $rt = Title
::newFromRedirect( $text );
1655 $conditions = array( 'page_id' => $this->getId() );
1656 if ( !is_null( $lastRevision ) ) {
1657 # An extra check against threads stepping on each other
1658 $conditions['page_latest'] = $lastRevision;
1661 $dbw->update( 'page',
1663 'page_latest' => $revision->getId(),
1664 'page_touched' => $dbw->timestamp(),
1665 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1666 'page_is_redirect' => $rt !== null ?
1 : 0,
1667 'page_len' => strlen( $text ),
1672 $result = $dbw->affectedRows() != 0;
1674 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1677 wfProfileOut( __METHOD__
);
1682 * Add row to the redirect table if this is a redirect, remove otherwise.
1684 * @param $dbw Database
1685 * @param $redirectTitle a title object pointing to the redirect target,
1686 * or NULL if this is not a redirect
1687 * @param $lastRevIsRedirect If given, will optimize adding and
1688 * removing rows in redirect table.
1689 * @return bool true on success, false on failure
1692 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1693 // Always update redirects (target link might have changed)
1694 // Update/Insert if we don't know if the last revision was a redirect or not
1695 // Delete if changing from redirect to non-redirect
1696 $isRedirect = !is_null( $redirectTitle );
1697 if ( $isRedirect ||
is_null( $lastRevIsRedirect ) ||
$lastRevIsRedirect !== $isRedirect ) {
1698 wfProfileIn( __METHOD__
);
1699 if ( $isRedirect ) {
1700 // This title is a redirect, Add/Update row in the redirect table
1701 $set = array( /* SET */
1702 'rd_namespace' => $redirectTitle->getNamespace(),
1703 'rd_title' => $redirectTitle->getDBkey(),
1704 'rd_from' => $this->getId(),
1706 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1708 // This is not a redirect, remove row from redirect table
1709 $where = array( 'rd_from' => $this->getId() );
1710 $dbw->delete( 'redirect', $where, __METHOD__
);
1712 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1713 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1715 wfProfileOut( __METHOD__
);
1716 return ( $dbw->affectedRows() != 0 );
1722 * If the given revision is newer than the currently set page_latest,
1723 * update the page record. Otherwise, do nothing.
1725 * @param $dbw Database object
1726 * @param $revision Revision object
1729 public function updateIfNewerOn( &$dbw, $revision ) {
1730 wfProfileIn( __METHOD__
);
1731 $row = $dbw->selectRow(
1732 array( 'revision', 'page' ),
1733 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1735 'page_id' => $this->getId(),
1736 'page_latest=rev_id' ),
1739 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1740 wfProfileOut( __METHOD__
);
1743 $prev = $row->rev_id
;
1744 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1746 # No or missing previous revision; mark the page as new
1748 $lastRevIsRedirect = null;
1750 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1751 wfProfileOut( __METHOD__
);
1756 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1757 * @return string Complete article text, or null if error
1759 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1760 wfProfileIn( __METHOD__
);
1761 if ( strval( $section ) == '' ) {
1762 // Whole-page edit; let the whole text through
1764 if ( is_null( $edittime ) ) {
1765 $rev = Revision
::newFromTitle( $this->mTitle
);
1767 $dbw = wfGetDB( DB_MASTER
);
1768 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1771 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1772 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1775 $oldtext = $rev->getText();
1777 if ( $section == 'new' ) {
1778 # Inserting a new section
1779 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1780 $text = strlen( trim( $oldtext ) ) > 0
1781 ?
"{$oldtext}\n\n{$subject}{$text}"
1782 : "{$subject}{$text}";
1784 # Replacing an existing section; roll out the big guns
1786 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1789 wfProfileOut( __METHOD__
);
1794 * This function is not deprecated until somebody fixes the core not to use
1795 * it. Nevertheless, use Article::doEdit() instead.
1797 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1798 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1799 ( $isminor ? EDIT_MINOR
: 0 ) |
1800 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1801 ( $bot ? EDIT_FORCE_BOT
: 0 );
1803 # If this is a comment, add the summary as headline
1804 if ( $comment && $summary != "" ) {
1805 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
1808 $this->doEdit( $text, $summary, $flags );
1810 $dbw = wfGetDB( DB_MASTER
);
1812 if ( !$this->mTitle
->userIsWatching() ) {
1818 if ( $this->mTitle
->userIsWatching() ) {
1824 $this->doRedirect( $this->isRedirect( $text ) );
1828 * @deprecated use Article::doEdit()
1830 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1831 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1832 ( $minor ? EDIT_MINOR
: 0 ) |
1833 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1835 $status = $this->doEdit( $text, $summary, $flags );
1836 if ( !$status->isOK() ) {
1840 $dbw = wfGetDB( DB_MASTER
);
1842 if ( !$this->mTitle
->userIsWatching() ) {
1848 if ( $this->mTitle
->userIsWatching() ) {
1855 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1856 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1858 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1865 * Change an existing article or create a new article. Updates RC and all necessary caches,
1866 * optionally via the deferred update array.
1868 * $wgUser must be set before calling this function.
1870 * @param $text String: new text
1871 * @param $summary String: edit summary
1872 * @param $flags Integer bitfield:
1874 * Article is known or assumed to be non-existent, create a new one
1876 * Article is known or assumed to be pre-existing, update it
1878 * Mark this edit minor, if the user is allowed to do so
1880 * Do not log the change in recentchanges
1882 * Mark the edit a "bot" edit regardless of user rights
1883 * EDIT_DEFER_UPDATES
1884 * Defer some of the updates until the end of index.php
1886 * Fill in blank summaries with generated text where possible
1888 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1889 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1890 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1891 * edit-already-exists error will be returned. These two conditions are also possible with
1892 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1894 * @param $baseRevId the revision ID this edit was based off, if any
1895 * @param $user Optional user object, $wgUser will be used if not passed
1897 * @return Status object. Possible errors:
1898 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1899 * edit-gone-missing: In update mode, but the article didn't exist
1900 * edit-conflict: In update mode, the article changed unexpectedly
1901 * edit-no-change: Warning that the text was the same as before
1902 * edit-already-exists: In creation mode, but the article already exists
1904 * Extensions may define additional errors.
1906 * $return->value will contain an associative array with members as follows:
1907 * new: Boolean indicating if the function attempted to create a new article
1908 * revision: The revision object for the inserted revision, or null
1910 * Compatibility note: this function previously returned a boolean value indicating success/failure
1912 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1913 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1915 # Low-level sanity check
1916 if ( $this->mTitle
->getText() == '' ) {
1917 throw new MWException( 'Something is trying to edit an article with an empty title' );
1920 wfProfileIn( __METHOD__
);
1922 $user = is_null( $user ) ?
$wgUser : $user;
1923 $status = Status
::newGood( array() );
1925 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1926 $this->loadPageData();
1928 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1929 $aid = $this->mTitle
->getArticleID();
1931 $flags |
= EDIT_UPDATE
;
1937 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1938 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1940 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1941 wfProfileOut( __METHOD__
);
1942 if ( $status->isOK() ) {
1943 $status->fatal( 'edit-hook-aborted' );
1948 # Silently ignore EDIT_MINOR if not allowed
1949 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1950 $bot = $flags & EDIT_FORCE_BOT
;
1952 $oldtext = $this->getRawText(); // current revision
1953 $oldsize = strlen( $oldtext );
1955 # Provide autosummaries if one is not provided and autosummaries are enabled.
1956 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1957 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1960 $editInfo = $this->prepareTextForEdit( $text );
1961 $text = $editInfo->pst
;
1962 $newsize = strlen( $text );
1964 $dbw = wfGetDB( DB_MASTER
);
1965 $now = wfTimestampNow();
1966 $this->mTimestamp
= $now;
1968 if ( $flags & EDIT_UPDATE
) {
1969 # Update article, but only if changed.
1970 $status->value
['new'] = false;
1971 # Make sure the revision is either completely inserted or not inserted at all
1972 if ( !$wgDBtransactions ) {
1973 $userAbort = ignore_user_abort( true );
1978 $changed = ( strcmp( $text, $oldtext ) != 0 );
1981 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1982 - (int)$this->isCountable( $oldtext );
1983 $this->mTotalAdjustment
= 0;
1985 if ( !$this->mLatest
) {
1986 # Article gone missing
1987 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1988 $status->fatal( 'edit-gone-missing' );
1989 wfProfileOut( __METHOD__
);
1993 $revision = new Revision( array(
1994 'page' => $this->getId(),
1995 'comment' => $summary,
1996 'minor_edit' => $isminor,
1998 'parent_id' => $this->mLatest
,
1999 'user' => $user->getId(),
2000 'user_text' => $user->getName(),
2004 $revisionId = $revision->insertOn( $dbw );
2008 # Note that we use $this->mLatest instead of fetching a value from the master DB
2009 # during the course of this function. This makes sure that EditPage can detect
2010 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2011 # before this function is called. A previous function used a separate query, this
2012 # creates a window where concurrent edits can cause an ignored edit conflict.
2013 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2016 /* Belated edit conflict! Run away!! */
2017 $status->fatal( 'edit-conflict' );
2018 # Delete the invalid revision if the DB is not transactional
2019 if ( !$wgDBtransactions ) {
2020 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2025 global $wgUseRCPatrol;
2026 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2027 # Update recentchanges
2028 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2029 # Mark as patrolled if the user can do so
2030 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan( 'autopatrol' );
2031 # Add RC row to the DB
2032 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2033 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2034 $revisionId, $patrolled
2036 # Log auto-patrolled edits
2038 PatrolLog
::record( $rc, true );
2041 $user->incEditCount();
2045 $status->warning( 'edit-no-change' );
2047 // Keep the same revision ID, but do some updates on it
2048 $revisionId = $this->getRevIdFetched();
2049 // Update page_touched, this is usually implicit in the page update
2050 // Other cache updates are done in onArticleEdit()
2051 $this->mTitle
->invalidateCache();
2054 if ( !$wgDBtransactions ) {
2055 ignore_user_abort( $userAbort );
2057 // Now that ignore_user_abort is restored, we can respond to fatal errors
2058 if ( !$status->isOK() ) {
2059 wfProfileOut( __METHOD__
);
2063 # Invalidate cache of this article and all pages using this article
2064 # as a template. Partly deferred.
2065 Article
::onArticleEdit( $this->mTitle
);
2066 # Update links tables, site stats, etc.
2067 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2069 # Create new article
2070 $status->value
['new'] = true;
2072 # Set statistics members
2073 # We work out if it's countable after PST to avoid counter drift
2074 # when articles are created with {{subst:}}
2075 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2076 $this->mTotalAdjustment
= 1;
2080 # Add the page record; stake our claim on this title!
2081 # This will return false if the article already exists
2082 $newid = $this->insertOn( $dbw );
2084 if ( $newid === false ) {
2086 $status->fatal( 'edit-already-exists' );
2087 wfProfileOut( __METHOD__
);
2091 # Save the revision text...
2092 $revision = new Revision( array(
2094 'comment' => $summary,
2095 'minor_edit' => $isminor,
2097 'user' => $user->getId(),
2098 'user_text' => $user->getName(),
2100 $revisionId = $revision->insertOn( $dbw );
2102 $this->mTitle
->resetArticleID( $newid );
2104 # Update the page record with revision data
2105 $this->updateRevisionOn( $dbw, $revision, 0 );
2107 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2108 # Update recentchanges
2109 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2110 global $wgUseRCPatrol, $wgUseNPPatrol;
2111 # Mark as patrolled if the user can do so
2112 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && $this->mTitle
->userCan( 'autopatrol' );
2113 # Add RC row to the DB
2114 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2115 '', strlen( $text ), $revisionId, $patrolled );
2116 # Log auto-patrolled edits
2118 PatrolLog
::record( $rc, true );
2121 $user->incEditCount();
2124 # Update links, etc.
2125 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2128 Article
::onArticleCreate( $this->mTitle
);
2130 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2131 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2134 # Do updates right now unless deferral was requested
2135 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2139 // Return the new revision (or null) to the caller
2140 $status->value
['revision'] = $revision;
2142 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2143 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2145 wfProfileOut( __METHOD__
);
2150 * @deprecated wrapper for doRedirect
2152 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2153 wfDeprecated( __METHOD__
);
2154 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2158 * Output a redirect back to the article.
2159 * This is typically used after an edit.
2161 * @param $noRedir Boolean: add redirect=no
2162 * @param $sectionAnchor String: section to redirect to, including "#"
2163 * @param $extraQuery String: extra query params
2165 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2168 $query = 'redirect=no';
2170 $query .= "&$query";
2172 $query = $extraQuery;
2174 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2178 * Mark this particular edit/page as patrolled
2180 public function markpatrolled() {
2181 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2182 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2184 # If we haven't been given an rc_id value, we can't do anything
2185 $rcid = (int) $wgRequest->getVal( 'rcid' );
2186 $rc = RecentChange
::newFromId( $rcid );
2187 if ( is_null( $rc ) ) {
2188 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2192 # It would be nice to see where the user had actually come from, but for now just guess
2193 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2194 $return = SpecialPage
::getTitleFor( $returnto );
2196 $dbw = wfGetDB( DB_MASTER
);
2197 $errors = $rc->doMarkPatrolled();
2199 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2200 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2204 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2205 // The hook itself has handled any output
2209 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2210 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2211 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2212 $wgOut->returnToMain( false, $return );
2216 if ( !empty( $errors ) ) {
2217 $wgOut->showPermissionsErrorPage( $errors );
2222 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2223 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2224 $wgOut->returnToMain( false, $return );
2228 * User-interface handler for the "watch" action
2230 public function watch() {
2231 global $wgUser, $wgOut;
2232 if ( $wgUser->isAnon() ) {
2233 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2236 if ( wfReadOnly() ) {
2237 $wgOut->readOnlyPage();
2240 if ( $this->doWatch() ) {
2241 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2242 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2243 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
2245 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2249 * Add this page to $wgUser's watchlist
2250 * @return bool true on successful watch operation
2252 public function doWatch() {
2254 if ( $wgUser->isAnon() ) {
2257 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2258 $wgUser->addWatch( $this->mTitle
);
2259 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2265 * User interface handler for the "unwatch" action.
2267 public function unwatch() {
2268 global $wgUser, $wgOut;
2269 if ( $wgUser->isAnon() ) {
2270 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2273 if ( wfReadOnly() ) {
2274 $wgOut->readOnlyPage();
2277 if ( $this->doUnwatch() ) {
2278 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2279 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2280 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
2282 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2286 * Stop watching a page
2287 * @return bool true on successful unwatch
2289 public function doUnwatch() {
2291 if ( $wgUser->isAnon() ) {
2294 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2295 $wgUser->removeWatch( $this->mTitle
);
2296 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2302 * action=protect handler
2304 public function protect() {
2305 $form = new ProtectionForm( $this );
2310 * action=unprotect handler (alias)
2312 public function unprotect() {
2317 * Update the article's restriction field, and leave a log entry.
2319 * @param $limit Array: set of restriction keys
2320 * @param $reason String
2321 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2322 * @param $expiry Array: per restriction type expiration
2323 * @return bool true on success
2325 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2326 global $wgUser, $wgContLang;
2328 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2330 $id = $this->mTitle
->getArticleID();
2332 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2336 if ( wfReadOnly() ) {
2337 wfDebug( "updateRestrictions failed: read-only\n" );
2341 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2342 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2350 // Take this opportunity to purge out expired restrictions
2351 Title
::purgeExpiredRestrictions();
2353 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2354 # we expect a single selection, but the schema allows otherwise.
2356 $updated = Article
::flattenRestrictions( $limit );
2358 foreach ( $restrictionTypes as $action ) {
2359 if ( isset( $expiry[$action] ) ) {
2360 # Get current restrictions on $action
2361 $aLimits = $this->mTitle
->getRestrictions( $action );
2362 $current[$action] = implode( '', $aLimits );
2363 # Are any actual restrictions being dealt with here?
2364 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2365 # If something changed, we need to log it. Checking $aRChanged
2366 # assures that "unprotecting" a page that is not protected does
2367 # not log just because the expiry was "changed".
2368 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2374 $current = Article
::flattenRestrictions( $current );
2376 $changed = ( $changed ||
$current != $updated );
2377 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2378 $protect = ( $updated != '' );
2380 # If nothing's changed, do nothing
2382 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2384 $dbw = wfGetDB( DB_MASTER
);
2386 # Prepare a null revision to be added to the history
2387 $modified = $current != '' && $protect;
2389 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2391 $comment_type = 'unprotectedarticle';
2393 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2395 # Only restrictions with the 'protect' right can cascade...
2396 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2397 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2398 # The schema allows multiple restrictions
2399 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) )
2401 $cascade_description = '';
2403 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2407 $comment .= ": $reason";
2409 $editComment = $comment;
2410 $encodedExpiry = array();
2411 $protect_description = '';
2412 foreach ( $limit as $action => $restrictions ) {
2413 if ( !isset( $expiry[$action] ) )
2414 $expiry[$action] = 'infinite';
2416 $encodedExpiry[$action] = Block
::encodeExpiry( $expiry[$action], $dbw );
2417 if ( $restrictions != '' ) {
2418 $protect_description .= "[$action=$restrictions] (";
2419 if ( $encodedExpiry[$action] != 'infinity' ) {
2420 $protect_description .= wfMsgForContent( 'protect-expiring',
2421 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2422 $wgContLang->date( $expiry[$action], false, false ) ,
2423 $wgContLang->time( $expiry[$action], false, false ) );
2425 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2427 $protect_description .= ') ';
2430 $protect_description = trim( $protect_description );
2432 if ( $protect_description && $protect )
2433 $editComment .= " ($protect_description)";
2435 $editComment .= "$cascade_description";
2436 # Update restrictions table
2437 foreach ( $limit as $action => $restrictions ) {
2438 if ( $restrictions != '' ) {
2439 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2440 array( 'pr_page' => $id,
2441 'pr_type' => $action,
2442 'pr_level' => $restrictions,
2443 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2444 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
2446 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2447 'pr_type' => $action ), __METHOD__
);
2451 # Insert a null revision
2452 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2453 $nullRevId = $nullRevision->insertOn( $dbw );
2455 $latest = $this->getLatest();
2456 # Update page record
2457 $dbw->update( 'page',
2459 'page_touched' => $dbw->timestamp(),
2460 'page_restrictions' => '',
2461 'page_latest' => $nullRevId
2462 ), array( /* WHERE */
2464 ), 'Article::protect'
2467 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2468 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2470 # Update the protection log
2471 $log = new LogPage( 'protect' );
2473 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2474 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2476 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2480 } # End "changed" check
2486 * Take an array of page restrictions and flatten it to a string
2487 * suitable for insertion into the page_restrictions field.
2488 * @param $limit Array
2491 protected static function flattenRestrictions( $limit ) {
2492 if ( !is_array( $limit ) ) {
2493 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2497 foreach ( $limit as $action => $restrictions ) {
2498 if ( $restrictions != '' ) {
2499 $bits[] = "$action=$restrictions";
2502 return implode( ':', $bits );
2506 * Auto-generates a deletion reason
2508 * @param &$hasHistory Boolean: whether the page has a history
2509 * @return mixed String containing deletion reason or empty string, or boolean false
2510 * if no revision occurred
2512 public function generateReason( &$hasHistory ) {
2514 $dbw = wfGetDB( DB_MASTER
);
2515 // Get the last revision
2516 $rev = Revision
::newFromTitle( $this->mTitle
);
2517 if ( is_null( $rev ) )
2520 // Get the article's contents
2521 $contents = $rev->getText();
2523 // If the page is blank, use the text from the previous revision,
2524 // which can only be blank if there's a move/import/protect dummy revision involved
2525 if ( $contents == '' ) {
2526 $prev = $rev->getPrevious();
2528 $contents = $prev->getText();
2533 // Find out if there was only one contributor
2534 // Only scan the last 20 revisions
2535 $res = $dbw->select( 'revision', 'rev_user_text',
2536 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2538 array( 'LIMIT' => 20 )
2540 if ( $res === false )
2541 // This page has no revisions, which is very weird
2544 $hasHistory = ( $res->numRows() > 1 );
2545 $row = $dbw->fetchObject( $res );
2546 if ( $row ) { // $row is false if the only contributor is hidden
2547 $onlyAuthor = $row->rev_user_text
;
2548 // Try to find a second contributor
2549 foreach ( $res as $row ) {
2550 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2551 $onlyAuthor = false;
2556 $onlyAuthor = false;
2558 $dbw->freeResult( $res );
2560 // Generate the summary with a '$1' placeholder
2562 // The current revision is blank and the one before is also
2563 // blank. It's just not our lucky day
2564 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2567 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2569 $reason = wfMsgForContent( 'excontent', '$1' );
2572 if ( $reason == '-' ) {
2573 // Allow these UI messages to be blanked out cleanly
2577 // Replace newlines with spaces to prevent uglyness
2578 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2579 // Calculate the maximum amount of chars to get
2580 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2581 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2582 $contents = $wgContLang->truncate( $contents, $maxLength );
2583 // Remove possible unfinished links
2584 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2585 // Now replace the '$1' placeholder
2586 $reason = str_replace( '$1', $contents, $reason );
2592 * UI entry point for page deletion
2594 public function delete() {
2595 global $wgUser, $wgOut, $wgRequest;
2597 $confirm = $wgRequest->wasPosted() &&
2598 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2600 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2601 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2603 $reason = $this->DeleteReasonList
;
2605 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2606 // Entry from drop down menu + additional comment
2607 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2608 } elseif ( $reason == 'other' ) {
2609 $reason = $this->DeleteReason
;
2611 # Flag to hide all contents of the archived revisions
2612 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2614 # This code desperately needs to be totally rewritten
2616 # Read-only check...
2617 if ( wfReadOnly() ) {
2618 $wgOut->readOnlyPage();
2623 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2625 if ( count( $permission_errors ) > 0 ) {
2626 $wgOut->showPermissionsErrorPage( $permission_errors );
2630 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2632 # Better double-check that it hasn't been deleted yet!
2633 $dbw = wfGetDB( DB_MASTER
);
2634 $conds = $this->mTitle
->pageCond();
2635 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2636 if ( $latest === false ) {
2637 $wgOut->showFatalError(
2640 array( 'class' => 'error mw-error-cannotdelete' ),
2641 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2644 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2645 LogEventsList
::showLogExtract(
2648 $this->mTitle
->getPrefixedText()
2653 # Hack for big sites
2654 $bigHistory = $this->isBigDeletion();
2655 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2656 global $wgLang, $wgDeleteRevisionsLimit;
2657 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2658 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2663 $this->doDelete( $reason, $suppress );
2664 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2666 } elseif ( $this->mTitle
->userIsWatching() ) {
2672 // Generate deletion reason
2673 $hasHistory = false;
2674 if ( !$reason ) $reason = $this->generateReason( $hasHistory );
2676 // If the page has a history, insert a warning
2677 if ( $hasHistory && !$confirm ) {
2679 $skin = $wgUser->getSkin();
2680 $revisions = $this->estimateRevisionCount();
2681 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2682 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2683 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2686 if ( $bigHistory ) {
2687 global $wgDeleteRevisionsLimit;
2688 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2689 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2693 return $this->confirmDelete( $reason );
2697 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2699 public function isBigDeletion() {
2700 global $wgDeleteRevisionsLimit;
2701 if ( $wgDeleteRevisionsLimit ) {
2702 $revCount = $this->estimateRevisionCount();
2703 return $revCount > $wgDeleteRevisionsLimit;
2709 * @return int approximate revision count
2711 public function estimateRevisionCount() {
2712 $dbr = wfGetDB( DB_SLAVE
);
2713 // For an exact count...
2714 // return $dbr->selectField( 'revision', 'COUNT(*)',
2715 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2716 return $dbr->estimateRowCount( 'revision', '*',
2717 array( 'rev_page' => $this->getId() ), __METHOD__
);
2721 * Get the last N authors
2722 * @param $num Integer: number of revisions to get
2723 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2724 * @return array Array of authors, duplicates not removed
2726 public function getLastNAuthors( $num, $revLatest = 0 ) {
2727 wfProfileIn( __METHOD__
);
2728 // First try the slave
2729 // If that doesn't have the latest revision, try the master
2731 $db = wfGetDB( DB_SLAVE
);
2733 $res = $db->select( array( 'page', 'revision' ),
2734 array( 'rev_id', 'rev_user_text' ),
2736 'page_namespace' => $this->mTitle
->getNamespace(),
2737 'page_title' => $this->mTitle
->getDBkey(),
2738 'rev_page = page_id'
2739 ), __METHOD__
, $this->getSelectOptions( array(
2740 'ORDER BY' => 'rev_timestamp DESC',
2745 wfProfileOut( __METHOD__
);
2748 $row = $db->fetchObject( $res );
2749 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2750 $db = wfGetDB( DB_MASTER
);
2755 } while ( $continue );
2757 $authors = array( $row->rev_user_text
);
2758 while ( $row = $db->fetchObject( $res ) ) {
2759 $authors[] = $row->rev_user_text
;
2761 wfProfileOut( __METHOD__
);
2766 * Output deletion confirmation dialog
2767 * @param $reason String: prefilled reason
2769 public function confirmDelete( $reason ) {
2770 global $wgOut, $wgUser;
2772 wfDebug( "Article::confirmDelete\n" );
2774 $deleteBackLink = $wgUser->getSkin()->link(
2779 array( 'known', 'noclasses' )
2781 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2782 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2783 $wgOut->addWikiMsg( 'confirmdeletetext' );
2785 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2787 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
2788 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2790 <td class='mw-input'><strong>" .
2791 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2792 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2798 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2800 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2801 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2802 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2803 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2804 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2805 "<tr id=\"wpDeleteReasonListRow\">
2806 <td class='mw-label'>" .
2807 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2809 <td class='mw-input'>" .
2810 Xml
::listDropDown( 'wpDeleteReasonList',
2811 wfMsgForContent( 'deletereason-dropdown' ),
2812 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2815 <tr id=\"wpDeleteReasonRow\">
2816 <td class='mw-label'>" .
2817 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2819 <td class='mw-input'>" .
2820 Html
::input( 'wpReason', $reason, 'text', array(
2822 'maxlength' => '255',
2829 # Dissalow watching is user is not logged in
2830 if ( $wgUser->isLoggedIn() ) {
2834 <td class='mw-input'>" .
2835 Xml
::checkLabel( wfMsg( 'watchthis' ),
2836 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2844 <td class='mw-submit'>" .
2845 Xml
::submitButton( wfMsg( 'deletepage' ),
2846 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2849 Xml
::closeElement( 'table' ) .
2850 Xml
::closeElement( 'fieldset' ) .
2851 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2852 Xml
::closeElement( 'form' );
2854 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2855 $skin = $wgUser->getSkin();
2856 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2857 $link = $skin->link(
2859 wfMsgHtml( 'delete-edit-reasonlist' ),
2861 array( 'action' => 'edit' )
2863 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2866 $wgOut->addHTML( $form );
2867 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2868 LogEventsList
::showLogExtract(
2871 $this->mTitle
->getPrefixedText()
2876 * Perform a deletion and output success or failure messages
2878 public function doDelete( $reason, $suppress = false ) {
2879 global $wgOut, $wgUser;
2880 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2883 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
2884 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2885 $deleted = $this->mTitle
->getPrefixedText();
2887 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2888 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2890 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2892 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2893 $wgOut->returnToMain( false );
2894 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
2897 if ( $error == '' ) {
2898 $wgOut->showFatalError(
2901 array( 'class' => 'error mw-error-cannotdelete' ),
2902 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2905 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2906 LogEventsList
::showLogExtract(
2909 $this->mTitle
->getPrefixedText()
2912 $wgOut->showFatalError( $error );
2918 * Back-end article deletion
2919 * Deletes the article with database consistency, writes logs, purges caches
2921 * @param $reason string delete reason for deletion log
2922 * @param suppress bitfield
2923 * Revision::DELETED_TEXT
2924 * Revision::DELETED_COMMENT
2925 * Revision::DELETED_USER
2926 * Revision::DELETED_RESTRICTED
2927 * @param $id int article ID
2928 * @param $commit boolean defaults to true, triggers transaction end
2929 * @return boolean true if successful
2931 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
2932 global $wgUseSquid, $wgDeferredUpdateList;
2933 global $wgUseTrackbacks;
2935 wfDebug( __METHOD__
. "\n" );
2937 $dbw = wfGetDB( DB_MASTER
);
2938 $ns = $this->mTitle
->getNamespace();
2939 $t = $this->mTitle
->getDBkey();
2940 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2942 if ( $t == '' ||
$id == 0 ) {
2946 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
2947 array_push( $wgDeferredUpdateList, $u );
2949 // Bitfields to further suppress the content
2952 // This should be 15...
2953 $bitfield |
= Revision
::DELETED_TEXT
;
2954 $bitfield |
= Revision
::DELETED_COMMENT
;
2955 $bitfield |
= Revision
::DELETED_USER
;
2956 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2958 $bitfield = 'rev_deleted';
2962 // For now, shunt the revision data into the archive table.
2963 // Text is *not* removed from the text table; bulk storage
2964 // is left intact to avoid breaking block-compression or
2965 // immutable storage schemes.
2967 // For backwards compatibility, note that some older archive
2968 // table entries will have ar_text and ar_flags fields still.
2970 // In the future, we may keep revisions and mark them with
2971 // the rev_deleted field, which is reserved for this purpose.
2972 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2974 'ar_namespace' => 'page_namespace',
2975 'ar_title' => 'page_title',
2976 'ar_comment' => 'rev_comment',
2977 'ar_user' => 'rev_user',
2978 'ar_user_text' => 'rev_user_text',
2979 'ar_timestamp' => 'rev_timestamp',
2980 'ar_minor_edit' => 'rev_minor_edit',
2981 'ar_rev_id' => 'rev_id',
2982 'ar_text_id' => 'rev_text_id',
2983 'ar_text' => '\'\'', // Be explicit to appease
2984 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2985 'ar_len' => 'rev_len',
2986 'ar_page_id' => 'page_id',
2987 'ar_deleted' => $bitfield
2990 'page_id = rev_page'
2994 # Delete restrictions for it
2995 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2997 # Now that it's safely backed up, delete it
2998 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2999 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3005 # Fix category table counts
3007 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3008 foreach ( $res as $row ) {
3009 $cats [] = $row->cl_to
;
3011 $this->updateCategoryCounts( array(), $cats );
3013 # If using cascading deletes, we can skip some explicit deletes
3014 if ( !$dbw->cascadingDeletes() ) {
3015 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3017 if ( $wgUseTrackbacks )
3018 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3020 # Delete outgoing links
3021 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3022 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3023 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3024 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3025 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3026 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3027 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3030 # If using cleanup triggers, we can skip some manual deletes
3031 if ( !$dbw->cleanupTriggers() ) {
3032 # Clean up recentchanges entries...
3033 $dbw->delete( 'recentchanges',
3034 array( 'rc_type != ' . RC_LOG
,
3035 'rc_namespace' => $this->mTitle
->getNamespace(),
3036 'rc_title' => $this->mTitle
->getDBkey() ),
3038 $dbw->delete( 'recentchanges',
3039 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3044 Article
::onArticleDelete( $this->mTitle
);
3046 # Clear the cached article id so the interface doesn't act like we exist
3047 $this->mTitle
->resetArticleID( 0 );
3049 # Log the deletion, if the page was suppressed, log it at Oversight instead
3050 $logtype = $suppress ?
'suppress' : 'delete';
3051 $log = new LogPage( $logtype );
3053 # Make sure logging got through
3054 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3064 * Roll back the most recent consecutive set of edits to a page
3065 * from the same user; fails if there are no eligible edits to
3066 * roll back to, e.g. user is the sole contributor. This function
3067 * performs permissions checks on $wgUser, then calls commitRollback()
3068 * to do the dirty work
3070 * @param $fromP String: Name of the user whose edits to rollback.
3071 * @param $summary String: Custom summary. Set to default summary if empty.
3072 * @param $token String: Rollback token.
3073 * @param $bot Boolean: If true, mark all reverted edits as bot.
3075 * @param $resultDetails Array: contains result-specific array of additional values
3076 * 'alreadyrolled' : 'current' (rev)
3077 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3079 * @return array of errors, each error formatted as
3080 * array(messagekey, param1, param2, ...).
3081 * On success, the array is empty. This array can also be passed to
3082 * OutputPage::showPermissionsErrorPage().
3084 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3086 $resultDetails = null;
3089 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3090 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3091 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3093 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
3094 $errors[] = array( 'sessionfailure' );
3096 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3097 $errors[] = array( 'actionthrottledtext' );
3099 # If there were errors, bail out now
3100 if ( !empty( $errors ) )
3103 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3107 * Backend implementation of doRollback(), please refer there for parameter
3108 * and return value documentation
3110 * NOTE: This function does NOT check ANY permissions, it just commits the
3111 * rollback to the DB Therefore, you should only call this function direct-
3112 * ly if you want to use custom permissions checks. If you don't, use
3113 * doRollback() instead.
3115 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3116 global $wgUseRCPatrol, $wgUser, $wgLang;
3117 $dbw = wfGetDB( DB_MASTER
);
3119 if ( wfReadOnly() ) {
3120 return array( array( 'readonlytext' ) );
3123 # Get the last editor
3124 $current = Revision
::newFromTitle( $this->mTitle
);
3125 if ( is_null( $current ) ) {
3126 # Something wrong... no page?
3127 return array( array( 'notanarticle' ) );
3130 $from = str_replace( '_', ' ', $fromP );
3131 # User name given should match up with the top revision.
3132 # If the user was deleted then $from should be empty.
3133 if ( $from != $current->getUserText() ) {
3134 $resultDetails = array( 'current' => $current );
3135 return array( array( 'alreadyrolled',
3136 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3137 htmlspecialchars( $fromP ),
3138 htmlspecialchars( $current->getUserText() )
3142 # Get the last edit not by this guy...
3143 # Note: these may not be public values
3144 $user = intval( $current->getRawUser() );
3145 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3146 $s = $dbw->selectRow( 'revision',
3147 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3148 array( 'rev_page' => $current->getPage(),
3149 "rev_user != {$user} OR rev_user_text != {$user_text}"
3151 array( 'USE INDEX' => 'page_timestamp',
3152 'ORDER BY' => 'rev_timestamp DESC' )
3154 if ( $s === false ) {
3155 # No one else ever edited this page
3156 return array( array( 'cantrollback' ) );
3157 } else if ( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
3158 # Only admins can see this text
3159 return array( array( 'notvisiblerev' ) );
3163 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3164 # Mark all reverted edits as bot
3167 if ( $wgUseRCPatrol ) {
3168 # Mark all reverted edits as patrolled
3169 $set['rc_patrolled'] = 1;
3172 if ( count( $set ) ) {
3173 $dbw->update( 'recentchanges', $set,
3175 'rc_cur_id' => $current->getPage(),
3176 'rc_user_text' => $current->getUserText(),
3177 "rc_timestamp > '{$s->rev_timestamp}'",
3182 # Generate the edit summary if necessary
3183 $target = Revision
::newFromId( $s->rev_id
);
3184 if ( empty( $summary ) ) {
3185 if ( $from == '' ) { // no public user name
3186 $summary = wfMsgForContent( 'revertpage-nouser' );
3188 $summary = wfMsgForContent( 'revertpage' );
3192 # Allow the custom summary to use the same args as the default message
3194 $target->getUserText(), $from, $s->rev_id
,
3195 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3196 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3198 $summary = wfMsgReplaceArgs( $summary, $args );
3201 $flags = EDIT_UPDATE
;
3203 if ( $wgUser->isAllowed( 'minoredit' ) )
3204 $flags |
= EDIT_MINOR
;
3206 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) ||
$wgUser->isAllowed( 'bot' ) ) )
3207 $flags |
= EDIT_FORCE_BOT
;
3208 # Actually store the edit
3209 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3210 if ( !empty( $status->value
['revision'] ) ) {
3211 $revId = $status->value
['revision']->getId();
3216 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3218 $resultDetails = array(
3219 'summary' => $summary,
3220 'current' => $current,
3221 'target' => $target,
3228 * User interface for rollback operations
3230 public function rollback() {
3231 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3234 $result = $this->doRollback(
3235 $wgRequest->getVal( 'from' ),
3236 $wgRequest->getText( 'summary' ),
3237 $wgRequest->getVal( 'token' ),
3238 $wgRequest->getBool( 'bot' ),
3242 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3243 $wgOut->rateLimited();
3246 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3247 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3248 $errArray = $result[0];
3249 $errMsg = array_shift( $errArray );
3250 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3251 if ( isset( $details['current'] ) ) {
3252 $current = $details['current'];
3253 if ( $current->getComment() != '' ) {
3254 $wgOut->addWikiMsgArray( 'editcomment', array(
3255 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3260 # Display permissions errors before read-only message -- there's no
3261 # point in misleading the user into thinking the inability to rollback
3262 # is only temporary.
3263 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3264 # array_diff is completely broken for arrays of arrays, sigh. Re-
3265 # move any 'readonlytext' error manually.
3267 foreach ( $result as $error ) {
3268 if ( $error != array( 'readonlytext' ) ) {
3272 $wgOut->showPermissionsErrorPage( $out );
3275 if ( $result == array( array( 'readonlytext' ) ) ) {
3276 $wgOut->readOnlyPage();
3280 $current = $details['current'];
3281 $target = $details['target'];
3282 $newId = $details['newid'];
3283 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3284 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3285 if ( $current->getUserText() === '' ) {
3286 $old = wfMsg( 'rev-deleted-user' );
3288 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3289 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3291 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3292 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3293 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3294 $wgOut->returnToMain( false, $this->mTitle
);
3296 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3297 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3298 $de->showDiff( '', '' );
3304 * Do standard deferred updates after page view
3306 public function viewUpdates() {
3307 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3308 if ( wfReadOnly() ) {
3311 # Don't update page view counters on views from bot users (bug 14044)
3312 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3313 Article
::incViewCount( $this->getID() );
3314 $u = new SiteStatsUpdate( 1, 0, 0 );
3315 array_push( $wgDeferredUpdateList, $u );
3317 # Update newtalk / watchlist notification status
3318 $wgUser->clearNotification( $this->mTitle
);
3322 * Prepare text which is about to be saved.
3323 * Returns a stdclass with source, pst and output members
3325 public function prepareTextForEdit( $text, $revid = null ) {
3326 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3328 return $this->mPreparedEdit
;
3331 $edit = (object)array();
3332 $edit->revid
= $revid;
3333 $edit->newText
= $text;
3334 $edit->pst
= $this->preSaveTransform( $text );
3335 $options = $this->getParserOptions();
3336 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
3337 $edit->oldText
= $this->getContent();
3338 $this->mPreparedEdit
= $edit;
3343 * Do standard deferred updates after page edit.
3344 * Update links tables, site stats, search index and message cache.
3345 * Purges pages that include this page if the text was changed here.
3346 * Every 100th edit, prune the recent changes table.
3349 * @param $text New text of the article
3350 * @param $summary Edit summary
3351 * @param $minoredit Minor edit
3352 * @param $timestamp_of_pagechange Timestamp associated with the page change
3353 * @param $newid rev_id value of the new revision
3354 * @param $changed Whether or not the content actually changed
3356 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3357 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3359 wfProfileIn( __METHOD__
);
3362 # Be careful not to double-PST: $text is usually already PST-ed once
3363 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3364 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3365 $editInfo = $this->prepareTextForEdit( $text, $newid );
3367 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3368 $editInfo = $this->mPreparedEdit
;
3371 # Save it to the parser cache
3372 if ( $wgEnableParserCache ) {
3373 $popts = $this->getParserOptions();
3374 $parserCache = ParserCache
::singleton();
3375 $parserCache->save( $editInfo->output
, $this, $popts );
3378 # Update the links tables
3379 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3382 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3384 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3385 if ( 0 == mt_rand( 0, 99 ) ) {
3386 // Flush old entries from the `recentchanges` table; we do this on
3387 // random requests so as to avoid an increase in writes for no good reason
3389 $dbw = wfGetDB( DB_MASTER
);
3390 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3391 $recentchanges = $dbw->tableName( 'recentchanges' );
3392 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3393 $dbw->query( $sql );
3397 $id = $this->getID();
3398 $title = $this->mTitle
->getPrefixedDBkey();
3399 $shortTitle = $this->mTitle
->getDBkey();
3402 wfProfileOut( __METHOD__
);
3406 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3407 array_push( $wgDeferredUpdateList, $u );
3408 $u = new SearchUpdate( $id, $title, $text );
3409 array_push( $wgDeferredUpdateList, $u );
3411 # If this is another user's talk page, update newtalk
3412 # Don't do this if $changed = false otherwise some idiot can null-edit a
3413 # load of user talk pages and piss people off, nor if it's a minor edit
3414 # by a properly-flagged bot.
3415 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3416 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3417 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3418 $other = User
::newFromName( $shortTitle, false );
3420 wfDebug( __METHOD__
. ": invalid username\n" );
3421 } elseif ( User
::isIP( $shortTitle ) ) {
3422 // An anonymous user
3423 $other->setNewtalk( true );
3424 } elseif ( $other->isLoggedIn() ) {
3425 $other->setNewtalk( true );
3427 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3432 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3433 $wgMessageCache->replace( $shortTitle, $text );
3436 wfProfileOut( __METHOD__
);
3440 * Perform article updates on a special page creation.
3442 * @param $rev Revision object
3444 * @todo This is a shitty interface function. Kill it and replace the
3445 * other shitty functions like editUpdates and such so it's not needed
3448 public function createUpdates( $rev ) {
3449 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3450 $this->mTotalAdjustment
= 1;
3451 $this->editUpdates( $rev->getText(), $rev->getComment(),
3452 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3456 * Generate the navigation links when browsing through an article revisions
3457 * It shows the information as:
3458 * Revision as of \<date\>; view current revision
3459 * \<- Previous version | Next Version -\>
3461 * @param $oldid String: revision ID of this article revision
3463 public function setOldSubtitle( $oldid = 0 ) {
3464 global $wgLang, $wgOut, $wgUser, $wgRequest;
3466 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3470 $unhide = $wgRequest->getInt( 'unhide' ) == 1 &&
3471 $wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $oldid );
3472 # Cascade unhide param in links for easy deletion browsing
3473 $extraParams = array();
3474 if ( $wgRequest->getVal( 'unhide' ) ) {
3475 $extraParams['unhide'] = 1;
3477 $revision = Revision
::newFromId( $oldid );
3479 $current = ( $oldid == $this->mLatest
);
3480 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3481 $tddate = $wgLang->date( $this->mTimestamp
, true );
3482 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3483 $sk = $wgUser->getSkin();
3485 ?
wfMsgHtml( 'currentrevisionlink' )
3488 wfMsgHtml( 'currentrevisionlink' ),
3491 array( 'known', 'noclasses' )
3494 ?
wfMsgHtml( 'diff' )
3497 wfMsgHtml( 'diff' ),
3503 array( 'known', 'noclasses' )
3505 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3509 wfMsgHtml( 'previousrevision' ),
3512 'direction' => 'prev',
3515 array( 'known', 'noclasses' )
3517 : wfMsgHtml( 'previousrevision' );
3521 wfMsgHtml( 'diff' ),
3527 array( 'known', 'noclasses' )
3529 : wfMsgHtml( 'diff' );
3530 $nextlink = $current
3531 ?
wfMsgHtml( 'nextrevision' )
3534 wfMsgHtml( 'nextrevision' ),
3537 'direction' => 'next',
3540 array( 'known', 'noclasses' )
3542 $nextdiff = $current
3543 ?
wfMsgHtml( 'diff' )
3546 wfMsgHtml( 'diff' ),
3552 array( 'known', 'noclasses' )
3556 // User can delete revisions or view deleted revisions...
3557 $canHide = $wgUser->isAllowed( 'deleterevision' );
3558 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3559 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3560 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3563 'type' => 'revision',
3564 'target' => $this->mTitle
->getPrefixedDbkey(),
3567 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3572 # Show user links if allowed to see them. If hidden, then show them only if requested...
3573 $userlinks = $sk->revUserTools( $revision, !$unhide );
3575 $m = wfMsg( 'revision-info-current' );
3576 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3577 ?
'revision-info-current'
3580 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3583 array( 'parseinline', 'replaceafter' ),
3589 $revision->getUser()
3592 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3593 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3594 $wgOut->setSubtitle( $r );
3598 * This function is called right before saving the wikitext,
3599 * so we can do things like signatures and links-in-context.
3601 * @param $text String article contents
3602 * @return string article contents with altered wikitext markup (signatures
3603 * converted, {{subst:}}, templates, etc.)
3605 public function preSaveTransform( $text ) {
3606 global $wgParser, $wgUser;
3607 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3610 /* Caching functions */
3613 * checkLastModified returns true if it has taken care of all
3614 * output to the client that is necessary for this request.
3615 * (that is, it has sent a cached version of the page)
3617 * @return boolean true if cached version send, false otherwise
3619 protected function tryFileCache() {
3620 static $called = false;
3622 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3626 if ( $this->isFileCacheable() ) {
3627 $cache = new HTMLFileCache( $this->mTitle
);
3628 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3629 wfDebug( "Article::tryFileCache(): about to load file\n" );
3630 $cache->loadFromFileCache();
3633 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3634 ob_start( array( &$cache, 'saveToFileCache' ) );
3637 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3643 * Check if the page can be cached
3646 public function isFileCacheable() {
3648 if ( HTMLFileCache
::useFileCache() ) {
3649 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3650 // Extension may have reason to disable file caching on some pages.
3652 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3659 * Loads page_touched and returns a value indicating if it should be used
3660 * @return boolean true if not a redirect
3662 public function checkTouched() {
3663 if ( !$this->mDataLoaded
) {
3664 $this->loadPageData();
3666 return !$this->mIsRedirect
;
3670 * Get the page_touched field
3671 * @return string containing GMT timestamp
3673 public function getTouched() {
3674 # Ensure that page data has been loaded
3675 if ( !$this->mDataLoaded
) {
3676 $this->loadPageData();
3678 return $this->mTouched
;
3682 * Get the page_latest field
3683 * @return integer rev_id of current revision
3685 public function getLatest() {
3686 if ( !$this->mDataLoaded
) {
3687 $this->loadPageData();
3689 return (int)$this->mLatest
;
3693 * Edit an article without doing all that other stuff
3694 * The article must already exist; link tables etc
3695 * are not updated, caches are not flushed.
3697 * @param $text String: text submitted
3698 * @param $comment String: comment submitted
3699 * @param $minor Boolean: whereas it's a minor modification
3701 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3702 wfProfileIn( __METHOD__
);
3704 $dbw = wfGetDB( DB_MASTER
);
3705 $revision = new Revision( array(
3706 'page' => $this->getId(),
3708 'comment' => $comment,
3709 'minor_edit' => $minor ?
1 : 0,
3711 $revision->insertOn( $dbw );
3712 $this->updateRevisionOn( $dbw, $revision );
3714 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3716 wfProfileOut( __METHOD__
);
3720 * Used to increment the view counter
3722 * @param $id Integer: article id
3724 public static function incViewCount( $id ) {
3725 $id = intval( $id );
3726 global $wgHitcounterUpdateFreq;
3728 $dbw = wfGetDB( DB_MASTER
);
3729 $pageTable = $dbw->tableName( 'page' );
3730 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3731 $acchitsTable = $dbw->tableName( 'acchits' );
3733 if ( $wgHitcounterUpdateFreq <= 1 ) {
3734 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3738 # Not important enough to warrant an error page in case of failure
3739 $oldignore = $dbw->ignoreErrors( true );
3741 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3743 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 +
1 );
3744 if ( ( rand() %
$checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
3745 # Most of the time (or on SQL errors), skip row count check
3746 $dbw->ignoreErrors( $oldignore );
3750 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
3751 $row = $dbw->fetchObject( $res );
3752 $rown = intval( $row->n
);
3753 if ( $rown >= $wgHitcounterUpdateFreq ) {
3754 wfProfileIn( 'Article::incViewCount-collect' );
3755 $old_user_abort = ignore_user_abort( true );
3757 $dbType = $dbw->getType();
3758 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__
, false );
3759 $tabletype = $dbType == 'mysql' ?
"ENGINE=HEAP " : '';
3760 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
3761 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
3762 'GROUP BY hc_id', __METHOD__
);
3763 $dbw->delete( 'hitcounter', '*', __METHOD__
);
3764 $dbw->unlockTables( __METHOD__
);
3765 if ( $dbType == 'mysql' ) {
3766 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
3767 'WHERE page_id = hc_id', __METHOD__
);
3770 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
3771 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__
);
3773 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__
);
3775 ignore_user_abort( $old_user_abort );
3776 wfProfileOut( 'Article::incViewCount-collect' );
3778 $dbw->ignoreErrors( $oldignore );
3782 * The onArticle*() functions are supposed to be a kind of hooks
3783 * which should be called whenever any of the specified actions
3786 * This is a good place to put code to clear caches, for instance.
3788 * This is called on page move and undelete, as well as edit
3790 * @param $title a title object
3792 public static function onArticleCreate( $title ) {
3793 # Update existence markers on article/talk tabs...
3794 if ( $title->isTalkPage() ) {
3795 $other = $title->getSubjectPage();
3797 $other = $title->getTalkPage();
3799 $other->invalidateCache();
3800 $other->purgeSquid();
3802 $title->touchLinks();
3803 $title->purgeSquid();
3804 $title->deleteTitleProtection();
3808 * Clears caches when article is deleted
3810 public static function onArticleDelete( $title ) {
3811 global $wgMessageCache;
3812 # Update existence markers on article/talk tabs...
3813 if ( $title->isTalkPage() ) {
3814 $other = $title->getSubjectPage();
3816 $other = $title->getTalkPage();
3818 $other->invalidateCache();
3819 $other->purgeSquid();
3821 $title->touchLinks();
3822 $title->purgeSquid();
3825 HTMLFileCache
::clearFileCache( $title );
3828 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3829 $wgMessageCache->replace( $title->getDBkey(), false );
3832 if ( $title->getNamespace() == NS_FILE
) {
3833 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3834 $update->doUpdate();
3837 if ( $title->getNamespace() == NS_USER_TALK
) {
3838 $user = User
::newFromName( $title->getText(), false );
3839 $user->setNewtalk( false );
3842 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3846 * Purge caches on page update etc
3848 * @param $title Title object
3849 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3851 public static function onArticleEdit( $title ) {
3852 global $wgDeferredUpdateList;
3854 // Invalidate caches of articles which include this page
3855 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3857 // Invalidate the caches of all pages which redirect here
3858 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3860 # Purge squid for this page only
3861 $title->purgeSquid();
3863 # Clear file cache for this page only
3864 HTMLFileCache
::clearFileCache( $title );
3870 * Overriden by ImagePage class, only present here to avoid a fatal error
3871 * Called for ?action=revert
3873 public function revert() {
3875 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3879 * Info about this page
3880 * Called for ?action=info when $wgAllowPageInfo is on.
3882 public function info() {
3883 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3885 if ( !$wgAllowPageInfo ) {
3886 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3890 $page = $this->mTitle
->getSubjectPage();
3892 $wgOut->setPagetitle( $page->getPrefixedText() );
3893 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3894 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3896 if ( !$this->mTitle
->exists() ) {
3897 $wgOut->addHTML( '<div class="noarticletext">' );
3898 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3899 // This doesn't quite make sense; the user is asking for
3900 // information about the _page_, not the message... -- RC
3901 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3903 $msg = $wgUser->isLoggedIn()
3905 : 'noarticletextanon';
3906 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3908 $wgOut->addHTML( '</div>' );
3910 $dbr = wfGetDB( DB_SLAVE
);
3912 'wl_title' => $page->getDBkey(),
3913 'wl_namespace' => $page->getNamespace() );
3914 $numwatchers = $dbr->selectField(
3919 $this->getSelectOptions() );
3921 $pageInfo = $this->pageCountInfo( $page );
3922 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3924 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3925 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
3927 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
3929 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3931 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3933 $wgOut->addHTML( '</ul>' );
3938 * Return the total number of edits and number of unique editors
3939 * on a given page. If page does not exist, returns false.
3941 * @param $title Title object
3942 * @return mixed array or boolean false
3944 public function pageCountInfo( $title ) {
3945 $id = $title->getArticleId();
3949 $dbr = wfGetDB( DB_SLAVE
);
3950 $rev_clause = array( 'rev_page' => $id );
3951 $edits = $dbr->selectField(
3956 $this->getSelectOptions()
3958 $authors = $dbr->selectField(
3960 'COUNT(DISTINCT rev_user_text)',
3963 $this->getSelectOptions()
3965 return array( 'edits' => $edits, 'authors' => $authors );
3969 * Return a list of templates used by this article.
3970 * Uses the templatelinks table
3972 * @return Array of Title objects
3974 public function getUsedTemplates() {
3976 $id = $this->mTitle
->getArticleID();
3980 $dbr = wfGetDB( DB_SLAVE
);
3981 $res = $dbr->select( array( 'templatelinks' ),
3982 array( 'tl_namespace', 'tl_title' ),
3983 array( 'tl_from' => $id ),
3985 if ( $res !== false ) {
3986 foreach ( $res as $row ) {
3987 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3990 $dbr->freeResult( $res );
3995 * Returns a list of hidden categories this page is a member of.
3996 * Uses the page_props and categorylinks tables.
3998 * @return Array of Title objects
4000 public function getHiddenCategories() {
4002 $id = $this->mTitle
->getArticleID();
4006 $dbr = wfGetDB( DB_SLAVE
);
4007 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4009 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4010 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4012 if ( $res !== false ) {
4013 foreach ( $res as $row ) {
4014 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4017 $dbr->freeResult( $res );
4022 * Return an applicable autosummary if one exists for the given edit.
4023 * @param $oldtext String: the previous text of the page.
4024 * @param $newtext String: The submitted text of the page.
4025 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4026 * @return string An appropriate autosummary, or an empty string.
4028 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4029 # Decide what kind of autosummary is needed.
4031 # Redirect autosummaries
4032 $ot = Title
::newFromRedirect( $oldtext );
4033 $rt = Title
::newFromRedirect( $newtext );
4034 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4035 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4038 # New page autosummaries
4039 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4040 # If they're making a new article, give its text, truncated, in the summary.
4042 $truncatedtext = $wgContLang->truncate(
4043 str_replace( "\n", ' ', $newtext ),
4044 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4045 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4048 # Blanking autosummaries
4049 if ( $oldtext != '' && $newtext == '' ) {
4050 return wfMsgForContent( 'autosumm-blank' );
4051 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4052 # Removing more than 90% of the article
4054 $truncatedtext = $wgContLang->truncate(
4056 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4057 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4060 # If we reach this point, there's no applicable autosummary for our case, so our
4061 # autosummary is empty.
4066 * Add the primary page-view wikitext to the output buffer
4067 * Saves the text into the parser cache if possible.
4068 * Updates templatelinks if it is out of date.
4070 * @param $text String
4071 * @param $cache Boolean
4072 * @param $parserOptions mixed ParserOptions object, or boolean false
4074 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4077 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4078 $wgOut->addParserOutput( $this->mParserOutput
);
4082 * This does all the heavy lifting for outputWikitext, except it returns the parser
4083 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4084 * say, embedding thread pages within a discussion system (LiquidThreads)
4086 * @param $text string
4087 * @param $cache boolean
4088 * @param $parserOptions parsing options, defaults to false
4089 * @return string containing parsed output
4091 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4092 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4094 if ( !$parserOptions ) {
4095 $parserOptions = $this->getParserOptions();
4099 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4100 $parserOptions, true, true, $this->getRevIdFetched() );
4105 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4106 $this->mTitle
->getPrefixedDBkey() ) );
4109 if ( $wgEnableParserCache && $cache && $this && $this->mParserOutput
->getCacheTime() != -1 ) {
4110 $parserCache = ParserCache
::singleton();
4111 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4113 // Make sure file cache is not used on uncacheable content.
4114 // Output that has magic words in it can still use the parser cache
4115 // (if enabled), though it will generally expire sooner.
4116 if ( $this->mParserOutput
->getCacheTime() == -1 ||
$this->mParserOutput
->containsOldMagic() ) {
4117 $wgUseFileCache = false;
4119 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4120 return $this->mParserOutput
;
4124 * Get parser options suitable for rendering the primary article wikitext
4125 * @return mixed ParserOptions object or boolean false
4127 public function getParserOptions() {
4129 if ( !$this->mParserOptions
) {
4130 $this->mParserOptions
= new ParserOptions( $wgUser );
4131 $this->mParserOptions
->setTidy( true );
4132 $this->mParserOptions
->enableLimitReport();
4134 return $this->mParserOptions
;
4138 * Updates cascading protections
4140 * @param $parserOutput mixed ParserOptions object, or boolean false
4143 protected function doCascadeProtectionUpdates( $parserOutput ) {
4144 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4148 // templatelinks table may have become out of sync,
4149 // especially if using variable-based transclusions.
4150 // For paranoia, check if things have changed and if
4151 // so apply updates to the database. This will ensure
4152 // that cascaded protections apply as soon as the changes
4155 # Get templates from templatelinks
4156 $id = $this->mTitle
->getArticleID();
4158 $tlTemplates = array();
4160 $dbr = wfGetDB( DB_SLAVE
);
4161 $res = $dbr->select( array( 'templatelinks' ),
4162 array( 'tl_namespace', 'tl_title' ),
4163 array( 'tl_from' => $id ),
4167 foreach ( $res as $row ) {
4168 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4171 # Get templates from parser output.
4172 $poTemplates = array();
4173 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4174 foreach ( $templates as $dbk => $id ) {
4175 $poTemplates["$ns:$dbk"] = true;
4180 # Note that we simulate array_diff_key in PHP <5.0.x
4181 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4183 if ( count( $templates_diff ) > 0 ) {
4184 # Whee, link updates time.
4185 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4191 * Update all the appropriate counts in the category table, given that
4192 * we've added the categories $added and deleted the categories $deleted.
4194 * @param $added array The names of categories that were added
4195 * @param $deleted array The names of categories that were deleted
4197 public function updateCategoryCounts( $added, $deleted ) {
4198 $ns = $this->mTitle
->getNamespace();
4199 $dbw = wfGetDB( DB_MASTER
);
4201 # First make sure the rows exist. If one of the "deleted" ones didn't
4202 # exist, we might legitimately not create it, but it's simpler to just
4203 # create it and then give it a negative value, since the value is bogus
4206 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4207 $insertCats = array_merge( $added, $deleted );
4208 if ( !$insertCats ) {
4209 # Okay, nothing to do
4212 $insertRows = array();
4213 foreach ( $insertCats as $cat ) {
4214 $insertRows[] = array(
4215 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4219 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4221 $addFields = array( 'cat_pages = cat_pages + 1' );
4222 $removeFields = array( 'cat_pages = cat_pages - 1' );
4223 if ( $ns == NS_CATEGORY
) {
4224 $addFields[] = 'cat_subcats = cat_subcats + 1';
4225 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4226 } elseif ( $ns == NS_FILE
) {
4227 $addFields[] = 'cat_files = cat_files + 1';
4228 $removeFields[] = 'cat_files = cat_files - 1';
4235 array( 'cat_title' => $added ),
4243 array( 'cat_title' => $deleted ),
4250 * Lightweight method to get the parser output for a page, checking the parser cache
4251 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4252 * consider, so it's not appropriate to use there.
4254 * @param $oldid mixed integer Revision ID or null
4256 public function getParserOutput( $oldid = null ) {
4257 global $wgEnableParserCache, $wgUser, $wgOut;
4259 // Should the parser cache be used?
4260 $useParserCache = $wgEnableParserCache &&
4261 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4265 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4266 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4267 wfIncrStats( 'pcache_miss_stub' );
4270 $parserOutput = false;
4271 if ( $useParserCache ) {
4272 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4275 if ( $parserOutput === false ) {
4276 // Cache miss; parse and output it.
4277 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4279 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4281 return $parserOutput;