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.
19 var $mComment = ''; // !<
21 var $mContentLoaded = false; // !<
22 var $mCounter = -1; // !< Not loaded
23 var $mCurID = -1; // !< Not loaded
24 var $mDataLoaded = false; // !<
25 var $mForUpdate = false; // !<
26 var $mGoodAdjustment = 0; // !<
27 var $mIsRedirect = false; // !<
28 var $mLatest = false; // !<
29 var $mMinorEdit; // !<
31 var $mPreparedEdit = false; // !< Title object if set
32 var $mRedirectedFrom = null; // !< Title object if set
33 var $mRedirectTarget = null; // !< Title object if set
34 var $mRedirectUrl = false; // !<
35 var $mRevIdFetched = 0; // !<
36 var $mRevision; // !< Revision object if set
37 var $mTimestamp = ''; // !<
38 var $mTitle; // !< Title object
39 var $mTotalAdjustment = 0; // !<
40 var $mTouched = '19700101000000'; // !<
41 var $mUser = -1; // !< Not loaded
42 var $mUserText = ''; // !<
43 var $mParserOptions; // !< ParserOptions object
44 var $mParserOutput; // !< ParserCache object if set
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
52 public function __construct( Title
$title, $oldId = null ) {
53 $this->mTitle
=& $title;
54 $this->mOldId
= $oldId;
58 * Constructor from an article article
59 * @param $id The article ID to load
61 public static function newFromID( $id ) {
62 $t = Title
::newFromID( $id );
63 # FIXME: doesn't inherit right
64 return $t == null ?
null : new self( $t );
65 # return $t == null ? null : new static( $t ); // PHP 5.3
69 * Tell the page view functions that this view was redirected
70 * from another page on the wiki.
71 * @param $from Title object.
73 public function setRedirectedFrom( Title
$from ) {
74 $this->mRedirectedFrom
= $from;
78 * If this page is a redirect, get its target
80 * The target will be fetched from the redirect table if possible.
81 * If this page doesn't have an entry there, call insertRedirect()
82 * @return mixed Title object, or null if this page is not a redirect
84 public function getRedirectTarget() {
85 if ( !$this->mTitle ||
!$this->mTitle
->isRedirect() )
87 if ( !is_null( $this->mRedirectTarget
) )
88 return $this->mRedirectTarget
;
89 # Query the redirect table
90 $dbr = wfGetDB( DB_SLAVE
);
91 $row = $dbr->selectRow( 'redirect',
92 array( 'rd_namespace', 'rd_title' ),
93 array( 'rd_from' => $this->getID() ),
97 return $this->mRedirectTarget
= Title
::makeTitle( $row->rd_namespace
, $row->rd_title
);
99 # This page doesn't have an entry in the redirect table
100 return $this->mRedirectTarget
= $this->insertRedirect();
104 * Insert an entry for this page into the redirect table.
106 * Don't call this function directly unless you know what you're doing.
107 * @return Title object
109 public function insertRedirect() {
110 $retval = Title
::newFromRedirect( $this->getContent() );
114 $dbw = wfGetDB( DB_MASTER
);
115 $dbw->replace( 'redirect', array( 'rd_from' ),
117 'rd_from' => $this->getID(),
118 'rd_namespace' => $retval->getNamespace(),
119 'rd_title' => $retval->getDBkey()
127 * Get the Title object this page redirects to
129 * @return mixed false, Title of in-wiki target, or string with URL
131 public function followRedirect() {
132 $text = $this->getContent();
133 return $this->followRedirectText( $text );
137 * Get the Title object this text redirects to
139 * @param $text string article content containing redirect info
140 * @return mixed false, Title of in-wiki target, or string with URL
142 public function followRedirectText( $text ) {
143 $rt = Title
::newFromRedirectRecurse( $text ); // recurse through to only get the final target
144 # process if title object is valid and not special:userlogout
146 if ( $rt->getInterwiki() != '' ) {
147 if ( $rt->isLocal() ) {
148 // Offsite wikis need an HTTP redirect.
150 // This can be hard to reverse and may produce loops,
151 // so they may be disabled in the site configuration.
152 $source = $this->mTitle
->getFullURL( 'redirect=no' );
153 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
156 if ( $rt->getNamespace() == NS_SPECIAL
) {
157 // Gotta handle redirects to special pages differently:
158 // Fill the HTTP response "Location" header and ignore
159 // the rest of the page we're on.
161 // This can be hard to reverse, so they may be disabled.
162 if ( $rt->isSpecial( 'Userlogout' ) ) {
165 return $rt->getFullURL();
171 // No or invalid redirect
176 * get the title object of the article
177 * @return Title object of current title
179 public function getTitle() {
180 return $this->mTitle
;
187 public function clear() {
188 $this->mDataLoaded
= false;
189 $this->mContentLoaded
= false;
191 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
192 $this->mRedirectedFrom
= null; # Title object if set
193 $this->mRedirectTarget
= null; # Title object if set
195 $this->mTimestamp
= $this->mComment
= '';
196 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
197 $this->mTouched
= '19700101000000';
198 $this->mForUpdate
= false;
199 $this->mIsRedirect
= false;
200 $this->mRevIdFetched
= 0;
201 $this->mRedirectUrl
= false;
202 $this->mLatest
= false;
203 $this->mPreparedEdit
= false;
207 * Note that getContent/loadContent do not follow redirects anymore.
208 * If you need to fetch redirectable content easily, try
209 * the shortcut in Article::followContent()
211 * @return Return the text of this revision
213 public function getContent() {
214 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
215 wfProfileIn( __METHOD__
);
216 if ( $this->getID() === 0 ) {
217 # If this is a MediaWiki:x message, then load the messages
218 # and return the message value for x.
219 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
220 # If this is a system message, get the default text.
221 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
222 $wgMessageCache->loadAllMessages( $lang );
223 $text = wfMsgGetKey( $message, false, $lang, false );
224 if ( wfEmptyMsg( $message, $text ) )
227 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
229 wfProfileOut( __METHOD__
);
232 $this->loadContent();
233 wfProfileOut( __METHOD__
);
234 return $this->mContent
;
239 * Get the text of the current revision. No side-effects...
241 * @return Return the text of the current revision
243 public function getRawText() {
244 // Check process cache for current revision
245 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
246 return $this->mContent
;
248 $rev = Revision
::newFromTitle( $this->mTitle
);
249 $text = $rev ?
$rev->getRawText() : false;
254 * This function returns the text of a section, specified by a number ($section).
255 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
256 * the first section before any such heading (section 0).
258 * If a section contains subsections, these are also returned.
260 * @param $text String: text to look in
261 * @param $section Integer: section number
262 * @return string text of the requested section
265 public function getSection( $text, $section ) {
267 return $wgParser->getSection( $text, $section );
271 * Get the text that needs to be saved in order to undo all revisions
272 * between $undo and $undoafter. Revisions must belong to the same page,
273 * must exist and must not be deleted
274 * @param $undo Revision
275 * @param $undoafter Revision Must be an earlier revision than $undo
276 * @return mixed string on success, false on failure
278 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
279 $undo_text = $undo->getText();
280 $undoafter_text = $undoafter->getText();
281 $cur_text = $this->getContent();
282 if ( $cur_text == $undo_text ) {
283 # No use doing a merge if it's just a straight revert.
284 return $undoafter_text;
287 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
293 * @return int The oldid of the article that is to be shown, 0 for the
296 public function getOldID() {
297 if ( is_null( $this->mOldId
) ) {
298 $this->mOldId
= $this->getOldIDFromRequest();
300 return $this->mOldId
;
304 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
306 * @return int The old id for the request
308 public function getOldIDFromRequest() {
310 $this->mRedirectUrl
= false;
311 $oldid = $wgRequest->getVal( 'oldid' );
312 if ( isset( $oldid ) ) {
313 $oldid = intval( $oldid );
314 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
315 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
319 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
321 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
322 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
335 * Load the revision (including text) into this object
337 function loadContent() {
338 if ( $this->mContentLoaded
) return;
339 wfProfileIn( __METHOD__
);
341 $oldid = $this->getOldID();
342 # Pre-fill content with error message so that if something
343 # fails we'll have something telling us what we intended.
344 $this->mOldId
= $oldid;
345 $this->fetchContent( $oldid );
346 wfProfileOut( __METHOD__
);
351 * Fetch a page record with the given conditions
352 * @param $dbr Database object
353 * @param $conditions Array
354 * @return mixed Database result resource, or false on failure
356 protected function pageData( $dbr, $conditions ) {
370 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
371 $row = $dbr->selectRow(
377 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
382 * Fetch a page record matching the Title object's namespace and title
383 * using a sanitized title string
385 * @param $dbr Database object
386 * @param $title Title object
387 * @return mixed Database result resource, or false on failure
389 public function pageDataFromTitle( $dbr, $title ) {
390 return $this->pageData( $dbr, array(
391 'page_namespace' => $title->getNamespace(),
392 'page_title' => $title->getDBkey() ) );
396 * Fetch a page record matching the requested ID
398 * @param $dbr Database
401 protected function pageDataFromId( $dbr, $id ) {
402 return $this->pageData( $dbr, array( 'page_id' => $id ) );
406 * Set the general counter, title etc data loaded from
409 * @param $data Database row object or "fromdb"
411 public function loadPageData( $data = 'fromdb' ) {
412 if ( $data === 'fromdb' ) {
413 $dbr = wfGetDB( DB_MASTER
);
414 $data = $this->pageDataFromId( $dbr, $this->getId() );
417 $lc = LinkCache
::singleton();
419 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
421 $this->mTitle
->mArticleID
= intval( $data->page_id
);
423 # Old-fashioned restrictions
424 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
426 $this->mCounter
= intval( $data->page_counter
);
427 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
428 $this->mIsRedirect
= intval( $data->page_is_redirect
);
429 $this->mLatest
= intval( $data->page_latest
);
431 if ( is_object( $this->mTitle
) ) {
432 $lc->addBadLinkObj( $this->mTitle
);
434 $this->mTitle
->mArticleID
= 0;
437 $this->mDataLoaded
= true;
441 * Get text of an article from database
442 * Does *NOT* follow redirects.
444 * @param $oldid Int: 0 for whatever the latest revision is
445 * @return mixed string containing article contents, or false if null
447 function fetchContent( $oldid = 0 ) {
448 if ( $this->mContentLoaded
) {
449 return $this->mContent
;
452 $dbr = wfGetDB( DB_MASTER
);
454 # Pre-fill content with error message so that if something
455 # fails we'll have something telling us what we intended.
456 $t = $this->mTitle
->getPrefixedText();
457 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
458 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
461 $revision = Revision
::newFromId( $oldid );
462 if ( is_null( $revision ) ) {
463 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
466 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
468 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
471 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
472 $this->loadPageData( $data );
474 if ( !$this->mDataLoaded
) {
475 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
477 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
480 $this->loadPageData( $data );
482 $revision = Revision
::newFromId( $this->mLatest
);
483 if ( is_null( $revision ) ) {
484 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
489 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
490 // We should instead work with the Revision object when we need it...
491 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
493 $this->mUser
= $revision->getUser();
494 $this->mUserText
= $revision->getUserText();
495 $this->mComment
= $revision->getComment();
496 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
498 $this->mRevIdFetched
= $revision->getId();
499 $this->mContentLoaded
= true;
500 $this->mRevision
=& $revision;
502 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
504 return $this->mContent
;
508 * Read/write accessor to select FOR UPDATE
510 * @param $x Mixed: FIXME
511 * @return mixed value of $x, or value stored in Article::mForUpdate
513 public function forUpdate( $x = null ) {
514 return wfSetVar( $this->mForUpdate
, $x );
518 * Get the database which should be used for reads
521 * @deprecated - just call wfGetDB( DB_MASTER ) instead
524 wfDeprecated( __METHOD__
);
525 return wfGetDB( DB_MASTER
);
529 * Get options for all SELECT statements
531 * @param $options Array: an optional options array which'll be appended to
533 * @return Array: options
535 protected function getSelectOptions( $options = '' ) {
536 if ( $this->mForUpdate
) {
537 if ( is_array( $options ) ) {
538 $options[] = 'FOR UPDATE';
540 $options = 'FOR UPDATE';
547 * @return int Page ID
549 public function getID() {
550 if ( $this->mTitle
) {
551 return $this->mTitle
->getArticleID();
558 * @return bool Whether or not the page exists in the database
560 public function exists() {
561 return $this->getId() > 0;
565 * Check if this page is something we're going to be showing
566 * some sort of sensible content for. If we return false, page
567 * views (plain action=view) will return an HTTP 404 response,
568 * so spiders and robots can know they're following a bad link.
572 public function hasViewableContent() {
573 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
577 * @return int The view count for the page
579 public function getCount() {
580 if ( -1 == $this->mCounter
) {
581 $id = $this->getID();
585 $dbr = wfGetDB( DB_SLAVE
);
586 $this->mCounter
= $dbr->selectField( 'page',
588 array( 'page_id' => $id ),
590 $this->getSelectOptions()
594 return $this->mCounter
;
598 * Determine whether a page would be suitable for being counted as an
599 * article in the site_stats table based on the title & its content
601 * @param $text String: text to analyze
604 public function isCountable( $text ) {
605 global $wgUseCommaCount;
607 $token = $wgUseCommaCount ?
',' : '[[';
608 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
612 * Tests if the article text represents a redirect
614 * @param $text mixed string containing article contents, or boolean
617 public function isRedirect( $text = false ) {
618 if ( $text === false ) {
619 if ( $this->mDataLoaded
) {
620 return $this->mIsRedirect
;
622 // Apparently loadPageData was never called
623 $this->loadContent();
624 $titleObj = Title
::newFromRedirectRecurse( $this->fetchContent() );
626 $titleObj = Title
::newFromRedirect( $text );
628 return $titleObj !== null;
632 * Returns true if the currently-referenced revision is the current edit
633 * to this page (and it exists).
636 public function isCurrent() {
637 # If no oldid, this is the current version.
638 if ( $this->getOldID() == 0 ) {
641 return $this->exists() && isset( $this->mRevision
) && $this->mRevision
->isCurrent();
645 * Loads everything except the text
646 * This isn't necessary for all uses, so it's only done if needed.
648 protected function loadLastEdit() {
649 if ( -1 != $this->mUser
)
652 # New or non-existent articles have no user information
653 $id = $this->getID();
654 if ( 0 == $id ) return;
656 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
657 if ( !is_null( $this->mLastRevision
) ) {
658 $this->mUser
= $this->mLastRevision
->getUser();
659 $this->mUserText
= $this->mLastRevision
->getUserText();
660 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
661 $this->mComment
= $this->mLastRevision
->getComment();
662 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
663 $this->mRevIdFetched
= $this->mLastRevision
->getId();
668 * @return string GMT timestamp of last article revision
671 public function getTimestamp() {
672 // Check if the field has been filled by ParserCache::get()
673 if ( !$this->mTimestamp
) {
674 $this->loadLastEdit();
676 return wfTimestamp( TS_MW
, $this->mTimestamp
);
680 * @return int user ID for the user that made the last article revision
682 public function getUser() {
683 $this->loadLastEdit();
688 * @return string username of the user that made the last article revision
690 public function getUserText() {
691 $this->loadLastEdit();
692 return $this->mUserText
;
696 * @return string Comment stored for the last article revision
698 public function getComment() {
699 $this->loadLastEdit();
700 return $this->mComment
;
704 * Returns true if last revision was marked as "minor edit"
706 * @return boolean Minor edit indicator for the last article revision.
708 public function getMinorEdit() {
709 $this->loadLastEdit();
710 return $this->mMinorEdit
;
714 * Use this to fetch the rev ID used on page views
716 * @return int revision ID of last article revision
718 public function getRevIdFetched() {
719 $this->loadLastEdit();
720 return $this->mRevIdFetched
;
724 * @param $limit Integer: default 0.
725 * @param $offset Integer: default 0.
726 * @return UserArrayFromResult object with User objects of article contributors for requested range
728 public function getContributors( $limit = 0, $offset = 0 ) {
729 # XXX: this is expensive; cache this info somewhere.
731 $dbr = wfGetDB( DB_SLAVE
);
732 $revTable = $dbr->tableName( 'revision' );
733 $userTable = $dbr->tableName( 'user' );
735 $pageId = $this->getId();
737 $user = $this->getUser();
739 $excludeCond = "AND rev_user != $user";
741 $userText = $dbr->addQuotes( $this->getUserText() );
742 $excludeCond = "AND rev_user_text != $userText";
745 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
); // username hidden?
747 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
748 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
749 WHERE rev_page = $pageId
752 GROUP BY rev_user, rev_user_text
753 ORDER BY timestamp DESC";
756 $sql = $dbr->limitResult( $sql, $limit, $offset );
758 $sql .= ' ' . $this->getSelectOptions();
759 $res = $dbr->query( $sql, __METHOD__
);
761 return new UserArrayFromResult( $res );
765 * This is the default action of the index.php entry point: just view the
766 * page of the given title.
768 public function view() {
769 global $wgUser, $wgOut, $wgRequest, $wgContLang;
770 global $wgEnableParserCache, $wgStylePath, $wgParser;
771 global $wgUseTrackbacks, $wgUseFileCache;
773 wfProfileIn( __METHOD__
);
775 # Get variables from query string
776 $oldid = $this->getOldID();
777 $parserCache = ParserCache
::singleton();
779 $parserOptions = clone $this->getParserOptions();
780 # Render printable version, use printable version cache
781 if ( $wgOut->isPrintable() ) {
782 $parserOptions->setIsPrintable( true );
785 # Try client and file cache
786 if ( $oldid === 0 && $this->checkTouched() ) {
789 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
791 # Is is client cached?
792 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
793 wfDebug( __METHOD__
. ": done 304\n" );
794 wfProfileOut( __METHOD__
);
797 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
798 wfDebug( __METHOD__
. ": done file cache\n" );
799 # tell wgOut that output is taken care of
801 $this->viewUpdates();
802 wfProfileOut( __METHOD__
);
807 $sk = $wgUser->getSkin();
809 # getOldID may want us to redirect somewhere else
810 if ( $this->mRedirectUrl
) {
811 $wgOut->redirect( $this->mRedirectUrl
);
812 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
813 wfProfileOut( __METHOD__
);
817 $wgOut->setArticleFlag( true );
818 # Set page title (may be overridden by DISPLAYTITLE)
819 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
821 # If we got diff in the query, we want to see a diff page instead of the article.
822 if ( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
823 wfDebug( __METHOD__
. ": showing diff page\n" );
824 $this->showDiffPage();
825 wfProfileOut( __METHOD__
);
829 # Should the parser cache be used?
830 $useParserCache = $this->useParserCache( $oldid );
831 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
832 if ( $wgUser->getOption( 'stubthreshold' ) ) {
833 wfIncrStats( 'pcache_miss_stub' );
836 # For the main page, overwrite the <title> element with the con-
837 # tents of 'pagetitle-view-mainpage' instead of the default (if
839 if ( $this->mTitle
->equals( Title
::newMainPage() )
840 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
842 $wgOut->setHTMLTitle( $m );
845 $wasRedirected = $this->showRedirectedFromHeader();
846 $this->showNamespaceHeader();
848 # Iterate through the possible ways of constructing the output text.
849 # Keep going until $outputDone is set, or we run out of things to do.
852 while ( !$outputDone && ++
$pass ) {
855 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
859 # Try the parser cache
860 if ( $useParserCache ) {
861 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
862 if ( $this->mParserOutput
!== false ) {
863 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
864 $wgOut->addParserOutput( $this->mParserOutput
);
865 # Ensure that UI elements requiring revision ID have
866 # the correct version information.
867 $wgOut->setRevisionId( $this->mLatest
);
874 $text = $this->getContent();
875 if ( $text === false ||
$this->getID() == 0 ) {
876 wfDebug( __METHOD__
. ": showing missing article\n" );
877 $this->showMissingArticle();
878 wfProfileOut( __METHOD__
);
882 # Another whitelist check in case oldid is altering the title
883 if ( !$this->mTitle
->userCanRead() ) {
884 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
885 $wgOut->loginToUse();
888 wfProfileOut( __METHOD__
);
892 # Are we looking at an old revision
893 if ( $oldid && !is_null( $this->mRevision
) ) {
894 $this->setOldSubtitle( $oldid );
895 if ( !$this->showDeletedRevisionHeader() ) {
896 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
897 wfProfileOut( __METHOD__
);
900 # If this "old" version is the current, then try the parser cache...
901 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
902 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
903 if ( $this->mParserOutput
) {
904 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
905 $wgOut->addParserOutput( $this->mParserOutput
);
906 $wgOut->setRevisionId( $this->mLatest
);
907 $this->showViewFooter();
908 $this->viewUpdates();
909 wfProfileOut( __METHOD__
);
915 # Ensure that UI elements requiring revision ID have
916 # the correct version information.
917 $wgOut->setRevisionId( $this->getRevIdFetched() );
919 # Pages containing custom CSS or JavaScript get special treatment
920 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
921 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
922 $this->showCssOrJsPage();
924 } else if ( $rt = Title
::newFromRedirectArray( $text ) ) {
925 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
926 # Viewing a redirect page (e.g. with parameter redirect=no)
927 # Don't append the subtitle if this was an old revision
928 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
929 # Parse just to get categories, displaytitle, etc.
930 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
931 $wgOut->addParserOutputNoText( $this->mParserOutput
);
937 # Run the parse, protected by a pool counter
938 wfDebug( __METHOD__
. ": doing uncached parse\n" );
939 $key = $parserCache->getKey( $this, $parserOptions );
940 $poolCounter = PoolCounter
::factory( 'Article::view', $key );
941 $dirtyCallback = $useParserCache ?
array( $this, 'tryDirtyCache' ) : false;
942 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
944 if ( !$status->isOK() ) {
945 # Connection or timeout error
946 $this->showPoolError( $status );
947 wfProfileOut( __METHOD__
);
954 # Should be unreachable, but just in case...
960 # Now that we've filled $this->mParserOutput, we know whether
961 # there are any __NOINDEX__ tags on the page
962 $policy = $this->getRobotPolicy( 'view' );
963 $wgOut->setIndexPolicy( $policy['index'] );
964 $wgOut->setFollowPolicy( $policy['follow'] );
966 $this->showViewFooter();
967 $this->viewUpdates();
968 wfProfileOut( __METHOD__
);
972 * Show a diff page according to current request variables. For use within
973 * Article::view() only, other callers should use the DifferenceEngine class.
975 public function showDiffPage() {
976 global $wgOut, $wgRequest, $wgUser;
978 $diff = $wgRequest->getVal( 'diff' );
979 $rcid = $wgRequest->getVal( 'rcid' );
980 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
981 $purge = $wgRequest->getVal( 'action' ) == 'purge';
982 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
983 $oldid = $this->getOldID();
985 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
986 // DifferenceEngine directly fetched the revision:
987 $this->mRevIdFetched
= $de->mNewid
;
988 $de->showDiffPage( $diffOnly );
990 // Needed to get the page's current revision
991 $this->loadPageData();
992 if ( $diff == 0 ||
$diff == $this->mLatest
) {
993 # Run view updates for current revision only
994 $this->viewUpdates();
999 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1000 * Article::view() only.
1002 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1005 public function showCssOrJsPage() {
1007 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
1008 // Give hooks a chance to customise the output
1009 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1010 // Wrap the whole lot in a <pre> and don't parse
1012 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1013 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1014 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1015 $wgOut->addHTML( "\n</pre>\n" );
1020 * Get the robot policy to be used for the current action=view request.
1021 * @return String the policy that should be set
1022 * @deprecated use getRobotPolicy() instead, which returns an associative
1025 public function getRobotPolicyForView() {
1026 wfDeprecated( __FUNC__
);
1027 $policy = $this->getRobotPolicy( 'view' );
1028 return $policy['index'] . ',' . $policy['follow'];
1032 * Get the robot policy to be used for the current view
1033 * @param $action String the action= GET parameter
1034 * @return Array the policy that should be set
1035 * TODO: actions other than 'view'
1037 public function getRobotPolicy( $action ) {
1039 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1040 global $wgDefaultRobotPolicy, $wgRequest;
1042 $ns = $this->mTitle
->getNamespace();
1043 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1044 # Don't index user and user talk pages for blocked users (bug 11443)
1045 if ( !$this->mTitle
->isSubpage() ) {
1046 $block = new Block();
1047 if ( $block->load( $this->mTitle
->getText() ) ) {
1048 return array( 'index' => 'noindex',
1049 'follow' => 'nofollow' );
1054 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1055 # Non-articles (special pages etc), and old revisions
1056 return array( 'index' => 'noindex',
1057 'follow' => 'nofollow' );
1058 } elseif ( $wgOut->isPrintable() ) {
1059 # Discourage indexing of printable versions, but encourage following
1060 return array( 'index' => 'noindex',
1061 'follow' => 'follow' );
1062 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1063 # For ?curid=x urls, disallow indexing
1064 return array( 'index' => 'noindex',
1065 'follow' => 'follow' );
1068 # Otherwise, construct the policy based on the various config variables.
1069 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1071 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1072 # Honour customised robot policies for this namespace
1073 $policy = array_merge( $policy,
1074 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] ) );
1076 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1077 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1078 # a final sanity check that we have really got the parser output.
1079 $policy = array_merge( $policy,
1080 array( 'index' => $this->mParserOutput
->getIndexPolicy() ) );
1083 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1084 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1085 $policy = array_merge( $policy,
1086 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) );
1094 * Converts a String robot policy into an associative array, to allow
1095 * merging of several policies using array_merge().
1096 * @param $policy Mixed, returns empty array on null/false/'', transparent
1097 * to already-converted arrays, converts String.
1098 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1100 public static function formatRobotPolicy( $policy ) {
1101 if ( is_array( $policy ) ) {
1103 } elseif ( !$policy ) {
1107 $policy = explode( ',', $policy );
1108 $policy = array_map( 'trim', $policy );
1111 foreach ( $policy as $var ) {
1112 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1113 $arr['index'] = $var;
1114 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1115 $arr['follow'] = $var;
1122 * If this request is a redirect view, send "redirected from" subtitle to
1123 * $wgOut. Returns true if the header was needed, false if this is not a
1124 * redirect view. Handles both local and remote redirects.
1128 public function showRedirectedFromHeader() {
1129 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1131 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1132 $sk = $wgUser->getSkin();
1133 if ( isset( $this->mRedirectedFrom
) ) {
1134 // This is an internally redirected page view.
1135 // We'll need a backlink to the source page for navigation.
1136 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1138 $this->mRedirectedFrom
,
1141 array( 'redirect' => 'no' ),
1142 array( 'known', 'noclasses' )
1144 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1145 $wgOut->setSubtitle( $s );
1147 // Set the fragment if one was specified in the redirect
1148 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1149 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1150 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1153 // Add a <link rel="canonical"> tag
1154 $wgOut->addLink( array( 'rel' => 'canonical',
1155 'href' => $this->mTitle
->getLocalURL() )
1159 } elseif ( $rdfrom ) {
1160 // This is an externally redirected view, from some other wiki.
1161 // If it was reported from a trusted site, supply a backlink.
1162 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1163 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1164 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1165 $wgOut->setSubtitle( $s );
1173 * Show a header specific to the namespace currently being viewed, like
1174 * [[MediaWiki:Talkpagetext]]. For Article::view().
1176 public function showNamespaceHeader() {
1178 if ( $this->mTitle
->isTalkPage() ) {
1179 $msg = wfMsgNoTrans( 'talkpageheader' );
1180 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1181 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1187 * Show the footer section of an ordinary page view
1189 public function showViewFooter() {
1190 global $wgOut, $wgUseTrackbacks, $wgRequest;
1191 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1192 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1193 $wgOut->addWikiMsg( 'anontalkpagetext' );
1196 # If we have been passed an &rcid= parameter, we want to give the user a
1197 # chance to mark this new article as patrolled.
1198 $this->showPatrolFooter();
1201 if ( $wgUseTrackbacks ) {
1202 $this->addTrackbacks();
1207 * If patrol is possible, output a patrol UI box. This is called from the
1208 * footer section of ordinary page views. If patrol is not possible or not
1209 * desired, does nothing.
1211 public function showPatrolFooter() {
1212 global $wgOut, $wgRequest, $wgUser;
1213 $rcid = $wgRequest->getVal( 'rcid' );
1215 if ( !$rcid ||
!$this->mTitle
->exists() ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1219 $sk = $wgUser->getSkin();
1222 "<div class='patrollink'>" .
1224 'markaspatrolledlink',
1227 wfMsgHtml( 'markaspatrolledtext' ),
1230 'action' => 'markpatrolled',
1233 array( 'known', 'noclasses' )
1241 * Show the error text for a missing article. For articles in the MediaWiki
1242 * namespace, show the default message text. To be called from Article::view().
1244 public function showMissingArticle() {
1245 global $wgOut, $wgRequest, $wgUser;
1247 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1248 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1249 $parts = explode( '/', $this->mTitle
->getText() );
1250 $rootPart = $parts[0];
1251 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1252 $ip = User
::isIP( $rootPart );
1253 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1254 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1</div>",
1255 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1256 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1257 LogEventsList
::showLogExtract(
1260 $user->getUserPage()->getPrefixedText(),
1264 'showIfEmpty' => false,
1266 'blocked-notice-logextract',
1267 $user->getName() # Support GENDER in notice
1273 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1274 # Show delete and move logs
1275 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1277 'conds' => array( "log_action != 'revision'" ),
1278 'showIfEmpty' => false,
1279 'msgKey' => array( 'moveddeleted-notice' ) )
1282 # Show error message
1283 $oldid = $this->getOldID();
1285 $text = wfMsgNoTrans( 'missing-article',
1286 $this->mTitle
->getPrefixedText(),
1287 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1288 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1289 // Use the default message text
1290 $text = $this->getContent();
1292 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1293 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1294 $errors = array_merge( $createErrors, $editErrors );
1296 if ( !count( $errors ) )
1297 $text = wfMsgNoTrans( 'noarticletext' );
1299 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1301 $text = "<div class='noarticletext'>\n$text\n</div>";
1302 if ( !$this->hasViewableContent() ) {
1303 // If there's no backing content, send a 404 Not Found
1304 // for better machine handling of broken links.
1305 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1307 $wgOut->addWikiText( $text );
1311 * If the revision requested for view is deleted, check permissions.
1312 * Send either an error message or a warning header to $wgOut.
1314 * @return boolean true if the view is allowed, false if not.
1316 public function showDeletedRevisionHeader() {
1317 global $wgOut, $wgRequest;
1318 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1322 // If the user is not allowed to see it...
1323 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1324 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1325 'rev-deleted-text-permission' );
1327 // If the user needs to confirm that they want to see it...
1328 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1329 # Give explanation and add a link to view the revision...
1330 $oldid = intval( $this->getOldID() );
1331 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1332 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1333 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1334 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1335 array( $msg, $link ) );
1337 // We are allowed to see...
1339 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1340 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1341 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
1347 * Should the parser cache be used?
1351 public function useParserCache( $oldid ) {
1352 global $wgUser, $wgEnableParserCache;
1354 return $wgEnableParserCache
1355 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1358 && !$this->mTitle
->isCssOrJsPage()
1359 && !$this->mTitle
->isCssJsSubpage();
1363 * Execute the uncached parse for action=view
1365 public function doViewParse() {
1367 $oldid = $this->getOldID();
1368 $useParserCache = $this->useParserCache( $oldid );
1369 $parserOptions = clone $this->getParserOptions();
1370 # Render printable version, use printable version cache
1371 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1372 # Don't show section-edit links on old revisions... this way lies madness.
1373 $parserOptions->setEditSection( $this->isCurrent() );
1374 $useParserCache = $this->useParserCache( $oldid );
1375 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1379 * Try to fetch an expired entry from the parser cache. If it is present,
1380 * output it and return true. If it is not present, output nothing and
1381 * return false. This is used as a callback function for
1382 * PoolCounter::executeProtected().
1386 public function tryDirtyCache() {
1388 $parserCache = ParserCache
::singleton();
1389 $options = $this->getParserOptions();
1390 $options->setIsPrintable( $wgOut->isPrintable() );
1391 $output = $parserCache->getDirty( $this, $options );
1393 wfDebug( __METHOD__
. ": sending dirty output\n" );
1394 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1395 $wgOut->setSquidMaxage( 0 );
1396 $this->mParserOutput
= $output;
1397 $wgOut->addParserOutput( $output );
1398 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1401 wfDebugLog( 'dirty', "dirty missing\n" );
1402 wfDebug( __METHOD__
. ": no dirty cache\n" );
1408 * Show an error page for an error from the pool counter.
1409 * @param $status Status
1411 public function showPoolError( $status ) {
1413 $wgOut->clearHTML(); // for release() errors
1414 $wgOut->enableClientCache( false );
1415 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1416 $wgOut->addWikiText(
1417 '<div class="errorbox">' .
1418 $status->getWikiText( false, 'view-pool-error' ) .
1426 * @param $target Title object or Array of destination(s) to redirect
1427 * @param $appendSubtitle Boolean [optional]
1428 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1429 * @return string containing HMTL with redirect link
1431 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1432 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1434 if ( !is_array( $target ) ) {
1435 $target = array( $target );
1437 $imageDir = $wgContLang->getDir();
1438 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1439 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1440 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of entities?
1442 if ( $appendSubtitle ) {
1443 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1445 $sk = $wgUser->getSkin();
1446 // the loop prepends the arrow image before the link, so the first case needs to be outside
1447 $title = array_shift( $target );
1448 if ( $forceKnown ) {
1451 htmlspecialchars( $title->getFullText() ),
1454 array( 'known', 'noclasses' )
1457 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1459 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1460 foreach ( $target as $rt ) {
1461 if ( $forceKnown ) {
1462 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1465 htmlspecialchars( $rt->getFullText() ),
1468 array( 'known', 'noclasses' )
1471 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1472 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1475 return '<img src="' . $imageUrl . '" alt="#REDIRECT " />' .
1476 '<span class="redirectText">' . $link . '</span>';
1481 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1483 public function addTrackbacks() {
1484 global $wgOut, $wgUser;
1485 $dbr = wfGetDB( DB_SLAVE
);
1486 $tbs = $dbr->select( 'trackbacks',
1487 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1488 array( 'tb_page' => $this->getID() )
1490 if ( !$dbr->numRows( $tbs ) ) return;
1493 while ( $o = $dbr->fetchObject( $tbs ) ) {
1495 if ( $wgUser->isAllowed( 'trackback' ) ) {
1496 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1497 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1498 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1501 $tbtext .= wfMsg( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1508 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1509 $this->mTitle
->invalidateCache();
1513 * Removes trackback record for current article from trackbacks table
1515 public function deletetrackback() {
1516 global $wgUser, $wgRequest, $wgOut;
1517 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1518 $wgOut->addWikiMsg( 'sessionfailure' );
1522 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1523 if ( count( $permission_errors ) ) {
1524 $wgOut->showPermissionsErrorPage( $permission_errors );
1528 $db = wfGetDB( DB_MASTER
);
1529 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1531 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1532 $this->mTitle
->invalidateCache();
1536 * Handle action=render
1539 public function render() {
1541 $wgOut->setArticleBodyOnly( true );
1546 * Handle action=purge
1548 public function purge() {
1549 global $wgUser, $wgRequest, $wgOut;
1550 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1551 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1556 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1557 $button = wfMsgExt( 'confirm_purge_button', array( 'escapenoentities' ) );
1558 $form = "<form method=\"post\" action=\"$action\">\n" .
1559 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1561 $top = wfMsgExt( 'confirm-purge-top', array( 'parse' ) );
1562 $bottom = wfMsgExt( 'confirm-purge-bottom', array( 'parse' ) );
1563 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1564 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1565 $wgOut->addHTML( $top . $form . $bottom );
1570 * Perform the actions of a page purging
1572 public function doPurge() {
1574 // Invalidate the cache
1575 $this->mTitle
->invalidateCache();
1577 if ( $wgUseSquid ) {
1578 // Commit the transaction before the purge is sent
1579 $dbw = wfGetDB( DB_MASTER
);
1583 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1584 $update->doUpdate();
1586 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1587 global $wgMessageCache;
1588 if ( $this->getID() == 0 ) {
1591 $text = $this->getRawText();
1593 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1598 * Insert a new empty page record for this article.
1599 * This *must* be followed up by creating a revision
1600 * and running $this->updateToLatest( $rev_id );
1601 * or else the record will be left in a funky state.
1602 * Best if all done inside a transaction.
1604 * @param $dbw Database
1605 * @return int The newly created page_id key, or false if the title already existed
1608 public function insertOn( $dbw ) {
1609 wfProfileIn( __METHOD__
);
1611 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1612 $dbw->insert( 'page', array(
1613 'page_id' => $page_id,
1614 'page_namespace' => $this->mTitle
->getNamespace(),
1615 'page_title' => $this->mTitle
->getDBkey(),
1616 'page_counter' => 0,
1617 'page_restrictions' => '',
1618 'page_is_redirect' => 0, # Will set this shortly...
1620 'page_random' => wfRandom(),
1621 'page_touched' => $dbw->timestamp(),
1622 'page_latest' => 0, # Fill this in shortly...
1623 'page_len' => 0, # Fill this in shortly...
1624 ), __METHOD__
, 'IGNORE' );
1626 $affected = $dbw->affectedRows();
1628 $newid = $dbw->insertId();
1629 $this->mTitle
->resetArticleId( $newid );
1631 wfProfileOut( __METHOD__
);
1632 return $affected ?
$newid : false;
1636 * Update the page record to point to a newly saved revision.
1638 * @param $dbw Database object
1639 * @param $revision Revision: For ID number, and text used to set
1640 length and redirect status fields
1641 * @param $lastRevision Integer: if given, will not overwrite the page field
1642 * when different from the currently set value.
1643 * Giving 0 indicates the new page flag should be set
1645 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1646 * removing rows in redirect table.
1647 * @return bool true on success, false on failure
1650 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1651 wfProfileIn( __METHOD__
);
1653 $text = $revision->getText();
1654 $rt = Title
::newFromRedirect( $text );
1656 $conditions = array( 'page_id' => $this->getId() );
1657 if ( !is_null( $lastRevision ) ) {
1658 # An extra check against threads stepping on each other
1659 $conditions['page_latest'] = $lastRevision;
1662 $dbw->update( 'page',
1664 'page_latest' => $revision->getId(),
1665 'page_touched' => $dbw->timestamp(),
1666 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1667 'page_is_redirect' => $rt !== null ?
1 : 0,
1668 'page_len' => strlen( $text ),
1673 $result = $dbw->affectedRows() != 0;
1675 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1678 wfProfileOut( __METHOD__
);
1683 * Add row to the redirect table if this is a redirect, remove otherwise.
1685 * @param $dbw Database
1686 * @param $redirectTitle a title object pointing to the redirect target,
1687 * or NULL if this is not a redirect
1688 * @param $lastRevIsRedirect If given, will optimize adding and
1689 * removing rows in redirect table.
1690 * @return bool true on success, false on failure
1693 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1694 // Always update redirects (target link might have changed)
1695 // Update/Insert if we don't know if the last revision was a redirect or not
1696 // Delete if changing from redirect to non-redirect
1697 $isRedirect = !is_null( $redirectTitle );
1698 if ( $isRedirect ||
is_null( $lastRevIsRedirect ) ||
$lastRevIsRedirect !== $isRedirect ) {
1699 wfProfileIn( __METHOD__
);
1700 if ( $isRedirect ) {
1701 // This title is a redirect, Add/Update row in the redirect table
1702 $set = array( /* SET */
1703 'rd_namespace' => $redirectTitle->getNamespace(),
1704 'rd_title' => $redirectTitle->getDBkey(),
1705 'rd_from' => $this->getId(),
1707 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1709 // This is not a redirect, remove row from redirect table
1710 $where = array( 'rd_from' => $this->getId() );
1711 $dbw->delete( 'redirect', $where, __METHOD__
);
1713 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1714 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1716 wfProfileOut( __METHOD__
);
1717 return ( $dbw->affectedRows() != 0 );
1723 * If the given revision is newer than the currently set page_latest,
1724 * update the page record. Otherwise, do nothing.
1726 * @param $dbw Database object
1727 * @param $revision Revision object
1730 public function updateIfNewerOn( &$dbw, $revision ) {
1731 wfProfileIn( __METHOD__
);
1732 $row = $dbw->selectRow(
1733 array( 'revision', 'page' ),
1734 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1736 'page_id' => $this->getId(),
1737 'page_latest=rev_id' ),
1740 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1741 wfProfileOut( __METHOD__
);
1744 $prev = $row->rev_id
;
1745 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1747 # No or missing previous revision; mark the page as new
1749 $lastRevIsRedirect = null;
1751 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1752 wfProfileOut( __METHOD__
);
1757 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1758 * @return string Complete article text, or null if error
1760 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1761 wfProfileIn( __METHOD__
);
1762 if ( strval( $section ) == '' ) {
1763 // Whole-page edit; let the whole text through
1765 if ( is_null( $edittime ) ) {
1766 $rev = Revision
::newFromTitle( $this->mTitle
);
1768 $dbw = wfGetDB( DB_MASTER
);
1769 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1772 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1773 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1776 $oldtext = $rev->getText();
1778 if ( $section == 'new' ) {
1779 # Inserting a new section
1780 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1781 $text = strlen( trim( $oldtext ) ) > 0
1782 ?
"{$oldtext}\n\n{$subject}{$text}"
1783 : "{$subject}{$text}";
1785 # Replacing an existing section; roll out the big guns
1787 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1790 wfProfileOut( __METHOD__
);
1795 * This function is not deprecated until somebody fixes the core not to use
1796 * it. Nevertheless, use Article::doEdit() instead.
1798 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1799 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1800 ( $isminor ? EDIT_MINOR
: 0 ) |
1801 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1802 ( $bot ? EDIT_FORCE_BOT
: 0 );
1804 # If this is a comment, add the summary as headline
1805 if ( $comment && $summary != "" ) {
1806 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
1809 $this->doEdit( $text, $summary, $flags );
1811 $dbw = wfGetDB( DB_MASTER
);
1813 if ( !$this->mTitle
->userIsWatching() ) {
1819 if ( $this->mTitle
->userIsWatching() ) {
1825 $this->doRedirect( $this->isRedirect( $text ) );
1829 * @deprecated use Article::doEdit()
1831 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1832 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1833 ( $minor ? EDIT_MINOR
: 0 ) |
1834 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1836 $status = $this->doEdit( $text, $summary, $flags );
1837 if ( !$status->isOK() ) {
1841 $dbw = wfGetDB( DB_MASTER
);
1843 if ( !$this->mTitle
->userIsWatching() ) {
1849 if ( $this->mTitle
->userIsWatching() ) {
1856 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1857 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1859 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1866 * Change an existing article or create a new article. Updates RC and all necessary caches,
1867 * optionally via the deferred update array.
1869 * $wgUser must be set before calling this function.
1871 * @param $text String: new text
1872 * @param $summary String: edit summary
1873 * @param $flags Integer bitfield:
1875 * Article is known or assumed to be non-existent, create a new one
1877 * Article is known or assumed to be pre-existing, update it
1879 * Mark this edit minor, if the user is allowed to do so
1881 * Do not log the change in recentchanges
1883 * Mark the edit a "bot" edit regardless of user rights
1884 * EDIT_DEFER_UPDATES
1885 * Defer some of the updates until the end of index.php
1887 * Fill in blank summaries with generated text where possible
1889 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1890 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1891 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1892 * edit-already-exists error will be returned. These two conditions are also possible with
1893 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1895 * @param $baseRevId the revision ID this edit was based off, if any
1896 * @param $user Optional user object, $wgUser will be used if not passed
1898 * @return Status object. Possible errors:
1899 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1900 * edit-gone-missing: In update mode, but the article didn't exist
1901 * edit-conflict: In update mode, the article changed unexpectedly
1902 * edit-no-change: Warning that the text was the same as before
1903 * edit-already-exists: In creation mode, but the article already exists
1905 * Extensions may define additional errors.
1907 * $return->value will contain an associative array with members as follows:
1908 * new: Boolean indicating if the function attempted to create a new article
1909 * revision: The revision object for the inserted revision, or null
1911 * Compatibility note: this function previously returned a boolean value indicating success/failure
1913 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1914 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1916 # Low-level sanity check
1917 if ( $this->mTitle
->getText() == '' ) {
1918 throw new MWException( 'Something is trying to edit an article with an empty title' );
1921 wfProfileIn( __METHOD__
);
1923 $user = is_null( $user ) ?
$wgUser : $user;
1924 $status = Status
::newGood( array() );
1926 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1927 $this->loadPageData();
1929 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1930 $aid = $this->mTitle
->getArticleID();
1932 $flags |
= EDIT_UPDATE
;
1938 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1939 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1941 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1942 wfProfileOut( __METHOD__
);
1943 if ( $status->isOK() ) {
1944 $status->fatal( 'edit-hook-aborted' );
1949 # Silently ignore EDIT_MINOR if not allowed
1950 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1951 $bot = $flags & EDIT_FORCE_BOT
;
1953 $oldtext = $this->getRawText(); // current revision
1954 $oldsize = strlen( $oldtext );
1956 # Provide autosummaries if one is not provided and autosummaries are enabled.
1957 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1958 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1961 $editInfo = $this->prepareTextForEdit( $text );
1962 $text = $editInfo->pst
;
1963 $newsize = strlen( $text );
1965 $dbw = wfGetDB( DB_MASTER
);
1966 $now = wfTimestampNow();
1967 $this->mTimestamp
= $now;
1969 if ( $flags & EDIT_UPDATE
) {
1970 # Update article, but only if changed.
1971 $status->value
['new'] = false;
1972 # Make sure the revision is either completely inserted or not inserted at all
1973 if ( !$wgDBtransactions ) {
1974 $userAbort = ignore_user_abort( true );
1979 $changed = ( strcmp( $text, $oldtext ) != 0 );
1982 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1983 - (int)$this->isCountable( $oldtext );
1984 $this->mTotalAdjustment
= 0;
1986 if ( !$this->mLatest
) {
1987 # Article gone missing
1988 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1989 $status->fatal( 'edit-gone-missing' );
1990 wfProfileOut( __METHOD__
);
1994 $revision = new Revision( array(
1995 'page' => $this->getId(),
1996 'comment' => $summary,
1997 'minor_edit' => $isminor,
1999 'parent_id' => $this->mLatest
,
2000 'user' => $user->getId(),
2001 'user_text' => $user->getName(),
2005 $revisionId = $revision->insertOn( $dbw );
2009 # Note that we use $this->mLatest instead of fetching a value from the master DB
2010 # during the course of this function. This makes sure that EditPage can detect
2011 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2012 # before this function is called. A previous function used a separate query, this
2013 # creates a window where concurrent edits can cause an ignored edit conflict.
2014 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2017 /* Belated edit conflict! Run away!! */
2018 $status->fatal( 'edit-conflict' );
2019 # Delete the invalid revision if the DB is not transactional
2020 if ( !$wgDBtransactions ) {
2021 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2026 global $wgUseRCPatrol;
2027 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2028 # Update recentchanges
2029 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2030 # Mark as patrolled if the user can do so
2031 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan( 'autopatrol' );
2032 # Add RC row to the DB
2033 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2034 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2035 $revisionId, $patrolled
2037 # Log auto-patrolled edits
2039 PatrolLog
::record( $rc, true );
2042 $user->incEditCount();
2046 $status->warning( 'edit-no-change' );
2048 // Keep the same revision ID, but do some updates on it
2049 $revisionId = $this->getRevIdFetched();
2050 // Update page_touched, this is usually implicit in the page update
2051 // Other cache updates are done in onArticleEdit()
2052 $this->mTitle
->invalidateCache();
2055 if ( !$wgDBtransactions ) {
2056 ignore_user_abort( $userAbort );
2058 // Now that ignore_user_abort is restored, we can respond to fatal errors
2059 if ( !$status->isOK() ) {
2060 wfProfileOut( __METHOD__
);
2064 # Invalidate cache of this article and all pages using this article
2065 # as a template. Partly deferred.
2066 Article
::onArticleEdit( $this->mTitle
);
2067 # Update links tables, site stats, etc.
2068 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2070 # Create new article
2071 $status->value
['new'] = true;
2073 # Set statistics members
2074 # We work out if it's countable after PST to avoid counter drift
2075 # when articles are created with {{subst:}}
2076 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2077 $this->mTotalAdjustment
= 1;
2081 # Add the page record; stake our claim on this title!
2082 # This will return false if the article already exists
2083 $newid = $this->insertOn( $dbw );
2085 if ( $newid === false ) {
2087 $status->fatal( 'edit-already-exists' );
2088 wfProfileOut( __METHOD__
);
2092 # Save the revision text...
2093 $revision = new Revision( array(
2095 'comment' => $summary,
2096 'minor_edit' => $isminor,
2098 'user' => $user->getId(),
2099 'user_text' => $user->getName(),
2101 $revisionId = $revision->insertOn( $dbw );
2103 $this->mTitle
->resetArticleID( $newid );
2105 # Update the page record with revision data
2106 $this->updateRevisionOn( $dbw, $revision, 0 );
2108 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2109 # Update recentchanges
2110 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2111 global $wgUseRCPatrol, $wgUseNPPatrol;
2112 # Mark as patrolled if the user can do so
2113 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && $this->mTitle
->userCan( 'autopatrol' );
2114 # Add RC row to the DB
2115 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2116 '', strlen( $text ), $revisionId, $patrolled );
2117 # Log auto-patrolled edits
2119 PatrolLog
::record( $rc, true );
2122 $user->incEditCount();
2125 # Update links, etc.
2126 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2129 Article
::onArticleCreate( $this->mTitle
);
2131 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2132 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2135 # Do updates right now unless deferral was requested
2136 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2140 // Return the new revision (or null) to the caller
2141 $status->value
['revision'] = $revision;
2143 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2144 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2146 wfProfileOut( __METHOD__
);
2151 * @deprecated wrapper for doRedirect
2153 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2154 wfDeprecated( __METHOD__
);
2155 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2159 * Output a redirect back to the article.
2160 * This is typically used after an edit.
2162 * @param $noRedir Boolean: add redirect=no
2163 * @param $sectionAnchor String: section to redirect to, including "#"
2164 * @param $extraQuery String: extra query params
2166 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2169 $query = 'redirect=no';
2171 $query .= "&$query";
2173 $query = $extraQuery;
2175 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2179 * Mark this particular edit/page as patrolled
2181 public function markpatrolled() {
2182 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2183 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2185 # If we haven't been given an rc_id value, we can't do anything
2186 $rcid = (int) $wgRequest->getVal( 'rcid' );
2187 $rc = RecentChange
::newFromId( $rcid );
2188 if ( is_null( $rc ) ) {
2189 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2193 # It would be nice to see where the user had actually come from, but for now just guess
2194 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2195 $return = SpecialPage
::getTitleFor( $returnto );
2197 $dbw = wfGetDB( DB_MASTER
);
2198 $errors = $rc->doMarkPatrolled();
2200 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2201 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2205 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2206 // The hook itself has handled any output
2210 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2211 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2212 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2213 $wgOut->returnToMain( false, $return );
2217 if ( !empty( $errors ) ) {
2218 $wgOut->showPermissionsErrorPage( $errors );
2223 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2224 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2225 $wgOut->returnToMain( false, $return );
2229 * User-interface handler for the "watch" action
2231 public function watch() {
2232 global $wgUser, $wgOut;
2233 if ( $wgUser->isAnon() ) {
2234 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2237 if ( wfReadOnly() ) {
2238 $wgOut->readOnlyPage();
2241 if ( $this->doWatch() ) {
2242 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2243 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2244 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
2246 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2250 * Add this page to $wgUser's watchlist
2251 * @return bool true on successful watch operation
2253 public function doWatch() {
2255 if ( $wgUser->isAnon() ) {
2258 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2259 $wgUser->addWatch( $this->mTitle
);
2260 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2266 * User interface handler for the "unwatch" action.
2268 public function unwatch() {
2269 global $wgUser, $wgOut;
2270 if ( $wgUser->isAnon() ) {
2271 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2274 if ( wfReadOnly() ) {
2275 $wgOut->readOnlyPage();
2278 if ( $this->doUnwatch() ) {
2279 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2280 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2281 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
2283 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2287 * Stop watching a page
2288 * @return bool true on successful unwatch
2290 public function doUnwatch() {
2292 if ( $wgUser->isAnon() ) {
2295 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2296 $wgUser->removeWatch( $this->mTitle
);
2297 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2303 * action=protect handler
2305 public function protect() {
2306 $form = new ProtectionForm( $this );
2311 * action=unprotect handler (alias)
2313 public function unprotect() {
2318 * Update the article's restriction field, and leave a log entry.
2320 * @param $limit Array: set of restriction keys
2321 * @param $reason String
2322 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2323 * @param $expiry Array: per restriction type expiration
2324 * @return bool true on success
2326 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2327 global $wgUser, $wgContLang;
2329 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2331 $id = $this->mTitle
->getArticleID();
2333 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2337 if ( wfReadOnly() ) {
2338 wfDebug( "updateRestrictions failed: read-only\n" );
2342 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2343 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2351 // Take this opportunity to purge out expired restrictions
2352 Title
::purgeExpiredRestrictions();
2354 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2355 # we expect a single selection, but the schema allows otherwise.
2357 $updated = Article
::flattenRestrictions( $limit );
2359 foreach ( $restrictionTypes as $action ) {
2360 if ( isset( $expiry[$action] ) ) {
2361 # Get current restrictions on $action
2362 $aLimits = $this->mTitle
->getRestrictions( $action );
2363 $current[$action] = implode( '', $aLimits );
2364 # Are any actual restrictions being dealt with here?
2365 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2366 # If something changed, we need to log it. Checking $aRChanged
2367 # assures that "unprotecting" a page that is not protected does
2368 # not log just because the expiry was "changed".
2369 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2375 $current = Article
::flattenRestrictions( $current );
2377 $changed = ( $changed ||
$current != $updated );
2378 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2379 $protect = ( $updated != '' );
2381 # If nothing's changed, do nothing
2383 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2385 $dbw = wfGetDB( DB_MASTER
);
2387 # Prepare a null revision to be added to the history
2388 $modified = $current != '' && $protect;
2390 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2392 $comment_type = 'unprotectedarticle';
2394 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2396 # Only restrictions with the 'protect' right can cascade...
2397 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2398 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2399 # The schema allows multiple restrictions
2400 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) )
2402 $cascade_description = '';
2404 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2408 $comment .= ": $reason";
2410 $editComment = $comment;
2411 $encodedExpiry = array();
2412 $protect_description = '';
2413 foreach ( $limit as $action => $restrictions ) {
2414 if ( !isset( $expiry[$action] ) )
2415 $expiry[$action] = 'infinite';
2417 $encodedExpiry[$action] = Block
::encodeExpiry( $expiry[$action], $dbw );
2418 if ( $restrictions != '' ) {
2419 $protect_description .= "[$action=$restrictions] (";
2420 if ( $encodedExpiry[$action] != 'infinity' ) {
2421 $protect_description .= wfMsgForContent( 'protect-expiring',
2422 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2423 $wgContLang->date( $expiry[$action], false, false ) ,
2424 $wgContLang->time( $expiry[$action], false, false ) );
2426 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2428 $protect_description .= ') ';
2431 $protect_description = trim( $protect_description );
2433 if ( $protect_description && $protect )
2434 $editComment .= " ($protect_description)";
2436 $editComment .= "$cascade_description";
2437 # Update restrictions table
2438 foreach ( $limit as $action => $restrictions ) {
2439 if ( $restrictions != '' ) {
2440 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2441 array( 'pr_page' => $id,
2442 'pr_type' => $action,
2443 'pr_level' => $restrictions,
2444 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2445 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
2447 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2448 'pr_type' => $action ), __METHOD__
);
2452 # Insert a null revision
2453 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2454 $nullRevId = $nullRevision->insertOn( $dbw );
2456 $latest = $this->getLatest();
2457 # Update page record
2458 $dbw->update( 'page',
2460 'page_touched' => $dbw->timestamp(),
2461 'page_restrictions' => '',
2462 'page_latest' => $nullRevId
2463 ), array( /* WHERE */
2465 ), 'Article::protect'
2468 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2469 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2471 # Update the protection log
2472 $log = new LogPage( 'protect' );
2474 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2475 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2477 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2481 } # End "changed" check
2487 * Take an array of page restrictions and flatten it to a string
2488 * suitable for insertion into the page_restrictions field.
2489 * @param $limit Array
2492 protected static function flattenRestrictions( $limit ) {
2493 if ( !is_array( $limit ) ) {
2494 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2498 foreach ( $limit as $action => $restrictions ) {
2499 if ( $restrictions != '' ) {
2500 $bits[] = "$action=$restrictions";
2503 return implode( ':', $bits );
2507 * Auto-generates a deletion reason
2509 * @param &$hasHistory Boolean: whether the page has a history
2510 * @return mixed String containing deletion reason or empty string, or boolean false
2511 * if no revision occurred
2513 public function generateReason( &$hasHistory ) {
2515 $dbw = wfGetDB( DB_MASTER
);
2516 // Get the last revision
2517 $rev = Revision
::newFromTitle( $this->mTitle
);
2518 if ( is_null( $rev ) )
2521 // Get the article's contents
2522 $contents = $rev->getText();
2524 // If the page is blank, use the text from the previous revision,
2525 // which can only be blank if there's a move/import/protect dummy revision involved
2526 if ( $contents == '' ) {
2527 $prev = $rev->getPrevious();
2529 $contents = $prev->getText();
2534 // Find out if there was only one contributor
2535 // Only scan the last 20 revisions
2536 $res = $dbw->select( 'revision', 'rev_user_text',
2537 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2539 array( 'LIMIT' => 20 )
2541 if ( $res === false )
2542 // This page has no revisions, which is very weird
2545 $hasHistory = ( $res->numRows() > 1 );
2546 $row = $dbw->fetchObject( $res );
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 ) {
2551 $onlyAuthor = false;
2555 $dbw->freeResult( $res );
2557 // Generate the summary with a '$1' placeholder
2559 // The current revision is blank and the one before is also
2560 // blank. It's just not our lucky day
2561 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2564 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2566 $reason = wfMsgForContent( 'excontent', '$1' );
2569 if ( $reason == '-' ) {
2570 // Allow these UI messages to be blanked out cleanly
2574 // Replace newlines with spaces to prevent uglyness
2575 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2576 // Calculate the maximum amount of chars to get
2577 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2578 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2579 $contents = $wgContLang->truncate( $contents, $maxLength );
2580 // Remove possible unfinished links
2581 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2582 // Now replace the '$1' placeholder
2583 $reason = str_replace( '$1', $contents, $reason );
2589 * UI entry point for page deletion
2591 public function delete() {
2592 global $wgUser, $wgOut, $wgRequest;
2594 $confirm = $wgRequest->wasPosted() &&
2595 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2597 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2598 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2600 $reason = $this->DeleteReasonList
;
2602 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2603 // Entry from drop down menu + additional comment
2604 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2605 } elseif ( $reason == 'other' ) {
2606 $reason = $this->DeleteReason
;
2608 # Flag to hide all contents of the archived revisions
2609 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2611 # This code desperately needs to be totally rewritten
2613 # Read-only check...
2614 if ( wfReadOnly() ) {
2615 $wgOut->readOnlyPage();
2620 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2622 if ( count( $permission_errors ) > 0 ) {
2623 $wgOut->showPermissionsErrorPage( $permission_errors );
2627 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2629 # Better double-check that it hasn't been deleted yet!
2630 $dbw = wfGetDB( DB_MASTER
);
2631 $conds = $this->mTitle
->pageCond();
2632 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2633 if ( $latest === false ) {
2634 $wgOut->showFatalError(
2637 array( 'class' => 'error mw-error-cannotdelete' ),
2638 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2641 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2642 LogEventsList
::showLogExtract(
2645 $this->mTitle
->getPrefixedText()
2650 # Hack for big sites
2651 $bigHistory = $this->isBigDeletion();
2652 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2653 global $wgLang, $wgDeleteRevisionsLimit;
2654 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2655 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2660 $this->doDelete( $reason, $suppress );
2661 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2663 } elseif ( $this->mTitle
->userIsWatching() ) {
2669 // Generate deletion reason
2670 $hasHistory = false;
2671 if ( !$reason ) $reason = $this->generateReason( $hasHistory );
2673 // If the page has a history, insert a warning
2674 if ( $hasHistory && !$confirm ) {
2676 $skin = $wgUser->getSkin();
2677 $revisions = $this->estimateRevisionCount();
2678 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2679 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2680 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2683 if ( $bigHistory ) {
2684 global $wgDeleteRevisionsLimit;
2685 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2686 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2690 return $this->confirmDelete( $reason );
2694 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2696 public function isBigDeletion() {
2697 global $wgDeleteRevisionsLimit;
2698 if ( $wgDeleteRevisionsLimit ) {
2699 $revCount = $this->estimateRevisionCount();
2700 return $revCount > $wgDeleteRevisionsLimit;
2706 * @return int approximate revision count
2708 public function estimateRevisionCount() {
2709 $dbr = wfGetDB( DB_SLAVE
);
2710 // For an exact count...
2711 // return $dbr->selectField( 'revision', 'COUNT(*)',
2712 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2713 return $dbr->estimateRowCount( 'revision', '*',
2714 array( 'rev_page' => $this->getId() ), __METHOD__
);
2718 * Get the last N authors
2719 * @param $num Integer: number of revisions to get
2720 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2721 * @return array Array of authors, duplicates not removed
2723 public function getLastNAuthors( $num, $revLatest = 0 ) {
2724 wfProfileIn( __METHOD__
);
2725 // First try the slave
2726 // If that doesn't have the latest revision, try the master
2728 $db = wfGetDB( DB_SLAVE
);
2730 $res = $db->select( array( 'page', 'revision' ),
2731 array( 'rev_id', 'rev_user_text' ),
2733 'page_namespace' => $this->mTitle
->getNamespace(),
2734 'page_title' => $this->mTitle
->getDBkey(),
2735 'rev_page = page_id'
2736 ), __METHOD__
, $this->getSelectOptions( array(
2737 'ORDER BY' => 'rev_timestamp DESC',
2742 wfProfileOut( __METHOD__
);
2745 $row = $db->fetchObject( $res );
2746 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2747 $db = wfGetDB( DB_MASTER
);
2752 } while ( $continue );
2754 $authors = array( $row->rev_user_text
);
2755 while ( $row = $db->fetchObject( $res ) ) {
2756 $authors[] = $row->rev_user_text
;
2758 wfProfileOut( __METHOD__
);
2763 * Output deletion confirmation dialog
2764 * @param $reason String: prefilled reason
2766 public function confirmDelete( $reason ) {
2767 global $wgOut, $wgUser;
2769 wfDebug( "Article::confirmDelete\n" );
2771 $deleteBackLink = $wgUser->getSkin()->link(
2776 array( 'known', 'noclasses' )
2778 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2779 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2780 $wgOut->addWikiMsg( 'confirmdeletetext' );
2782 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2784 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
2785 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2787 <td class='mw-input'><strong>" .
2788 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2789 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2795 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2797 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2798 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2799 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2800 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2801 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2802 "<tr id=\"wpDeleteReasonListRow\">
2803 <td class='mw-label'>" .
2804 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2806 <td class='mw-input'>" .
2807 Xml
::listDropDown( 'wpDeleteReasonList',
2808 wfMsgForContent( 'deletereason-dropdown' ),
2809 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2812 <tr id=\"wpDeleteReasonRow\">
2813 <td class='mw-label'>" .
2814 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2816 <td class='mw-input'>" .
2817 Html
::input( 'wpReason', $reason, 'text', array(
2819 'maxlength' => '255',
2826 # Dissalow watching is user is not logged in
2827 if ( $wgUser->isLoggedIn() ) {
2831 <td class='mw-input'>" .
2832 Xml
::checkLabel( wfMsg( 'watchthis' ),
2833 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2841 <td class='mw-submit'>" .
2842 Xml
::submitButton( wfMsg( 'deletepage' ),
2843 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2846 Xml
::closeElement( 'table' ) .
2847 Xml
::closeElement( 'fieldset' ) .
2848 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2849 Xml
::closeElement( 'form' );
2851 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2852 $skin = $wgUser->getSkin();
2853 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2854 $link = $skin->link(
2856 wfMsgHtml( 'delete-edit-reasonlist' ),
2858 array( 'action' => 'edit' )
2860 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2863 $wgOut->addHTML( $form );
2864 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2865 LogEventsList
::showLogExtract(
2868 $this->mTitle
->getPrefixedText()
2873 * Perform a deletion and output success or failure messages
2875 public function doDelete( $reason, $suppress = false ) {
2876 global $wgOut, $wgUser;
2877 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2880 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
2881 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2882 $deleted = $this->mTitle
->getPrefixedText();
2884 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2885 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2887 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2889 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2890 $wgOut->returnToMain( false );
2891 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
2894 if ( $error == '' ) {
2895 $wgOut->showFatalError(
2898 array( 'class' => 'error mw-error-cannotdelete' ),
2899 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2902 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2903 LogEventsList
::showLogExtract(
2906 $this->mTitle
->getPrefixedText()
2909 $wgOut->showFatalError( $error );
2915 * Back-end article deletion
2916 * Deletes the article with database consistency, writes logs, purges caches
2918 * @param $reason string delete reason for deletion log
2919 * @param suppress bitfield
2920 * Revision::DELETED_TEXT
2921 * Revision::DELETED_COMMENT
2922 * Revision::DELETED_USER
2923 * Revision::DELETED_RESTRICTED
2924 * @param $id int article ID
2925 * @param $commit boolean defaults to true, triggers transaction end
2926 * @return boolean true if successful
2928 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
2929 global $wgUseSquid, $wgDeferredUpdateList;
2930 global $wgUseTrackbacks;
2932 wfDebug( __METHOD__
. "\n" );
2934 $dbw = wfGetDB( DB_MASTER
);
2935 $ns = $this->mTitle
->getNamespace();
2936 $t = $this->mTitle
->getDBkey();
2937 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2939 if ( $t == '' ||
$id == 0 ) {
2943 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
2944 array_push( $wgDeferredUpdateList, $u );
2946 // Bitfields to further suppress the content
2949 // This should be 15...
2950 $bitfield |
= Revision
::DELETED_TEXT
;
2951 $bitfield |
= Revision
::DELETED_COMMENT
;
2952 $bitfield |
= Revision
::DELETED_USER
;
2953 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2955 $bitfield = 'rev_deleted';
2959 // For now, shunt the revision data into the archive table.
2960 // Text is *not* removed from the text table; bulk storage
2961 // is left intact to avoid breaking block-compression or
2962 // immutable storage schemes.
2964 // For backwards compatibility, note that some older archive
2965 // table entries will have ar_text and ar_flags fields still.
2967 // In the future, we may keep revisions and mark them with
2968 // the rev_deleted field, which is reserved for this purpose.
2969 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2971 'ar_namespace' => 'page_namespace',
2972 'ar_title' => 'page_title',
2973 'ar_comment' => 'rev_comment',
2974 'ar_user' => 'rev_user',
2975 'ar_user_text' => 'rev_user_text',
2976 'ar_timestamp' => 'rev_timestamp',
2977 'ar_minor_edit' => 'rev_minor_edit',
2978 'ar_rev_id' => 'rev_id',
2979 'ar_text_id' => 'rev_text_id',
2980 'ar_text' => '\'\'', // Be explicit to appease
2981 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2982 'ar_len' => 'rev_len',
2983 'ar_page_id' => 'page_id',
2984 'ar_deleted' => $bitfield
2987 'page_id = rev_page'
2991 # Delete restrictions for it
2992 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2994 # Now that it's safely backed up, delete it
2995 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2996 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3002 # Fix category table counts
3004 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3005 foreach ( $res as $row ) {
3006 $cats [] = $row->cl_to
;
3008 $this->updateCategoryCounts( array(), $cats );
3010 # If using cascading deletes, we can skip some explicit deletes
3011 if ( !$dbw->cascadingDeletes() ) {
3012 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3014 if ( $wgUseTrackbacks )
3015 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3017 # Delete outgoing links
3018 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3019 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3020 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3021 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3022 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3023 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3024 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3027 # If using cleanup triggers, we can skip some manual deletes
3028 if ( !$dbw->cleanupTriggers() ) {
3029 # Clean up recentchanges entries...
3030 $dbw->delete( 'recentchanges',
3031 array( 'rc_type != ' . RC_LOG
,
3032 'rc_namespace' => $this->mTitle
->getNamespace(),
3033 'rc_title' => $this->mTitle
->getDBkey() ),
3035 $dbw->delete( 'recentchanges',
3036 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3041 Article
::onArticleDelete( $this->mTitle
);
3043 # Clear the cached article id so the interface doesn't act like we exist
3044 $this->mTitle
->resetArticleID( 0 );
3046 # Log the deletion, if the page was suppressed, log it at Oversight instead
3047 $logtype = $suppress ?
'suppress' : 'delete';
3048 $log = new LogPage( $logtype );
3050 # Make sure logging got through
3051 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3061 * Roll back the most recent consecutive set of edits to a page
3062 * from the same user; fails if there are no eligible edits to
3063 * roll back to, e.g. user is the sole contributor. This function
3064 * performs permissions checks on $wgUser, then calls commitRollback()
3065 * to do the dirty work
3067 * @param $fromP String: Name of the user whose edits to rollback.
3068 * @param $summary String: Custom summary. Set to default summary if empty.
3069 * @param $token String: Rollback token.
3070 * @param $bot Boolean: If true, mark all reverted edits as bot.
3072 * @param $resultDetails Array: contains result-specific array of additional values
3073 * 'alreadyrolled' : 'current' (rev)
3074 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3076 * @return array of errors, each error formatted as
3077 * array(messagekey, param1, param2, ...).
3078 * On success, the array is empty. This array can also be passed to
3079 * OutputPage::showPermissionsErrorPage().
3081 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3083 $resultDetails = null;
3086 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3087 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3088 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3090 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
3091 $errors[] = array( 'sessionfailure' );
3093 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3094 $errors[] = array( 'actionthrottledtext' );
3096 # If there were errors, bail out now
3097 if ( !empty( $errors ) )
3100 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3104 * Backend implementation of doRollback(), please refer there for parameter
3105 * and return value documentation
3107 * NOTE: This function does NOT check ANY permissions, it just commits the
3108 * rollback to the DB Therefore, you should only call this function direct-
3109 * ly if you want to use custom permissions checks. If you don't, use
3110 * doRollback() instead.
3112 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3113 global $wgUseRCPatrol, $wgUser, $wgLang;
3114 $dbw = wfGetDB( DB_MASTER
);
3116 if ( wfReadOnly() ) {
3117 return array( array( 'readonlytext' ) );
3120 # Get the last editor
3121 $current = Revision
::newFromTitle( $this->mTitle
);
3122 if ( is_null( $current ) ) {
3123 # Something wrong... no page?
3124 return array( array( 'notanarticle' ) );
3127 $from = str_replace( '_', ' ', $fromP );
3128 # User name given should match up with the top revision.
3129 # If the user was deleted then $from should be empty.
3130 if ( $from != $current->getUserText() ) {
3131 $resultDetails = array( 'current' => $current );
3132 return array( array( 'alreadyrolled',
3133 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3134 htmlspecialchars( $fromP ),
3135 htmlspecialchars( $current->getUserText() )
3139 # Get the last edit not by this guy...
3140 # Note: these may not be public values
3141 $user = intval( $current->getRawUser() );
3142 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3143 $s = $dbw->selectRow( 'revision',
3144 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3145 array( 'rev_page' => $current->getPage(),
3146 "rev_user != {$user} OR rev_user_text != {$user_text}"
3148 array( 'USE INDEX' => 'page_timestamp',
3149 'ORDER BY' => 'rev_timestamp DESC' )
3151 if ( $s === false ) {
3152 # No one else ever edited this page
3153 return array( array( 'cantrollback' ) );
3154 } else if ( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
3155 # Only admins can see this text
3156 return array( array( 'notvisiblerev' ) );
3160 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3161 # Mark all reverted edits as bot
3164 if ( $wgUseRCPatrol ) {
3165 # Mark all reverted edits as patrolled
3166 $set['rc_patrolled'] = 1;
3169 if ( count( $set ) ) {
3170 $dbw->update( 'recentchanges', $set,
3172 'rc_cur_id' => $current->getPage(),
3173 'rc_user_text' => $current->getUserText(),
3174 "rc_timestamp > '{$s->rev_timestamp}'",
3179 # Generate the edit summary if necessary
3180 $target = Revision
::newFromId( $s->rev_id
);
3181 if ( empty( $summary ) ) {
3182 if ( $from == '' ) { // no public user name
3183 $summary = wfMsgForContent( 'revertpage-nouser' );
3185 $summary = wfMsgForContent( 'revertpage' );
3189 # Allow the custom summary to use the same args as the default message
3191 $target->getUserText(), $from, $s->rev_id
,
3192 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3193 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3195 $summary = wfMsgReplaceArgs( $summary, $args );
3198 $flags = EDIT_UPDATE
;
3200 if ( $wgUser->isAllowed( 'minoredit' ) )
3201 $flags |
= EDIT_MINOR
;
3203 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) ||
$wgUser->isAllowed( 'bot' ) ) )
3204 $flags |
= EDIT_FORCE_BOT
;
3205 # Actually store the edit
3206 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3207 if ( !empty( $status->value
['revision'] ) ) {
3208 $revId = $status->value
['revision']->getId();
3213 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3215 $resultDetails = array(
3216 'summary' => $summary,
3217 'current' => $current,
3218 'target' => $target,
3225 * User interface for rollback operations
3227 public function rollback() {
3228 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3231 $result = $this->doRollback(
3232 $wgRequest->getVal( 'from' ),
3233 $wgRequest->getText( 'summary' ),
3234 $wgRequest->getVal( 'token' ),
3235 $wgRequest->getBool( 'bot' ),
3239 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3240 $wgOut->rateLimited();
3243 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3244 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3245 $errArray = $result[0];
3246 $errMsg = array_shift( $errArray );
3247 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3248 if ( isset( $details['current'] ) ) {
3249 $current = $details['current'];
3250 if ( $current->getComment() != '' ) {
3251 $wgOut->addWikiMsgArray( 'editcomment', array(
3252 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3257 # Display permissions errors before read-only message -- there's no
3258 # point in misleading the user into thinking the inability to rollback
3259 # is only temporary.
3260 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3261 # array_diff is completely broken for arrays of arrays, sigh. Re-
3262 # move any 'readonlytext' error manually.
3264 foreach ( $result as $error ) {
3265 if ( $error != array( 'readonlytext' ) ) {
3269 $wgOut->showPermissionsErrorPage( $out );
3272 if ( $result == array( array( 'readonlytext' ) ) ) {
3273 $wgOut->readOnlyPage();
3277 $current = $details['current'];
3278 $target = $details['target'];
3279 $newId = $details['newid'];
3280 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3281 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3282 if ( $current->getUserText() === '' ) {
3283 $old = wfMsg( 'rev-deleted-user' );
3285 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3286 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3288 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3289 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3290 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3291 $wgOut->returnToMain( false, $this->mTitle
);
3293 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3294 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3295 $de->showDiff( '', '' );
3301 * Do standard deferred updates after page view
3303 public function viewUpdates() {
3304 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3305 if ( wfReadOnly() ) {
3308 # Don't update page view counters on views from bot users (bug 14044)
3309 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3310 Article
::incViewCount( $this->getID() );
3311 $u = new SiteStatsUpdate( 1, 0, 0 );
3312 array_push( $wgDeferredUpdateList, $u );
3314 # Update newtalk / watchlist notification status
3315 $wgUser->clearNotification( $this->mTitle
);
3319 * Prepare text which is about to be saved.
3320 * Returns a stdclass with source, pst and output members
3322 public function prepareTextForEdit( $text, $revid = null ) {
3323 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3325 return $this->mPreparedEdit
;
3328 $edit = (object)array();
3329 $edit->revid
= $revid;
3330 $edit->newText
= $text;
3331 $edit->pst
= $this->preSaveTransform( $text );
3332 $options = $this->getParserOptions();
3333 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
3334 $edit->oldText
= $this->getContent();
3335 $this->mPreparedEdit
= $edit;
3340 * Do standard deferred updates after page edit.
3341 * Update links tables, site stats, search index and message cache.
3342 * Purges pages that include this page if the text was changed here.
3343 * Every 100th edit, prune the recent changes table.
3346 * @param $text New text of the article
3347 * @param $summary Edit summary
3348 * @param $minoredit Minor edit
3349 * @param $timestamp_of_pagechange Timestamp associated with the page change
3350 * @param $newid rev_id value of the new revision
3351 * @param $changed Whether or not the content actually changed
3353 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3354 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3356 wfProfileIn( __METHOD__
);
3359 # Be careful not to double-PST: $text is usually already PST-ed once
3360 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3361 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3362 $editInfo = $this->prepareTextForEdit( $text, $newid );
3364 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3365 $editInfo = $this->mPreparedEdit
;
3368 # Save it to the parser cache
3369 if ( $wgEnableParserCache ) {
3370 $popts = $this->getParserOptions();
3371 $parserCache = ParserCache
::singleton();
3372 $parserCache->save( $editInfo->output
, $this, $popts );
3375 # Update the links tables
3376 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3379 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3381 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3382 if ( 0 == mt_rand( 0, 99 ) ) {
3383 // Flush old entries from the `recentchanges` table; we do this on
3384 // random requests so as to avoid an increase in writes for no good reason
3386 $dbw = wfGetDB( DB_MASTER
);
3387 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3388 $recentchanges = $dbw->tableName( 'recentchanges' );
3389 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3390 $dbw->query( $sql );
3394 $id = $this->getID();
3395 $title = $this->mTitle
->getPrefixedDBkey();
3396 $shortTitle = $this->mTitle
->getDBkey();
3399 wfProfileOut( __METHOD__
);
3403 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3404 array_push( $wgDeferredUpdateList, $u );
3405 $u = new SearchUpdate( $id, $title, $text );
3406 array_push( $wgDeferredUpdateList, $u );
3408 # If this is another user's talk page, update newtalk
3409 # Don't do this if $changed = false otherwise some idiot can null-edit a
3410 # load of user talk pages and piss people off, nor if it's a minor edit
3411 # by a properly-flagged bot.
3412 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3413 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3414 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3415 $other = User
::newFromName( $shortTitle, false );
3417 wfDebug( __METHOD__
. ": invalid username\n" );
3418 } elseif ( User
::isIP( $shortTitle ) ) {
3419 // An anonymous user
3420 $other->setNewtalk( true );
3421 } elseif ( $other->isLoggedIn() ) {
3422 $other->setNewtalk( true );
3424 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3429 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3430 $wgMessageCache->replace( $shortTitle, $text );
3433 wfProfileOut( __METHOD__
);
3437 * Perform article updates on a special page creation.
3439 * @param $rev Revision object
3441 * @todo This is a shitty interface function. Kill it and replace the
3442 * other shitty functions like editUpdates and such so it's not needed
3445 public function createUpdates( $rev ) {
3446 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3447 $this->mTotalAdjustment
= 1;
3448 $this->editUpdates( $rev->getText(), $rev->getComment(),
3449 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3453 * Generate the navigation links when browsing through an article revisions
3454 * It shows the information as:
3455 * Revision as of \<date\>; view current revision
3456 * \<- Previous version | Next Version -\>
3458 * @param $oldid String: revision ID of this article revision
3460 public function setOldSubtitle( $oldid = 0 ) {
3461 global $wgLang, $wgOut, $wgUser, $wgRequest;
3463 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3467 $unhide = $wgRequest->getInt( 'unhide' ) == 1 &&
3468 $wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $oldid );
3469 # Cascade unhide param in links for easy deletion browsing
3470 $extraParams = array();
3471 if ( $wgRequest->getVal( 'unhide' ) ) {
3472 $extraParams['unhide'] = 1;
3474 $revision = Revision
::newFromId( $oldid );
3476 $current = ( $oldid == $this->mLatest
);
3477 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3478 $tddate = $wgLang->date( $this->mTimestamp
, true );
3479 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3480 $sk = $wgUser->getSkin();
3482 ?
wfMsgHtml( 'currentrevisionlink' )
3485 wfMsgHtml( 'currentrevisionlink' ),
3488 array( 'known', 'noclasses' )
3491 ?
wfMsgHtml( 'diff' )
3494 wfMsgHtml( 'diff' ),
3500 array( 'known', 'noclasses' )
3502 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3506 wfMsgHtml( 'previousrevision' ),
3509 'direction' => 'prev',
3512 array( 'known', 'noclasses' )
3514 : wfMsgHtml( 'previousrevision' );
3518 wfMsgHtml( 'diff' ),
3524 array( 'known', 'noclasses' )
3526 : wfMsgHtml( 'diff' );
3527 $nextlink = $current
3528 ?
wfMsgHtml( 'nextrevision' )
3531 wfMsgHtml( 'nextrevision' ),
3534 'direction' => 'next',
3537 array( 'known', 'noclasses' )
3539 $nextdiff = $current
3540 ?
wfMsgHtml( 'diff' )
3543 wfMsgHtml( 'diff' ),
3549 array( 'known', 'noclasses' )
3553 // User can delete revisions or view deleted revisions...
3554 $canHide = $wgUser->isAllowed( 'deleterevision' );
3555 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3556 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3557 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3560 'type' => 'revision',
3561 'target' => $this->mTitle
->getPrefixedDbkey(),
3564 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3569 # Show user links if allowed to see them. If hidden, then show them only if requested...
3570 $userlinks = $sk->revUserTools( $revision, !$unhide );
3572 $m = wfMsg( 'revision-info-current' );
3573 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3574 ?
'revision-info-current'
3577 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3580 array( 'parseinline', 'replaceafter' ),
3586 $revision->getUser()
3589 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3590 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3591 $wgOut->setSubtitle( $r );
3595 * This function is called right before saving the wikitext,
3596 * so we can do things like signatures and links-in-context.
3598 * @param $text String article contents
3599 * @return string article contents with altered wikitext markup (signatures
3600 * converted, {{subst:}}, templates, etc.)
3602 public function preSaveTransform( $text ) {
3603 global $wgParser, $wgUser;
3604 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3607 /* Caching functions */
3610 * checkLastModified returns true if it has taken care of all
3611 * output to the client that is necessary for this request.
3612 * (that is, it has sent a cached version of the page)
3614 * @return boolean true if cached version send, false otherwise
3616 protected function tryFileCache() {
3617 static $called = false;
3619 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3623 if ( $this->isFileCacheable() ) {
3624 $cache = new HTMLFileCache( $this->mTitle
);
3625 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3626 wfDebug( "Article::tryFileCache(): about to load file\n" );
3627 $cache->loadFromFileCache();
3630 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3631 ob_start( array( &$cache, 'saveToFileCache' ) );
3634 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3640 * Check if the page can be cached
3643 public function isFileCacheable() {
3645 if ( HTMLFileCache
::useFileCache() ) {
3646 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3647 // Extension may have reason to disable file caching on some pages.
3649 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3656 * Loads page_touched and returns a value indicating if it should be used
3657 * @return boolean true if not a redirect
3659 public function checkTouched() {
3660 if ( !$this->mDataLoaded
) {
3661 $this->loadPageData();
3663 return !$this->mIsRedirect
;
3667 * Get the page_touched field
3668 * @return string containing GMT timestamp
3670 public function getTouched() {
3671 # Ensure that page data has been loaded
3672 if ( !$this->mDataLoaded
) {
3673 $this->loadPageData();
3675 return $this->mTouched
;
3679 * Get the page_latest field
3680 * @return integer rev_id of current revision
3682 public function getLatest() {
3683 if ( !$this->mDataLoaded
) {
3684 $this->loadPageData();
3686 return (int)$this->mLatest
;
3690 * Edit an article without doing all that other stuff
3691 * The article must already exist; link tables etc
3692 * are not updated, caches are not flushed.
3694 * @param $text String: text submitted
3695 * @param $comment String: comment submitted
3696 * @param $minor Boolean: whereas it's a minor modification
3698 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3699 wfProfileIn( __METHOD__
);
3701 $dbw = wfGetDB( DB_MASTER
);
3702 $revision = new Revision( array(
3703 'page' => $this->getId(),
3705 'comment' => $comment,
3706 'minor_edit' => $minor ?
1 : 0,
3708 $revision->insertOn( $dbw );
3709 $this->updateRevisionOn( $dbw, $revision );
3711 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3713 wfProfileOut( __METHOD__
);
3717 * Used to increment the view counter
3719 * @param $id Integer: article id
3721 public static function incViewCount( $id ) {
3722 $id = intval( $id );
3723 global $wgHitcounterUpdateFreq;
3725 $dbw = wfGetDB( DB_MASTER
);
3726 $pageTable = $dbw->tableName( 'page' );
3727 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3728 $acchitsTable = $dbw->tableName( 'acchits' );
3730 if ( $wgHitcounterUpdateFreq <= 1 ) {
3731 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3735 # Not important enough to warrant an error page in case of failure
3736 $oldignore = $dbw->ignoreErrors( true );
3738 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3740 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 +
1 );
3741 if ( ( rand() %
$checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
3742 # Most of the time (or on SQL errors), skip row count check
3743 $dbw->ignoreErrors( $oldignore );
3747 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
3748 $row = $dbw->fetchObject( $res );
3749 $rown = intval( $row->n
);
3750 if ( $rown >= $wgHitcounterUpdateFreq ) {
3751 wfProfileIn( 'Article::incViewCount-collect' );
3752 $old_user_abort = ignore_user_abort( true );
3754 $dbType = $dbw->getType();
3755 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__
, false );
3756 $tabletype = $dbType == 'mysql' ?
"ENGINE=HEAP " : '';
3757 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
3758 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
3759 'GROUP BY hc_id', __METHOD__
);
3760 $dbw->delete( 'hitcounter', '*', __METHOD__
);
3761 $dbw->unlockTables( __METHOD__
);
3762 if ( $dbType == 'mysql' ) {
3763 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
3764 'WHERE page_id = hc_id', __METHOD__
);
3767 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
3768 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__
);
3770 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__
);
3772 ignore_user_abort( $old_user_abort );
3773 wfProfileOut( 'Article::incViewCount-collect' );
3775 $dbw->ignoreErrors( $oldignore );
3779 * The onArticle*() functions are supposed to be a kind of hooks
3780 * which should be called whenever any of the specified actions
3783 * This is a good place to put code to clear caches, for instance.
3785 * This is called on page move and undelete, as well as edit
3787 * @param $title a title object
3789 public static function onArticleCreate( $title ) {
3790 # Update existence markers on article/talk tabs...
3791 if ( $title->isTalkPage() ) {
3792 $other = $title->getSubjectPage();
3794 $other = $title->getTalkPage();
3796 $other->invalidateCache();
3797 $other->purgeSquid();
3799 $title->touchLinks();
3800 $title->purgeSquid();
3801 $title->deleteTitleProtection();
3805 * Clears caches when article is deleted
3807 public static function onArticleDelete( $title ) {
3808 global $wgMessageCache;
3809 # Update existence markers on article/talk tabs...
3810 if ( $title->isTalkPage() ) {
3811 $other = $title->getSubjectPage();
3813 $other = $title->getTalkPage();
3815 $other->invalidateCache();
3816 $other->purgeSquid();
3818 $title->touchLinks();
3819 $title->purgeSquid();
3822 HTMLFileCache
::clearFileCache( $title );
3825 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3826 $wgMessageCache->replace( $title->getDBkey(), false );
3829 if ( $title->getNamespace() == NS_FILE
) {
3830 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3831 $update->doUpdate();
3834 if ( $title->getNamespace() == NS_USER_TALK
) {
3835 $user = User
::newFromName( $title->getText(), false );
3836 $user->setNewtalk( false );
3839 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3843 * Purge caches on page update etc
3845 * @param $title Title object
3846 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3848 public static function onArticleEdit( $title ) {
3849 global $wgDeferredUpdateList;
3851 // Invalidate caches of articles which include this page
3852 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3854 // Invalidate the caches of all pages which redirect here
3855 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3857 # Purge squid for this page only
3858 $title->purgeSquid();
3860 # Clear file cache for this page only
3861 HTMLFileCache
::clearFileCache( $title );
3867 * Overriden by ImagePage class, only present here to avoid a fatal error
3868 * Called for ?action=revert
3870 public function revert() {
3872 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3876 * Info about this page
3877 * Called for ?action=info when $wgAllowPageInfo is on.
3879 public function info() {
3880 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3882 if ( !$wgAllowPageInfo ) {
3883 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3887 $page = $this->mTitle
->getSubjectPage();
3889 $wgOut->setPagetitle( $page->getPrefixedText() );
3890 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3891 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3893 if ( !$this->mTitle
->exists() ) {
3894 $wgOut->addHTML( '<div class="noarticletext">' );
3895 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3896 // This doesn't quite make sense; the user is asking for
3897 // information about the _page_, not the message... -- RC
3898 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3900 $msg = $wgUser->isLoggedIn()
3902 : 'noarticletextanon';
3903 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3905 $wgOut->addHTML( '</div>' );
3907 $dbr = wfGetDB( DB_SLAVE
);
3909 'wl_title' => $page->getDBkey(),
3910 'wl_namespace' => $page->getNamespace() );
3911 $numwatchers = $dbr->selectField(
3916 $this->getSelectOptions() );
3918 $pageInfo = $this->pageCountInfo( $page );
3919 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3921 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3922 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
3924 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
3926 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3928 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3930 $wgOut->addHTML( '</ul>' );
3935 * Return the total number of edits and number of unique editors
3936 * on a given page. If page does not exist, returns false.
3938 * @param $title Title object
3939 * @return mixed array or boolean false
3941 public function pageCountInfo( $title ) {
3942 $id = $title->getArticleId();
3946 $dbr = wfGetDB( DB_SLAVE
);
3947 $rev_clause = array( 'rev_page' => $id );
3948 $edits = $dbr->selectField(
3953 $this->getSelectOptions()
3955 $authors = $dbr->selectField(
3957 'COUNT(DISTINCT rev_user_text)',
3960 $this->getSelectOptions()
3962 return array( 'edits' => $edits, 'authors' => $authors );
3966 * Return a list of templates used by this article.
3967 * Uses the templatelinks table
3969 * @return Array of Title objects
3971 public function getUsedTemplates() {
3973 $id = $this->mTitle
->getArticleID();
3977 $dbr = wfGetDB( DB_SLAVE
);
3978 $res = $dbr->select( array( 'templatelinks' ),
3979 array( 'tl_namespace', 'tl_title' ),
3980 array( 'tl_from' => $id ),
3982 if ( $res !== false ) {
3983 foreach ( $res as $row ) {
3984 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3987 $dbr->freeResult( $res );
3992 * Returns a list of hidden categories this page is a member of.
3993 * Uses the page_props and categorylinks tables.
3995 * @return Array of Title objects
3997 public function getHiddenCategories() {
3999 $id = $this->mTitle
->getArticleID();
4003 $dbr = wfGetDB( DB_SLAVE
);
4004 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4006 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4007 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4009 if ( $res !== false ) {
4010 foreach ( $res as $row ) {
4011 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4014 $dbr->freeResult( $res );
4019 * Return an applicable autosummary if one exists for the given edit.
4020 * @param $oldtext String: the previous text of the page.
4021 * @param $newtext String: The submitted text of the page.
4022 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4023 * @return string An appropriate autosummary, or an empty string.
4025 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4026 # Decide what kind of autosummary is needed.
4028 # Redirect autosummaries
4029 $ot = Title
::newFromRedirect( $oldtext );
4030 $rt = Title
::newFromRedirect( $newtext );
4031 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4032 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4035 # New page autosummaries
4036 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4037 # If they're making a new article, give its text, truncated, in the summary.
4039 $truncatedtext = $wgContLang->truncate(
4040 str_replace( "\n", ' ', $newtext ),
4041 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4042 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4045 # Blanking autosummaries
4046 if ( $oldtext != '' && $newtext == '' ) {
4047 return wfMsgForContent( 'autosumm-blank' );
4048 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4049 # Removing more than 90% of the article
4051 $truncatedtext = $wgContLang->truncate(
4053 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4054 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4057 # If we reach this point, there's no applicable autosummary for our case, so our
4058 # autosummary is empty.
4063 * Add the primary page-view wikitext to the output buffer
4064 * Saves the text into the parser cache if possible.
4065 * Updates templatelinks if it is out of date.
4067 * @param $text String
4068 * @param $cache Boolean
4069 * @param $parserOptions mixed ParserOptions object, or boolean false
4071 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4074 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4075 $wgOut->addParserOutput( $this->mParserOutput
);
4079 * This does all the heavy lifting for outputWikitext, except it returns the parser
4080 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4081 * say, embedding thread pages within a discussion system (LiquidThreads)
4083 * @param $text string
4084 * @param $cache boolean
4085 * @param $parserOptions parsing options, defaults to false
4086 * @return string containing parsed output
4088 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4089 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4091 if ( !$parserOptions ) {
4092 $parserOptions = $this->getParserOptions();
4096 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4097 $parserOptions, true, true, $this->getRevIdFetched() );
4102 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4103 $this->mTitle
->getPrefixedDBkey() ) );
4106 if ( $wgEnableParserCache && $cache && $this && $this->mParserOutput
->getCacheTime() != -1 ) {
4107 $parserCache = ParserCache
::singleton();
4108 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4110 // Make sure file cache is not used on uncacheable content.
4111 // Output that has magic words in it can still use the parser cache
4112 // (if enabled), though it will generally expire sooner.
4113 if ( $this->mParserOutput
->getCacheTime() == -1 ||
$this->mParserOutput
->containsOldMagic() ) {
4114 $wgUseFileCache = false;
4116 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4117 return $this->mParserOutput
;
4121 * Get parser options suitable for rendering the primary article wikitext
4122 * @return mixed ParserOptions object or boolean false
4124 public function getParserOptions() {
4126 if ( !$this->mParserOptions
) {
4127 $this->mParserOptions
= new ParserOptions( $wgUser );
4128 $this->mParserOptions
->setTidy( true );
4129 $this->mParserOptions
->enableLimitReport();
4131 return $this->mParserOptions
;
4135 * Updates cascading protections
4137 * @param $parserOutput mixed ParserOptions object, or boolean false
4140 protected function doCascadeProtectionUpdates( $parserOutput ) {
4141 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4145 // templatelinks table may have become out of sync,
4146 // especially if using variable-based transclusions.
4147 // For paranoia, check if things have changed and if
4148 // so apply updates to the database. This will ensure
4149 // that cascaded protections apply as soon as the changes
4152 # Get templates from templatelinks
4153 $id = $this->mTitle
->getArticleID();
4155 $tlTemplates = array();
4157 $dbr = wfGetDB( DB_SLAVE
);
4158 $res = $dbr->select( array( 'templatelinks' ),
4159 array( 'tl_namespace', 'tl_title' ),
4160 array( 'tl_from' => $id ),
4164 foreach ( $res as $row ) {
4165 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4168 # Get templates from parser output.
4169 $poTemplates = array();
4170 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4171 foreach ( $templates as $dbk => $id ) {
4172 $poTemplates["$ns:$dbk"] = true;
4177 # Note that we simulate array_diff_key in PHP <5.0.x
4178 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4180 if ( count( $templates_diff ) > 0 ) {
4181 # Whee, link updates time.
4182 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4188 * Update all the appropriate counts in the category table, given that
4189 * we've added the categories $added and deleted the categories $deleted.
4191 * @param $added array The names of categories that were added
4192 * @param $deleted array The names of categories that were deleted
4194 public function updateCategoryCounts( $added, $deleted ) {
4195 $ns = $this->mTitle
->getNamespace();
4196 $dbw = wfGetDB( DB_MASTER
);
4198 # First make sure the rows exist. If one of the "deleted" ones didn't
4199 # exist, we might legitimately not create it, but it's simpler to just
4200 # create it and then give it a negative value, since the value is bogus
4203 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4204 $insertCats = array_merge( $added, $deleted );
4205 if ( !$insertCats ) {
4206 # Okay, nothing to do
4209 $insertRows = array();
4210 foreach ( $insertCats as $cat ) {
4211 $insertRows[] = array(
4212 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4216 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4218 $addFields = array( 'cat_pages = cat_pages + 1' );
4219 $removeFields = array( 'cat_pages = cat_pages - 1' );
4220 if ( $ns == NS_CATEGORY
) {
4221 $addFields[] = 'cat_subcats = cat_subcats + 1';
4222 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4223 } elseif ( $ns == NS_FILE
) {
4224 $addFields[] = 'cat_files = cat_files + 1';
4225 $removeFields[] = 'cat_files = cat_files - 1';
4232 array( 'cat_title' => $added ),
4240 array( 'cat_title' => $deleted ),
4247 * Lightweight method to get the parser output for a page, checking the parser cache
4248 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4249 * consider, so it's not appropriate to use there.
4251 * @param $oldid mixed integer Revision ID or null
4253 public function getParserOutput( $oldid = null ) {
4254 global $wgEnableParserCache, $wgUser, $wgOut;
4256 // Should the parser cache be used?
4257 $useParserCache = $wgEnableParserCache &&
4258 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4262 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4263 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4264 wfIncrStats( 'pcache_miss_stub' );
4267 $parserOutput = false;
4268 if ( $useParserCache ) {
4269 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4272 if ( $parserOutput === false ) {
4273 // Cache miss; parse and output it.
4274 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4276 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4278 return $parserOutput;