8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
14 * @internal documentation reviewed 15 Mar 2010
20 var $mComment = ''; // !<
22 var $mContentLoaded = false; // !<
23 var $mCounter = -1; // !< Not loaded
24 var $mCurID = -1; // !< Not loaded
25 var $mDataLoaded = false; // !<
26 var $mForUpdate = false; // !<
27 var $mGoodAdjustment = 0; // !<
28 var $mIsRedirect = false; // !<
29 var $mLatest = false; // !<
30 var $mMinorEdit; // !<
32 var $mPreparedEdit = false; // !< Title object if set
33 var $mRedirectedFrom = null; // !< Title object if set
34 var $mRedirectTarget = null; // !< Title object if set
35 var $mRedirectUrl = false; // !<
36 var $mRevIdFetched = 0; // !<
37 var $mRevision; // !< Revision object if set
38 var $mTimestamp = ''; // !<
39 var $mTitle; // !< Title object
40 var $mTotalAdjustment = 0; // !<
41 var $mTouched = '19700101000000'; // !<
42 var $mUser = -1; // !< Not loaded
43 var $mUserText = ''; // !< username from Revision if set
44 var $mParserOptions; // !< ParserOptions object
45 var $mParserOutput; // !< ParserCache object if set
49 * Constructor and clear the article
50 * @param $title Reference to a Title object.
51 * @param $oldId Integer revision ID, null to fetch from request, zero for current
53 public function __construct( Title
$title, $oldId = null ) {
54 $this->mTitle
=& $title;
55 $this->mOldId
= $oldId;
59 * Constructor from an article article
60 * @param $id The article ID to load
62 public static function newFromID( $id ) {
63 $t = Title
::newFromID( $id );
64 # FIXME: doesn't inherit right
65 return $t == null ?
null : new self( $t );
66 # return $t == null ? null : new static( $t ); // PHP 5.3
70 * Tell the page view functions that this view was redirected
71 * from another page on the wiki.
72 * @param $from Title object.
74 public function setRedirectedFrom( Title
$from ) {
75 $this->mRedirectedFrom
= $from;
79 * If this page is a redirect, get its target
81 * The target will be fetched from the redirect table if possible.
82 * If this page doesn't have an entry there, call insertRedirect()
83 * @return mixed Title object, or null if this page is not a redirect
85 public function getRedirectTarget() {
86 if ( !$this->mTitle ||
!$this->mTitle
->isRedirect() ) {
90 if ( !is_null( $this->mRedirectTarget
) ) {
91 return $this->mRedirectTarget
;
94 # Query the redirect table
95 $dbr = wfGetDB( DB_SLAVE
);
96 $row = $dbr->selectRow( 'redirect',
97 array( 'rd_namespace', 'rd_title' ),
98 array( 'rd_from' => $this->getID() ),
103 return $this->mRedirectTarget
= Title
::makeTitle( $row->rd_namespace
, $row->rd_title
);
106 # This page doesn't have an entry in the redirect table
107 return $this->mRedirectTarget
= $this->insertRedirect();
111 * Insert an entry for this page into the redirect table.
113 * Don't call this function directly unless you know what you're doing.
114 * @return Title object
116 public function insertRedirect() {
117 $retval = Title
::newFromRedirect( $this->getContent() );
123 $dbw = wfGetDB( DB_MASTER
);
124 $dbw->replace( 'redirect', array( 'rd_from' ),
126 'rd_from' => $this->getID(),
127 'rd_namespace' => $retval->getNamespace(),
128 'rd_title' => $retval->getDBkey()
137 * Get the Title object this page redirects to
139 * @return mixed false, Title of in-wiki target, or string with URL
141 public function followRedirect() {
142 $text = $this->getContent();
144 return $this->followRedirectText( $text );
148 * Get the Title object this text redirects to
150 * @param $text string article content containing redirect info
151 * @return mixed false, Title of in-wiki target, or string with URL
153 public function followRedirectText( $text ) {
154 $rt = Title
::newFromRedirectRecurse( $text ); // recurse through to only get the final target
155 # process if title object is valid and not special:userlogout
158 if ( $rt->getInterwiki() != '' ) {
159 if ( $rt->isLocal() ) {
160 // Offsite wikis need an HTTP redirect.
162 // This can be hard to reverse and may produce loops,
163 // so they may be disabled in the site configuration.
164 $source = $this->mTitle
->getFullURL( 'redirect=no' );
165 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
168 if ( $rt->getNamespace() == NS_SPECIAL
) {
169 // Gotta handle redirects to special pages differently:
170 // Fill the HTTP response "Location" header and ignore
171 // the rest of the page we're on.
173 // This can be hard to reverse, so they may be disabled.
174 if ( $rt->isSpecial( 'Userlogout' ) ) {
177 return $rt->getFullURL();
185 // No or invalid redirect
190 * get the title object of the article
191 * @return Title object of current title
193 public function getTitle() {
194 return $this->mTitle
;
201 public function clear() {
202 $this->mDataLoaded
= false;
203 $this->mContentLoaded
= false;
205 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
206 $this->mRedirectedFrom
= null; # Title object if set
207 $this->mRedirectTarget
= null; # Title object if set
209 $this->mTimestamp
= $this->mComment
= '';
210 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
211 $this->mTouched
= '19700101000000';
212 $this->mForUpdate
= false;
213 $this->mIsRedirect
= false;
214 $this->mRevIdFetched
= 0;
215 $this->mRedirectUrl
= false;
216 $this->mLatest
= false;
217 $this->mPreparedEdit
= false;
221 * Note that getContent/loadContent do not follow redirects anymore.
222 * If you need to fetch redirectable content easily, try
223 * the shortcut in Article::followRedirect()
225 * @return Return the text of this revision
227 public function getContent() {
228 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
230 wfProfileIn( __METHOD__
);
232 if ( $this->getID() === 0 ) {
233 # If this is a MediaWiki:x message, then load the messages
234 # and return the message value for x.
235 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
236 # If this is a system message, get the default text.
237 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
238 $wgMessageCache->loadAllMessages( $lang );
239 $text = wfMsgGetKey( $message, false, $lang, false );
241 if ( wfEmptyMsg( $message, $text ) )
244 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
246 wfProfileOut( __METHOD__
);
250 $this->loadContent();
251 wfProfileOut( __METHOD__
);
253 return $this->mContent
;
258 * Get the text of the current revision. No side-effects...
260 * @return Return the text of the current revision
262 public function getRawText() {
263 // Check process cache for current revision
264 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
265 return $this->mContent
;
268 $rev = Revision
::newFromTitle( $this->mTitle
);
269 $text = $rev ?
$rev->getRawText() : false;
275 * This function returns the text of a section, specified by a number ($section).
276 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
277 * the first section before any such heading (section 0).
279 * If a section contains subsections, these are also returned.
281 * @param $text String: text to look in
282 * @param $section Integer: section number
283 * @return string text of the requested section
286 public function getSection( $text, $section ) {
289 return $wgParser->getSection( $text, $section );
293 * Get the text that needs to be saved in order to undo all revisions
294 * between $undo and $undoafter. Revisions must belong to the same page,
295 * must exist and must not be deleted
296 * @param $undo Revision
297 * @param $undoafter Revision Must be an earlier revision than $undo
298 * @return mixed string on success, false on failure
300 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
301 $undo_text = $undo->getText();
302 $undoafter_text = $undoafter->getText();
303 $cur_text = $this->getContent();
305 if ( $cur_text == $undo_text ) {
306 # No use doing a merge if it's just a straight revert.
307 return $undoafter_text;
312 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
320 * @return int The oldid of the article that is to be shown, 0 for the
323 public function getOldID() {
324 if ( is_null( $this->mOldId
) ) {
325 $this->mOldId
= $this->getOldIDFromRequest();
328 return $this->mOldId
;
332 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
334 * @return int The old id for the request
336 public function getOldIDFromRequest() {
339 $this->mRedirectUrl
= false;
341 $oldid = $wgRequest->getVal( 'oldid' );
343 if ( isset( $oldid ) ) {
344 $oldid = intval( $oldid );
345 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
346 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
350 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
352 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
353 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
368 * Load the revision (including text) into this object
370 function loadContent() {
371 if ( $this->mContentLoaded
) {
375 wfProfileIn( __METHOD__
);
378 $oldid = $this->getOldID();
379 # Pre-fill content with error message so that if something
380 # fails we'll have something telling us what we intended.
381 $this->mOldId
= $oldid;
382 $this->fetchContent( $oldid );
384 wfProfileOut( __METHOD__
);
388 * Fetch a page record with the given conditions
389 * @param $dbr Database object
390 * @param $conditions Array
391 * @return mixed Database result resource, or false on failure
393 protected function pageData( $dbr, $conditions ) {
408 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
410 $row = $dbr->selectRow(
417 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
423 * Fetch a page record matching the Title object's namespace and title
424 * using a sanitized title string
426 * @param $dbr Database object
427 * @param $title Title object
428 * @return mixed Database result resource, or false on failure
430 public function pageDataFromTitle( $dbr, $title ) {
431 return $this->pageData( $dbr, array(
432 'page_namespace' => $title->getNamespace(),
433 'page_title' => $title->getDBkey() ) );
437 * Fetch a page record matching the requested ID
439 * @param $dbr Database
442 protected function pageDataFromId( $dbr, $id ) {
443 return $this->pageData( $dbr, array( 'page_id' => $id ) );
447 * Set the general counter, title etc data loaded from
450 * @param $data Database row object or "fromdb"
452 public function loadPageData( $data = 'fromdb' ) {
453 if ( $data === 'fromdb' ) {
454 $dbr = wfGetDB( DB_MASTER
);
455 $data = $this->pageDataFromId( $dbr, $this->getId() );
458 $lc = LinkCache
::singleton();
461 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
463 $this->mTitle
->mArticleID
= intval( $data->page_id
);
465 # Old-fashioned restrictions
466 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
468 $this->mCounter
= intval( $data->page_counter
);
469 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
470 $this->mIsRedirect
= intval( $data->page_is_redirect
);
471 $this->mLatest
= intval( $data->page_latest
);
473 if ( is_object( $this->mTitle
) ) {
474 $lc->addBadLinkObj( $this->mTitle
);
476 $this->mTitle
->mArticleID
= 0;
479 $this->mDataLoaded
= true;
483 * Get text of an article from database
484 * Does *NOT* follow redirects.
486 * @param $oldid Int: 0 for whatever the latest revision is
487 * @return mixed string containing article contents, or false if null
489 function fetchContent( $oldid = 0 ) {
490 if ( $this->mContentLoaded
) {
491 return $this->mContent
;
494 $dbr = wfGetDB( DB_MASTER
);
496 # Pre-fill content with error message so that if something
497 # fails we'll have something telling us what we intended.
498 $t = $this->mTitle
->getPrefixedText();
499 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
500 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
503 $revision = Revision
::newFromId( $oldid );
504 if ( is_null( $revision ) ) {
505 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
509 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
512 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
516 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
517 $this->loadPageData( $data );
519 if ( !$this->mDataLoaded
) {
520 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
523 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
527 $this->loadPageData( $data );
529 $revision = Revision
::newFromId( $this->mLatest
);
530 if ( is_null( $revision ) ) {
531 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
536 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
537 // We should instead work with the Revision object when we need it...
538 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
540 $this->mUser
= $revision->getUser();
541 $this->mUserText
= $revision->getUserText();
542 $this->mComment
= $revision->getComment();
543 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
545 $this->mRevIdFetched
= $revision->getId();
546 $this->mContentLoaded
= true;
547 $this->mRevision
=& $revision;
549 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
551 return $this->mContent
;
555 * Read/write accessor to select FOR UPDATE
557 * @param $x Mixed: FIXME
558 * @return mixed value of $x, or value stored in Article::mForUpdate
560 public function forUpdate( $x = null ) {
561 return wfSetVar( $this->mForUpdate
, $x );
565 * Get the database which should be used for reads
568 * @deprecated - just call wfGetDB( DB_MASTER ) instead
571 wfDeprecated( __METHOD__
);
572 return wfGetDB( DB_MASTER
);
576 * Get options for all SELECT statements
578 * @param $options Array: an optional options array which'll be appended to
580 * @return Array: options
582 protected function getSelectOptions( $options = '' ) {
583 if ( $this->mForUpdate
) {
584 if ( is_array( $options ) ) {
585 $options[] = 'FOR UPDATE';
587 $options = 'FOR UPDATE';
595 * @return int Page ID
597 public function getID() {
598 if ( $this->mTitle
) {
599 return $this->mTitle
->getArticleID();
606 * @return bool Whether or not the page exists in the database
608 public function exists() {
609 return $this->getId() > 0;
613 * Check if this page is something we're going to be showing
614 * some sort of sensible content for. If we return false, page
615 * views (plain action=view) will return an HTTP 404 response,
616 * so spiders and robots can know they're following a bad link.
620 public function hasViewableContent() {
621 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
625 * @return int The view count for the page
627 public function getCount() {
628 if ( -1 == $this->mCounter
) {
629 $id = $this->getID();
634 $dbr = wfGetDB( DB_SLAVE
);
635 $this->mCounter
= $dbr->selectField( 'page',
637 array( 'page_id' => $id ),
639 $this->getSelectOptions()
644 return $this->mCounter
;
648 * Determine whether a page would be suitable for being counted as an
649 * article in the site_stats table based on the title & its content
651 * @param $text String: text to analyze
654 public function isCountable( $text ) {
655 global $wgUseCommaCount;
657 $token = $wgUseCommaCount ?
',' : '[[';
659 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
663 * Tests if the article text represents a redirect
665 * @param $text mixed string containing article contents, or boolean
668 public function isRedirect( $text = false ) {
669 if ( $text === false ) {
670 if ( $this->mDataLoaded
) {
671 return $this->mIsRedirect
;
674 // Apparently loadPageData was never called
675 $this->loadContent();
676 $titleObj = Title
::newFromRedirectRecurse( $this->fetchContent() );
678 $titleObj = Title
::newFromRedirect( $text );
681 return $titleObj !== null;
685 * Returns true if the currently-referenced revision is the current edit
686 * to this page (and it exists).
689 public function isCurrent() {
690 # If no oldid, this is the current version.
691 if ( $this->getOldID() == 0 ) {
695 return $this->exists() && isset( $this->mRevision
) && $this->mRevision
->isCurrent();
699 * Loads everything except the text
700 * This isn't necessary for all uses, so it's only done if needed.
702 protected function loadLastEdit() {
703 if ( -1 != $this->mUser
) {
707 # New or non-existent articles have no user information
708 $id = $this->getID();
713 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
714 if ( !is_null( $this->mLastRevision
) ) {
715 $this->mUser
= $this->mLastRevision
->getUser();
716 $this->mUserText
= $this->mLastRevision
->getUserText();
717 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
718 $this->mComment
= $this->mLastRevision
->getComment();
719 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
720 $this->mRevIdFetched
= $this->mLastRevision
->getId();
725 * @return string GMT timestamp of last article revision
728 public function getTimestamp() {
729 // Check if the field has been filled by ParserCache::get()
730 if ( !$this->mTimestamp
) {
731 $this->loadLastEdit();
734 return wfTimestamp( TS_MW
, $this->mTimestamp
);
738 * @return int user ID for the user that made the last article revision
740 public function getUser() {
741 $this->loadLastEdit();
747 * @return string username of the user that made the last article revision
749 public function getUserText() {
750 $this->loadLastEdit();
752 return $this->mUserText
;
756 * @return string Comment stored for the last article revision
758 public function getComment() {
759 $this->loadLastEdit();
761 return $this->mComment
;
765 * Returns true if last revision was marked as "minor edit"
767 * @return boolean Minor edit indicator for the last article revision.
769 public function getMinorEdit() {
770 $this->loadLastEdit();
772 return $this->mMinorEdit
;
776 * Use this to fetch the rev ID used on page views
778 * @return int revision ID of last article revision
780 public function getRevIdFetched() {
781 $this->loadLastEdit();
783 return $this->mRevIdFetched
;
787 * @param $limit Integer: default 0.
788 * @param $offset Integer: default 0.
789 * @return UserArrayFromResult object with User objects of article contributors for requested range
791 public function getContributors( $limit = 0, $offset = 0 ) {
792 # FIXME: this is expensive; cache this info somewhere.
794 $dbr = wfGetDB( DB_SLAVE
);
795 $revTable = $dbr->tableName( 'revision' );
796 $userTable = $dbr->tableName( 'user' );
798 $pageId = $this->getId();
800 $user = $this->getUser();
803 $excludeCond = "AND rev_user != $user";
805 $userText = $dbr->addQuotes( $this->getUserText() );
806 $excludeCond = "AND rev_user_text != $userText";
809 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
); // username hidden?
811 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
812 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
813 WHERE rev_page = $pageId
816 GROUP BY rev_user, rev_user_text
817 ORDER BY timestamp DESC";
820 $sql = $dbr->limitResult( $sql, $limit, $offset );
823 $sql .= ' ' . $this->getSelectOptions();
824 $res = $dbr->query( $sql, __METHOD__
);
826 return new UserArrayFromResult( $res );
830 * This is the default action of the index.php entry point: just view the
831 * page of the given title.
833 public function view() {
834 global $wgUser, $wgOut, $wgRequest, $wgContLang;
835 global $wgEnableParserCache, $wgStylePath, $wgParser;
836 global $wgUseTrackbacks, $wgUseFileCache;
838 wfProfileIn( __METHOD__
);
840 # Get variables from query string
841 $oldid = $this->getOldID();
842 $parserCache = ParserCache
::singleton();
844 $parserOptions = clone $this->getParserOptions();
845 # Render printable version, use printable version cache
846 if ( $wgOut->isPrintable() ) {
847 $parserOptions->setIsPrintable( true );
850 # Try client and file cache
851 if ( $oldid === 0 && $this->checkTouched() ) {
855 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
858 # Is is client cached?
859 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
860 wfDebug( __METHOD__
. ": done 304\n" );
861 wfProfileOut( __METHOD__
);
865 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
866 wfDebug( __METHOD__
. ": done file cache\n" );
867 # tell wgOut that output is taken care of
869 $this->viewUpdates();
870 wfProfileOut( __METHOD__
);
876 # getOldID may want us to redirect somewhere else
877 if ( $this->mRedirectUrl
) {
878 $wgOut->redirect( $this->mRedirectUrl
);
879 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
880 wfProfileOut( __METHOD__
);
885 $wgOut->setArticleFlag( true );
886 # Set page title (may be overridden by DISPLAYTITLE)
887 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
889 # If we got diff in the query, we want to see a diff page instead of the article.
890 if ( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
891 wfDebug( __METHOD__
. ": showing diff page\n" );
892 $this->showDiffPage();
893 wfProfileOut( __METHOD__
);
898 # Should the parser cache be used?
899 $useParserCache = $this->useParserCache( $oldid );
900 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
901 if ( $wgUser->getOption( 'stubthreshold' ) ) {
902 wfIncrStats( 'pcache_miss_stub' );
905 $wasRedirected = $this->showRedirectedFromHeader();
906 $this->showNamespaceHeader();
908 # Iterate through the possible ways of constructing the output text.
909 # Keep going until $outputDone is set, or we run out of things to do.
912 $this->mParserOutput
= false;
914 while ( !$outputDone && ++
$pass ) {
917 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
920 # Try the parser cache
921 if ( $useParserCache ) {
922 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
924 if ( $this->mParserOutput
!== false ) {
925 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
926 $wgOut->addParserOutput( $this->mParserOutput
);
927 # Ensure that UI elements requiring revision ID have
928 # the correct version information.
929 $wgOut->setRevisionId( $this->mLatest
);
935 $text = $this->getContent();
936 if ( $text === false ||
$this->getID() == 0 ) {
937 wfDebug( __METHOD__
. ": showing missing article\n" );
938 $this->showMissingArticle();
939 wfProfileOut( __METHOD__
);
943 # Another whitelist check in case oldid is altering the title
944 if ( !$this->mTitle
->userCanRead() ) {
945 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
946 $wgOut->loginToUse();
949 wfProfileOut( __METHOD__
);
953 # Are we looking at an old revision
954 if ( $oldid && !is_null( $this->mRevision
) ) {
955 $this->setOldSubtitle( $oldid );
957 if ( !$this->showDeletedRevisionHeader() ) {
958 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
959 wfProfileOut( __METHOD__
);
963 # If this "old" version is the current, then try the parser cache...
964 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
965 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
966 if ( $this->mParserOutput
) {
967 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
968 $wgOut->addParserOutput( $this->mParserOutput
);
969 $wgOut->setRevisionId( $this->mLatest
);
970 $this->showViewFooter();
971 $this->viewUpdates();
972 wfProfileOut( __METHOD__
);
978 # Ensure that UI elements requiring revision ID have
979 # the correct version information.
980 $wgOut->setRevisionId( $this->getRevIdFetched() );
982 # Pages containing custom CSS or JavaScript get special treatment
983 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
984 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
985 $this->showCssOrJsPage();
987 } else if ( $rt = Title
::newFromRedirectArray( $text ) ) {
988 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
989 # Viewing a redirect page (e.g. with parameter redirect=no)
990 # Don't append the subtitle if this was an old revision
991 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
992 # Parse just to get categories, displaytitle, etc.
993 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
994 $wgOut->addParserOutputNoText( $this->mParserOutput
);
999 # Run the parse, protected by a pool counter
1000 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1001 $key = $parserCache->getKey( $this, $parserOptions );
1002 $poolCounter = PoolCounter
::factory( 'Article::view', $key );
1003 $dirtyCallback = $useParserCache ?
array( $this, 'tryDirtyCache' ) : false;
1004 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
1006 if ( !$status->isOK() ) {
1007 # Connection or timeout error
1008 $this->showPoolError( $status );
1009 wfProfileOut( __METHOD__
);
1015 # Should be unreachable, but just in case...
1021 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1022 if ( $this->mParserOutput
) {
1023 $titleText = $this->mParserOutput
->getTitleText();
1025 if ( strval( $titleText ) !== '' ) {
1026 $wgOut->setPageTitle( $titleText );
1030 # For the main page, overwrite the <title> element with the con-
1031 # tents of 'pagetitle-view-mainpage' instead of the default (if
1032 # that's not empty).
1033 if ( $this->mTitle
->equals( Title
::newMainPage() )
1034 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
1036 $wgOut->setHTMLTitle( $m );
1039 # Now that we've filled $this->mParserOutput, we know whether
1040 # there are any __NOINDEX__ tags on the page
1041 $policy = $this->getRobotPolicy( 'view' );
1042 $wgOut->setIndexPolicy( $policy['index'] );
1043 $wgOut->setFollowPolicy( $policy['follow'] );
1045 $this->showViewFooter();
1046 $this->viewUpdates();
1047 wfProfileOut( __METHOD__
);
1051 * Show a diff page according to current request variables. For use within
1052 * Article::view() only, other callers should use the DifferenceEngine class.
1054 public function showDiffPage() {
1055 global $wgOut, $wgRequest, $wgUser;
1057 $diff = $wgRequest->getVal( 'diff' );
1058 $rcid = $wgRequest->getVal( 'rcid' );
1059 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1060 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1061 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1062 $oldid = $this->getOldID();
1064 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1065 // DifferenceEngine directly fetched the revision:
1066 $this->mRevIdFetched
= $de->mNewid
;
1067 $de->showDiffPage( $diffOnly );
1069 // Needed to get the page's current revision
1070 $this->loadPageData();
1071 if ( $diff == 0 ||
$diff == $this->mLatest
) {
1072 # Run view updates for current revision only
1073 $this->viewUpdates();
1078 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1079 * Article::view() only.
1081 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1084 public function showCssOrJsPage() {
1087 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1089 // Give hooks a chance to customise the output
1090 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1091 // Wrap the whole lot in a <pre> and don't parse
1093 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1094 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1095 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1096 $wgOut->addHTML( "\n</pre>\n" );
1101 * Get the robot policy to be used for the current action=view request.
1102 * @return String the policy that should be set
1103 * @deprecated use getRobotPolicy() instead, which returns an associative
1106 public function getRobotPolicyForView() {
1107 wfDeprecated( __METHOD__
);
1108 $policy = $this->getRobotPolicy( 'view' );
1110 return $policy['index'] . ',' . $policy['follow'];
1114 * Get the robot policy to be used for the current view
1115 * @param $action String the action= GET parameter
1116 * @return Array the policy that should be set
1117 * TODO: actions other than 'view'
1119 public function getRobotPolicy( $action ) {
1120 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1121 global $wgDefaultRobotPolicy, $wgRequest;
1123 $ns = $this->mTitle
->getNamespace();
1125 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1126 # Don't index user and user talk pages for blocked users (bug 11443)
1127 if ( !$this->mTitle
->isSubpage() ) {
1128 $block = new Block();
1129 if ( $block->load( $this->mTitle
->getText() ) ) {
1131 'index' => 'noindex',
1132 'follow' => 'nofollow'
1138 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1139 # Non-articles (special pages etc), and old revisions
1141 'index' => 'noindex',
1142 'follow' => 'nofollow'
1144 } elseif ( $wgOut->isPrintable() ) {
1145 # Discourage indexing of printable versions, but encourage following
1147 'index' => 'noindex',
1148 'follow' => 'follow'
1150 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1151 # For ?curid=x urls, disallow indexing
1153 'index' => 'noindex',
1154 'follow' => 'follow'
1158 # Otherwise, construct the policy based on the various config variables.
1159 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1161 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1162 # Honour customised robot policies for this namespace
1163 $policy = array_merge(
1165 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1168 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1169 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1170 # a final sanity check that we have really got the parser output.
1171 $policy = array_merge(
1173 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1177 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1178 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1179 $policy = array_merge(
1181 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1189 * Converts a String robot policy into an associative array, to allow
1190 * merging of several policies using array_merge().
1191 * @param $policy Mixed, returns empty array on null/false/'', transparent
1192 * to already-converted arrays, converts String.
1193 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1195 public static function formatRobotPolicy( $policy ) {
1196 if ( is_array( $policy ) ) {
1198 } elseif ( !$policy ) {
1202 $policy = explode( ',', $policy );
1203 $policy = array_map( 'trim', $policy );
1206 foreach ( $policy as $var ) {
1207 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1208 $arr['index'] = $var;
1209 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1210 $arr['follow'] = $var;
1218 * If this request is a redirect view, send "redirected from" subtitle to
1219 * $wgOut. Returns true if the header was needed, false if this is not a
1220 * redirect view. Handles both local and remote redirects.
1224 public function showRedirectedFromHeader() {
1225 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1227 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1228 $sk = $wgUser->getSkin();
1230 if ( isset( $this->mRedirectedFrom
) ) {
1231 // This is an internally redirected page view.
1232 // We'll need a backlink to the source page for navigation.
1233 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1235 $this->mRedirectedFrom
,
1238 array( 'redirect' => 'no' ),
1239 array( 'known', 'noclasses' )
1242 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1243 $wgOut->setSubtitle( $s );
1245 // Set the fragment if one was specified in the redirect
1246 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1247 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1248 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1251 // Add a <link rel="canonical"> tag
1252 $wgOut->addLink( array( 'rel' => 'canonical',
1253 'href' => $this->mTitle
->getLocalURL() )
1258 } elseif ( $rdfrom ) {
1259 // This is an externally redirected view, from some other wiki.
1260 // If it was reported from a trusted site, supply a backlink.
1261 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1262 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1263 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1264 $wgOut->setSubtitle( $s );
1274 * Show a header specific to the namespace currently being viewed, like
1275 * [[MediaWiki:Talkpagetext]]. For Article::view().
1277 public function showNamespaceHeader() {
1280 if ( $this->mTitle
->isTalkPage() ) {
1281 $msg = wfMsgNoTrans( 'talkpageheader' );
1282 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1283 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1289 * Show the footer section of an ordinary page view
1291 public function showViewFooter() {
1292 global $wgOut, $wgUseTrackbacks, $wgRequest;
1294 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1295 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1296 $wgOut->addWikiMsg( 'anontalkpagetext' );
1299 # If we have been passed an &rcid= parameter, we want to give the user a
1300 # chance to mark this new article as patrolled.
1301 $this->showPatrolFooter();
1304 if ( $wgUseTrackbacks ) {
1305 $this->addTrackbacks();
1310 * If patrol is possible, output a patrol UI box. This is called from the
1311 * footer section of ordinary page views. If patrol is not possible or not
1312 * desired, does nothing.
1314 public function showPatrolFooter() {
1315 global $wgOut, $wgRequest, $wgUser;
1317 $rcid = $wgRequest->getVal( 'rcid' );
1319 if ( !$rcid ||
!$this->mTitle
->exists() ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1323 $sk = $wgUser->getSkin();
1326 "<div class='patrollink'>" .
1328 'markaspatrolledlink',
1331 wfMsgHtml( 'markaspatrolledtext' ),
1334 'action' => 'markpatrolled',
1337 array( 'known', 'noclasses' )
1345 * Show the error text for a missing article. For articles in the MediaWiki
1346 * namespace, show the default message text. To be called from Article::view().
1348 public function showMissingArticle() {
1349 global $wgOut, $wgRequest, $wgUser;
1351 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1352 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1353 $parts = explode( '/', $this->mTitle
->getText() );
1354 $rootPart = $parts[0];
1355 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1356 $ip = User
::isIP( $rootPart );
1358 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1359 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1360 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1361 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1362 LogEventsList
::showLogExtract(
1365 $user->getUserPage()->getPrefixedText(),
1369 'showIfEmpty' => false,
1371 'blocked-notice-logextract',
1372 $user->getName() # Support GENDER in notice
1379 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1381 # Show delete and move logs
1382 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1384 'conds' => array( "log_action != 'revision'" ),
1385 'showIfEmpty' => false,
1386 'msgKey' => array( 'moveddeleted-notice' ) )
1389 # Show error message
1390 $oldid = $this->getOldID();
1392 $text = wfMsgNoTrans( 'missing-article',
1393 $this->mTitle
->getPrefixedText(),
1394 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1395 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1396 // Use the default message text
1397 $text = $this->getContent();
1399 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1400 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1401 $errors = array_merge( $createErrors, $editErrors );
1403 if ( !count( $errors ) ) {
1404 $text = wfMsgNoTrans( 'noarticletext' );
1406 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1409 $text = "<div class='noarticletext'>\n$text\n</div>";
1411 if ( !$this->hasViewableContent() ) {
1412 // If there's no backing content, send a 404 Not Found
1413 // for better machine handling of broken links.
1414 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1417 $wgOut->addWikiText( $text );
1421 * If the revision requested for view is deleted, check permissions.
1422 * Send either an error message or a warning header to $wgOut.
1424 * @return boolean true if the view is allowed, false if not.
1426 public function showDeletedRevisionHeader() {
1427 global $wgOut, $wgRequest;
1429 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1434 // If the user is not allowed to see it...
1435 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1436 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1437 'rev-deleted-text-permission' );
1440 // If the user needs to confirm that they want to see it...
1441 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1442 # Give explanation and add a link to view the revision...
1443 $oldid = intval( $this->getOldID() );
1444 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1445 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1446 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1447 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1448 array( $msg, $link ) );
1451 // We are allowed to see...
1453 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1454 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1455 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1462 * Should the parser cache be used?
1466 public function useParserCache( $oldid ) {
1467 global $wgUser, $wgEnableParserCache;
1469 return $wgEnableParserCache
1470 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1473 && !$this->mTitle
->isCssOrJsPage()
1474 && !$this->mTitle
->isCssJsSubpage();
1478 * Execute the uncached parse for action=view
1480 public function doViewParse() {
1483 $oldid = $this->getOldID();
1484 $useParserCache = $this->useParserCache( $oldid );
1485 $parserOptions = clone $this->getParserOptions();
1487 # Render printable version, use printable version cache
1488 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1490 # Don't show section-edit links on old revisions... this way lies madness.
1491 $parserOptions->setEditSection( $this->isCurrent() );
1492 $useParserCache = $this->useParserCache( $oldid );
1493 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1497 * Try to fetch an expired entry from the parser cache. If it is present,
1498 * output it and return true. If it is not present, output nothing and
1499 * return false. This is used as a callback function for
1500 * PoolCounter::executeProtected().
1504 public function tryDirtyCache() {
1507 $parserCache = ParserCache
::singleton();
1508 $options = $this->getParserOptions();
1509 $options->setIsPrintable( $wgOut->isPrintable() );
1510 $output = $parserCache->getDirty( $this, $options );
1513 wfDebug( __METHOD__
. ": sending dirty output\n" );
1514 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1515 $wgOut->setSquidMaxage( 0 );
1516 $this->mParserOutput
= $output;
1517 $wgOut->addParserOutput( $output );
1518 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1522 wfDebugLog( 'dirty', "dirty missing\n" );
1523 wfDebug( __METHOD__
. ": no dirty cache\n" );
1530 * Show an error page for an error from the pool counter.
1531 * @param $status Status
1533 public function showPoolError( $status ) {
1536 $wgOut->clearHTML(); // for release() errors
1537 $wgOut->enableClientCache( false );
1538 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1539 $wgOut->addWikiText(
1540 '<div class="errorbox">' .
1541 $status->getWikiText( false, 'view-pool-error' ) .
1549 * @param $target Title object or Array of destination(s) to redirect
1550 * @param $appendSubtitle Boolean [optional]
1551 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1552 * @return string containing HMTL with redirect link
1554 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1555 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1558 if ( !is_array( $target ) ) {
1559 $target = array( $target );
1562 $imageDir = $wgContLang->getDir();
1563 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1564 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1565 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of Unicode?
1567 if ( $appendSubtitle ) {
1568 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1571 $sk = $wgUser->getSkin();
1572 // the loop prepends the arrow image before the link, so the first case needs to be outside
1573 $title = array_shift( $target );
1575 if ( $forceKnown ) {
1578 htmlspecialchars( $title->getFullText() ),
1581 array( 'known', 'noclasses' )
1584 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1587 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1588 foreach ( $target as $rt ) {
1589 if ( $forceKnown ) {
1590 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1593 htmlspecialchars( $rt->getFullText() ),
1596 array( 'known', 'noclasses' )
1599 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1600 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1604 return '<img src="' . $imageUrl . '" alt="#REDIRECT " />' .
1605 '<span class="redirectText">' . $link . '</span>';
1609 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1611 public function addTrackbacks() {
1612 global $wgOut, $wgUser;
1614 $dbr = wfGetDB( DB_SLAVE
);
1615 $tbs = $dbr->select( 'trackbacks',
1616 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1617 array( 'tb_page' => $this->getID() )
1620 if ( !$dbr->numRows( $tbs ) ) {
1625 while ( $o = $dbr->fetchObject( $tbs ) ) {
1628 if ( $wgUser->isAllowed( 'trackback' ) ) {
1629 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1630 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1631 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1635 $tbtext .= wfMsg( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1643 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1647 * Removes trackback record for current article from trackbacks table
1649 public function deletetrackback() {
1650 global $wgUser, $wgRequest, $wgOut;
1652 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1653 $wgOut->addWikiMsg( 'sessionfailure' );
1658 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1660 if ( count( $permission_errors ) ) {
1661 $wgOut->showPermissionsErrorPage( $permission_errors );
1666 $db = wfGetDB( DB_MASTER
);
1667 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1669 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1670 $this->mTitle
->invalidateCache();
1674 * Handle action=render
1677 public function render() {
1680 $wgOut->setArticleBodyOnly( true );
1685 * Handle action=purge
1687 public function purge() {
1688 global $wgUser, $wgRequest, $wgOut;
1690 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1691 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1696 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1697 $button = wfMsgExt( 'confirm_purge_button', array( 'escapenoentities' ) );
1698 $form = "<form method=\"post\" action=\"$action\">\n" .
1699 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1701 $top = wfMsgExt( 'confirm-purge-top', array( 'parse' ) );
1702 $bottom = wfMsgExt( 'confirm-purge-bottom', array( 'parse' ) );
1703 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1704 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1705 $wgOut->addHTML( $top . $form . $bottom );
1710 * Perform the actions of a page purging
1712 public function doPurge() {
1715 // Invalidate the cache
1716 $this->mTitle
->invalidateCache();
1718 if ( $wgUseSquid ) {
1719 // Commit the transaction before the purge is sent
1720 $dbw = wfGetDB( DB_MASTER
);
1724 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1725 $update->doUpdate();
1728 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1729 global $wgMessageCache;
1731 if ( $this->getID() == 0 ) {
1734 $text = $this->getRawText();
1737 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1742 * Insert a new empty page record for this article.
1743 * This *must* be followed up by creating a revision
1744 * and running $this->updateRevisionOn( ... );
1745 * or else the record will be left in a funky state.
1746 * Best if all done inside a transaction.
1748 * @param $dbw Database
1749 * @return int The newly created page_id key, or false if the title already existed
1752 public function insertOn( $dbw ) {
1753 wfProfileIn( __METHOD__
);
1755 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1756 $dbw->insert( 'page', array(
1757 'page_id' => $page_id,
1758 'page_namespace' => $this->mTitle
->getNamespace(),
1759 'page_title' => $this->mTitle
->getDBkey(),
1760 'page_counter' => 0,
1761 'page_restrictions' => '',
1762 'page_is_redirect' => 0, # Will set this shortly...
1764 'page_random' => wfRandom(),
1765 'page_touched' => $dbw->timestamp(),
1766 'page_latest' => 0, # Fill this in shortly...
1767 'page_len' => 0, # Fill this in shortly...
1768 ), __METHOD__
, 'IGNORE' );
1770 $affected = $dbw->affectedRows();
1773 $newid = $dbw->insertId();
1774 $this->mTitle
->resetArticleId( $newid );
1776 wfProfileOut( __METHOD__
);
1778 return $affected ?
$newid : false;
1782 * Update the page record to point to a newly saved revision.
1784 * @param $dbw Database object
1785 * @param $revision Revision: For ID number, and text used to set
1786 length and redirect status fields
1787 * @param $lastRevision Integer: if given, will not overwrite the page field
1788 * when different from the currently set value.
1789 * Giving 0 indicates the new page flag should be set
1791 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1792 * removing rows in redirect table.
1793 * @param $setNewFlag Boolean: Set to true if a page flag should be set
1794 * Needed when $lastRevision has to be set to sth. !=0
1795 * @return bool true on success, false on failure
1798 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
1799 wfProfileIn( __METHOD__
);
1801 $text = $revision->getText();
1802 $rt = Title
::newFromRedirect( $text );
1804 $conditions = array( 'page_id' => $this->getId() );
1806 if ( !is_null( $lastRevision ) ) {
1807 # An extra check against threads stepping on each other
1808 $conditions['page_latest'] = $lastRevision;
1811 if ( !$setNewFlag ) {
1812 $setNewFlag = ( $lastRevision === 0 );
1815 $dbw->update( 'page',
1817 'page_latest' => $revision->getId(),
1818 'page_touched' => $dbw->timestamp(),
1819 'page_is_new' => $setNewFlag,
1820 'page_is_redirect' => $rt !== null ?
1 : 0,
1821 'page_len' => strlen( $text ),
1826 $result = $dbw->affectedRows() != 0;
1828 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1831 wfProfileOut( __METHOD__
);
1836 * Add row to the redirect table if this is a redirect, remove otherwise.
1838 * @param $dbw Database
1839 * @param $redirectTitle a title object pointing to the redirect target,
1840 * or NULL if this is not a redirect
1841 * @param $lastRevIsRedirect If given, will optimize adding and
1842 * removing rows in redirect table.
1843 * @return bool true on success, false on failure
1846 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1847 // Always update redirects (target link might have changed)
1848 // Update/Insert if we don't know if the last revision was a redirect or not
1849 // Delete if changing from redirect to non-redirect
1850 $isRedirect = !is_null( $redirectTitle );
1852 if ( $isRedirect ||
is_null( $lastRevIsRedirect ) ||
$lastRevIsRedirect !== $isRedirect ) {
1853 wfProfileIn( __METHOD__
);
1854 if ( $isRedirect ) {
1855 // This title is a redirect, Add/Update row in the redirect table
1856 $set = array( /* SET */
1857 'rd_namespace' => $redirectTitle->getNamespace(),
1858 'rd_title' => $redirectTitle->getDBkey(),
1859 'rd_from' => $this->getId(),
1861 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1863 // This is not a redirect, remove row from redirect table
1864 $where = array( 'rd_from' => $this->getId() );
1865 $dbw->delete( 'redirect', $where, __METHOD__
);
1868 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1869 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1871 wfProfileOut( __METHOD__
);
1873 return ( $dbw->affectedRows() != 0 );
1880 * If the given revision is newer than the currently set page_latest,
1881 * update the page record. Otherwise, do nothing.
1883 * @param $dbw Database object
1884 * @param $revision Revision object
1887 public function updateIfNewerOn( &$dbw, $revision ) {
1888 wfProfileIn( __METHOD__
);
1890 $row = $dbw->selectRow(
1891 array( 'revision', 'page' ),
1892 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1894 'page_id' => $this->getId(),
1895 'page_latest=rev_id' ),
1899 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1900 wfProfileOut( __METHOD__
);
1903 $prev = $row->rev_id
;
1904 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1906 # No or missing previous revision; mark the page as new
1908 $lastRevIsRedirect = null;
1911 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1913 wfProfileOut( __METHOD__
);
1918 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1919 * @param $text String: new text of the section
1920 * @param $summary String: new section's subject, only if $section is 'new'
1921 * @param $edittime String: revision timestamp or null to use the current revision
1922 * @return string Complete article text, or null if error
1924 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1925 wfProfileIn( __METHOD__
);
1927 if ( strval( $section ) == '' ) {
1928 // Whole-page edit; let the whole text through
1930 if ( is_null( $edittime ) ) {
1931 $rev = Revision
::newFromTitle( $this->mTitle
);
1933 $dbw = wfGetDB( DB_MASTER
);
1934 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1938 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1939 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1943 $oldtext = $rev->getText();
1945 if ( $section == 'new' ) {
1946 # Inserting a new section
1947 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1948 $text = strlen( trim( $oldtext ) ) > 0
1949 ?
"{$oldtext}\n\n{$subject}{$text}"
1950 : "{$subject}{$text}";
1952 # Replacing an existing section; roll out the big guns
1955 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1959 wfProfileOut( __METHOD__
);
1964 * This function is not deprecated until somebody fixes the core not to use
1965 * it. Nevertheless, use Article::doEdit() instead.
1967 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1968 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1969 ( $isminor ? EDIT_MINOR
: 0 ) |
1970 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1971 ( $bot ? EDIT_FORCE_BOT
: 0 );
1973 $this->doEdit( $text, $summary, $flags, false, null, $watchthis, $comment, '', true );
1977 * @deprecated use Article::doEdit()
1979 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1980 wfDeprecated( __METHOD__
);
1981 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1982 ( $minor ? EDIT_MINOR
: 0 ) |
1983 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1985 $status = $this->doEdit( $text, $summary, $flags, false, null, $watchthis, false, $sectionanchor, true );
1987 if ( !$status->isOK() ) {
1995 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1997 * @return Int updated $flags
1999 function checkFlags( $flags ) {
2000 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
2001 if ( $this->mTitle
->getArticleID() ) {
2002 $flags |
= EDIT_UPDATE
;
2014 * Change an existing article or create a new article. Updates RC and all necessary caches,
2015 * optionally via the deferred update array.
2017 * $wgUser must be set before calling this function.
2019 * @param $text String: new text
2020 * @param $summary String: edit summary
2021 * @param $flags Integer bitfield:
2023 * Article is known or assumed to be non-existent, create a new one
2025 * Article is known or assumed to be pre-existing, update it
2027 * Mark this edit minor, if the user is allowed to do so
2029 * Do not log the change in recentchanges
2031 * Mark the edit a "bot" edit regardless of user rights
2032 * EDIT_DEFER_UPDATES
2033 * Defer some of the updates until the end of index.php
2035 * Fill in blank summaries with generated text where possible
2037 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2038 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2039 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2040 * edit-already-exists error will be returned. These two conditions are also possible with
2041 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2043 * @param $baseRevId the revision ID this edit was based off, if any
2044 * @param $user Optional user object, $wgUser will be used if not passed
2045 * @param $watchthis Watch the page if true, unwatch the page if false, do nothing if null
2046 * @param $sectionanchor The section anchor for the page; used for redirecting the user back to the page
2047 * after the edit is successfully committed
2048 * @param $redirect If true, redirect the user back to the page after the edit is successfully committed
2050 * @return Status object. Possible errors:
2051 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2052 * edit-gone-missing: In update mode, but the article didn't exist
2053 * edit-conflict: In update mode, the article changed unexpectedly
2054 * edit-no-change: Warning that the text was the same as before
2055 * edit-already-exists: In creation mode, but the article already exists
2057 * Extensions may define additional errors.
2059 * $return->value will contain an associative array with members as follows:
2060 * new: Boolean indicating if the function attempted to create a new article
2061 * revision: The revision object for the inserted revision, or null
2063 * Compatibility note: this function previously returned a boolean value indicating success/failure
2065 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null , $watchthis = null,
2066 $comment = false, $sectionanchor = '', $redirect = false) {
2067 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2069 # Low-level sanity check
2070 if ( $this->mTitle
->getText() == '' ) {
2071 throw new MWException( 'Something is trying to edit an article with an empty title' );
2074 wfProfileIn( __METHOD__
);
2076 $user = is_null( $user ) ?
$wgUser : $user;
2077 $status = Status
::newGood( array() );
2079 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2080 $this->loadPageData();
2082 $flags = $this->checkFlags( $flags );
2084 # If this is a comment, add the summary as headline
2085 if ( $comment && $summary != "" ) {
2086 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
2089 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2090 $flags & EDIT_MINOR
, &$watchthis, null, &$flags, &$status) ) )
2092 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2093 wfProfileOut( __METHOD__
);
2095 if ( $status->isOK() ) {
2096 $status->fatal( 'edit-hook-aborted' );
2102 # Silently ignore EDIT_MINOR if not allowed
2103 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2104 $bot = $flags & EDIT_FORCE_BOT
;
2106 $oldtext = $this->getRawText(); // current revision
2107 $oldsize = strlen( $oldtext );
2109 # Provide autosummaries if one is not provided and autosummaries are enabled.
2110 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2111 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2114 $editInfo = $this->prepareTextForEdit( $text );
2115 $text = $editInfo->pst
;
2116 $newsize = strlen( $text );
2118 $dbw = wfGetDB( DB_MASTER
);
2119 $now = wfTimestampNow();
2120 $this->mTimestamp
= $now;
2122 if ( $flags & EDIT_UPDATE
) {
2123 # Update article, but only if changed.
2124 $status->value
['new'] = false;
2126 # Make sure the revision is either completely inserted or not inserted at all
2127 if ( !$wgDBtransactions ) {
2128 $userAbort = ignore_user_abort( true );
2133 $changed = ( strcmp( $text, $oldtext ) != 0 );
2136 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
2137 - (int)$this->isCountable( $oldtext );
2138 $this->mTotalAdjustment
= 0;
2140 if ( !$this->mLatest
) {
2141 # Article gone missing
2142 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2143 $status->fatal( 'edit-gone-missing' );
2145 wfProfileOut( __METHOD__
);
2149 $revision = new Revision( array(
2150 'page' => $this->getId(),
2151 'comment' => $summary,
2152 'minor_edit' => $isminor,
2154 'parent_id' => $this->mLatest
,
2155 'user' => $user->getId(),
2156 'user_text' => $user->getName(),
2160 $revisionId = $revision->insertOn( $dbw );
2164 # Note that we use $this->mLatest instead of fetching a value from the master DB
2165 # during the course of this function. This makes sure that EditPage can detect
2166 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2167 # before this function is called. A previous function used a separate query, this
2168 # creates a window where concurrent edits can cause an ignored edit conflict.
2169 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2172 /* Belated edit conflict! Run away!! */
2173 $status->fatal( 'edit-conflict' );
2175 # Delete the invalid revision if the DB is not transactional
2176 if ( !$wgDBtransactions ) {
2177 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2183 global $wgUseRCPatrol;
2184 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2185 # Update recentchanges
2186 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2187 # Mark as patrolled if the user can do so
2188 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan( 'autopatrol' );
2189 # Add RC row to the DB
2190 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2191 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2192 $revisionId, $patrolled
2195 # Log auto-patrolled edits
2197 PatrolLog
::record( $rc, true );
2200 $user->incEditCount();
2204 $status->warning( 'edit-no-change' );
2206 // Keep the same revision ID, but do some updates on it
2207 $revisionId = $this->getRevIdFetched();
2208 // Update page_touched, this is usually implicit in the page update
2209 // Other cache updates are done in onArticleEdit()
2210 $this->mTitle
->invalidateCache();
2213 if ( !$wgDBtransactions ) {
2214 ignore_user_abort( $userAbort );
2217 // Now that ignore_user_abort is restored, we can respond to fatal errors
2218 if ( !$status->isOK() ) {
2219 wfProfileOut( __METHOD__
);
2223 # Invalidate cache of this article and all pages using this article
2224 # as a template. Partly deferred.
2225 Article
::onArticleEdit( $this->mTitle
);
2226 # Update links tables, site stats, etc.
2227 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2229 # Create new article
2230 $status->value
['new'] = true;
2232 # Set statistics members
2233 # We work out if it's countable after PST to avoid counter drift
2234 # when articles are created with {{subst:}}
2235 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2236 $this->mTotalAdjustment
= 1;
2240 # Add the page record; stake our claim on this title!
2241 # This will return false if the article already exists
2242 $newid = $this->insertOn( $dbw );
2244 if ( $newid === false ) {
2246 $status->fatal( 'edit-already-exists' );
2248 wfProfileOut( __METHOD__
);
2252 # Save the revision text...
2253 $revision = new Revision( array(
2255 'comment' => $summary,
2256 'minor_edit' => $isminor,
2258 'user' => $user->getId(),
2259 'user_text' => $user->getName(),
2261 $revisionId = $revision->insertOn( $dbw );
2263 $this->mTitle
->resetArticleID( $newid );
2265 # Update the page record with revision data
2266 $this->updateRevisionOn( $dbw, $revision, 0 );
2268 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2270 # Update recentchanges
2271 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2272 global $wgUseRCPatrol, $wgUseNPPatrol;
2274 # Mark as patrolled if the user can do so
2275 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && $this->mTitle
->userCan( 'autopatrol' );
2276 # Add RC row to the DB
2277 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2278 '', strlen( $text ), $revisionId, $patrolled );
2280 # Log auto-patrolled edits
2282 PatrolLog
::record( $rc, true );
2285 $user->incEditCount();
2288 # Update links, etc.
2289 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2292 Article
::onArticleCreate( $this->mTitle
);
2294 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2295 $flags & EDIT_MINOR
, &$watchthis, null, &$flags, $revision ) );
2298 # Do updates right now unless deferral was requested
2299 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2303 // Return the new revision (or null) to the caller
2304 $status->value
['revision'] = $revision;
2306 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2307 $flags & EDIT_MINOR
, &$watchthis, null, &$flags, $revision, &$status, $baseRevId,
2310 # Watch or unwatch the page
2311 if ( $watchthis === true ) {
2312 if ( !$this->mTitle
->userIsWatching() ) {
2317 } elseif ( $watchthis === false ) {
2318 if ( $this->mTitle
->userIsWatching() ) {
2325 # Give extensions a chance to modify URL query on update
2328 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
2331 if ( $sectionanchor ||
$extraQuery ) {
2332 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
2334 $this->doRedirect( $this->isRedirect( $text ) );
2338 wfProfileOut( __METHOD__
);
2344 * @deprecated wrapper for doRedirect
2346 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2347 wfDeprecated( __METHOD__
);
2348 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2352 * Output a redirect back to the article.
2353 * This is typically used after an edit.
2355 * @param $noRedir Boolean: add redirect=no
2356 * @param $sectionAnchor String: section to redirect to, including "#"
2357 * @param $extraQuery String: extra query params
2359 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2363 $query = 'redirect=no';
2365 $query .= "&$extraQuery";
2367 $query = $extraQuery;
2370 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2374 * Mark this particular edit/page as patrolled
2376 public function markpatrolled() {
2377 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2379 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2381 # If we haven't been given an rc_id value, we can't do anything
2382 $rcid = (int) $wgRequest->getVal( 'rcid' );
2383 $rc = RecentChange
::newFromId( $rcid );
2385 if ( is_null( $rc ) ) {
2386 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2390 # It would be nice to see where the user had actually come from, but for now just guess
2391 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2392 $return = SpecialPage
::getTitleFor( $returnto );
2394 $dbw = wfGetDB( DB_MASTER
);
2395 $errors = $rc->doMarkPatrolled();
2397 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2398 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2403 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2404 // The hook itself has handled any output
2408 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2409 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2410 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2411 $wgOut->returnToMain( false, $return );
2416 if ( !empty( $errors ) ) {
2417 $wgOut->showPermissionsErrorPage( $errors );
2423 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2424 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2425 $wgOut->returnToMain( false, $return );
2429 * User-interface handler for the "watch" action
2431 public function watch() {
2432 global $wgUser, $wgOut;
2434 if ( $wgUser->isAnon() ) {
2435 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2439 if ( wfReadOnly() ) {
2440 $wgOut->readOnlyPage();
2444 if ( $this->doWatch() ) {
2445 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2446 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2447 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
2450 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2454 * Add this page to $wgUser's watchlist
2455 * @return bool true on successful watch operation
2457 public function doWatch() {
2460 if ( $wgUser->isAnon() ) {
2464 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2465 $wgUser->addWatch( $this->mTitle
);
2466 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2473 * User interface handler for the "unwatch" action.
2475 public function unwatch() {
2476 global $wgUser, $wgOut;
2478 if ( $wgUser->isAnon() ) {
2479 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2483 if ( wfReadOnly() ) {
2484 $wgOut->readOnlyPage();
2488 if ( $this->doUnwatch() ) {
2489 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2490 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2491 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
2494 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2498 * Stop watching a page
2499 * @return bool true on successful unwatch
2501 public function doUnwatch() {
2504 if ( $wgUser->isAnon() ) {
2508 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2509 $wgUser->removeWatch( $this->mTitle
);
2510 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2517 * action=protect handler
2519 public function protect() {
2520 $form = new ProtectionForm( $this );
2525 * action=unprotect handler (alias)
2527 public function unprotect() {
2532 * Update the article's restriction field, and leave a log entry.
2534 * @param $limit Array: set of restriction keys
2535 * @param $reason String
2536 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2537 * @param $expiry Array: per restriction type expiration
2538 * @return bool true on success
2540 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2541 global $wgUser, $wgContLang;
2543 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2545 $id = $this->mTitle
->getArticleID();
2548 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2552 if ( wfReadOnly() ) {
2553 wfDebug( "updateRestrictions failed: read-only\n" );
2557 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2558 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2566 // Take this opportunity to purge out expired restrictions
2567 Title
::purgeExpiredRestrictions();
2569 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2570 # we expect a single selection, but the schema allows otherwise.
2572 $updated = Article
::flattenRestrictions( $limit );
2575 foreach ( $restrictionTypes as $action ) {
2576 if ( isset( $expiry[$action] ) ) {
2577 # Get current restrictions on $action
2578 $aLimits = $this->mTitle
->getRestrictions( $action );
2579 $current[$action] = implode( '', $aLimits );
2580 # Are any actual restrictions being dealt with here?
2581 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2583 # If something changed, we need to log it. Checking $aRChanged
2584 # assures that "unprotecting" a page that is not protected does
2585 # not log just because the expiry was "changed".
2586 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2592 $current = Article
::flattenRestrictions( $current );
2594 $changed = ( $changed ||
$current != $updated );
2595 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2596 $protect = ( $updated != '' );
2598 # If nothing's changed, do nothing
2600 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2601 $dbw = wfGetDB( DB_MASTER
);
2603 # Prepare a null revision to be added to the history
2604 $modified = $current != '' && $protect;
2607 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2609 $comment_type = 'unprotectedarticle';
2612 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2614 # Only restrictions with the 'protect' right can cascade...
2615 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2616 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2618 # The schema allows multiple restrictions
2619 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2623 $cascade_description = '';
2626 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2630 $comment .= ": $reason";
2633 $editComment = $comment;
2634 $encodedExpiry = array();
2635 $protect_description = '';
2636 foreach ( $limit as $action => $restrictions ) {
2637 if ( !isset( $expiry[$action] ) )
2638 $expiry[$action] = 'infinite';
2640 $encodedExpiry[$action] = Block
::encodeExpiry( $expiry[$action], $dbw );
2641 if ( $restrictions != '' ) {
2642 $protect_description .= "[$action=$restrictions] (";
2643 if ( $encodedExpiry[$action] != 'infinity' ) {
2644 $protect_description .= wfMsgForContent( 'protect-expiring',
2645 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2646 $wgContLang->date( $expiry[$action], false, false ) ,
2647 $wgContLang->time( $expiry[$action], false, false ) );
2649 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2652 $protect_description .= ') ';
2655 $protect_description = trim( $protect_description );
2657 if ( $protect_description && $protect ) {
2658 $editComment .= " ($protect_description)";
2662 $editComment .= "$cascade_description";
2665 # Update restrictions table
2666 foreach ( $limit as $action => $restrictions ) {
2667 if ( $restrictions != '' ) {
2668 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2669 array( 'pr_page' => $id,
2670 'pr_type' => $action,
2671 'pr_level' => $restrictions,
2672 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2673 'pr_expiry' => $encodedExpiry[$action]
2678 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2679 'pr_type' => $action ), __METHOD__
);
2683 # Insert a null revision
2684 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2685 $nullRevId = $nullRevision->insertOn( $dbw );
2687 $latest = $this->getLatest();
2688 # Update page record
2689 $dbw->update( 'page',
2691 'page_touched' => $dbw->timestamp(),
2692 'page_restrictions' => '',
2693 'page_latest' => $nullRevId
2694 ), array( /* WHERE */
2696 ), 'Article::protect'
2699 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2700 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2702 # Update the protection log
2703 $log = new LogPage( 'protect' );
2705 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2706 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2708 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2711 } # End "changed" check
2717 * Take an array of page restrictions and flatten it to a string
2718 * suitable for insertion into the page_restrictions field.
2719 * @param $limit Array
2722 protected static function flattenRestrictions( $limit ) {
2723 if ( !is_array( $limit ) ) {
2724 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2730 foreach ( $limit as $action => $restrictions ) {
2731 if ( $restrictions != '' ) {
2732 $bits[] = "$action=$restrictions";
2736 return implode( ':', $bits );
2740 * Auto-generates a deletion reason
2742 * @param &$hasHistory Boolean: whether the page has a history
2743 * @return mixed String containing deletion reason or empty string, or boolean false
2744 * if no revision occurred
2746 public function generateReason( &$hasHistory ) {
2749 $dbw = wfGetDB( DB_MASTER
);
2750 // Get the last revision
2751 $rev = Revision
::newFromTitle( $this->mTitle
);
2753 if ( is_null( $rev ) ) {
2757 // Get the article's contents
2758 $contents = $rev->getText();
2761 // If the page is blank, use the text from the previous revision,
2762 // which can only be blank if there's a move/import/protect dummy revision involved
2763 if ( $contents == '' ) {
2764 $prev = $rev->getPrevious();
2767 $contents = $prev->getText();
2772 // Find out if there was only one contributor
2773 // Only scan the last 20 revisions
2774 $res = $dbw->select( 'revision', 'rev_user_text',
2775 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2777 array( 'LIMIT' => 20 )
2780 if ( $res === false ) {
2781 // This page has no revisions, which is very weird
2785 $hasHistory = ( $res->numRows() > 1 );
2786 $row = $dbw->fetchObject( $res );
2788 if ( $row ) { // $row is false if the only contributor is hidden
2789 $onlyAuthor = $row->rev_user_text
;
2790 // Try to find a second contributor
2791 foreach ( $res as $row ) {
2792 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2793 $onlyAuthor = false;
2798 $onlyAuthor = false;
2801 $dbw->freeResult( $res );
2803 // Generate the summary with a '$1' placeholder
2805 // The current revision is blank and the one before is also
2806 // blank. It's just not our lucky day
2807 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2809 if ( $onlyAuthor ) {
2810 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2812 $reason = wfMsgForContent( 'excontent', '$1' );
2816 if ( $reason == '-' ) {
2817 // Allow these UI messages to be blanked out cleanly
2821 // Replace newlines with spaces to prevent uglyness
2822 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2823 // Calculate the maximum amount of chars to get
2824 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2825 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2826 $contents = $wgContLang->truncate( $contents, $maxLength );
2827 // Remove possible unfinished links
2828 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2829 // Now replace the '$1' placeholder
2830 $reason = str_replace( '$1', $contents, $reason );
2837 * UI entry point for page deletion
2839 public function delete() {
2840 global $wgUser, $wgOut, $wgRequest;
2842 $confirm = $wgRequest->wasPosted() &&
2843 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2845 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2846 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2848 $reason = $this->DeleteReasonList
;
2850 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2851 // Entry from drop down menu + additional comment
2852 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2853 } elseif ( $reason == 'other' ) {
2854 $reason = $this->DeleteReason
;
2857 # Flag to hide all contents of the archived revisions
2858 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2860 # This code desperately needs to be totally rewritten
2862 # Read-only check...
2863 if ( wfReadOnly() ) {
2864 $wgOut->readOnlyPage();
2870 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2872 if ( count( $permission_errors ) > 0 ) {
2873 $wgOut->showPermissionsErrorPage( $permission_errors );
2878 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2880 # Better double-check that it hasn't been deleted yet!
2881 $dbw = wfGetDB( DB_MASTER
);
2882 $conds = $this->mTitle
->pageCond();
2883 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2884 if ( $latest === false ) {
2885 $wgOut->showFatalError(
2888 array( 'class' => 'error mw-error-cannotdelete' ),
2889 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2892 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2893 LogEventsList
::showLogExtract(
2896 $this->mTitle
->getPrefixedText()
2902 # Hack for big sites
2903 $bigHistory = $this->isBigDeletion();
2904 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2905 global $wgLang, $wgDeleteRevisionsLimit;
2907 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2908 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2914 $this->doDelete( $reason, $suppress );
2916 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2918 } elseif ( $this->mTitle
->userIsWatching() ) {
2925 // Generate deletion reason
2926 $hasHistory = false;
2928 $reason = $this->generateReason( $hasHistory );
2931 // If the page has a history, insert a warning
2932 if ( $hasHistory && !$confirm ) {
2935 $skin = $wgUser->getSkin();
2936 $revisions = $this->estimateRevisionCount();
2937 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2938 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2939 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2943 if ( $bigHistory ) {
2944 global $wgDeleteRevisionsLimit;
2946 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2947 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2951 return $this->confirmDelete( $reason );
2955 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2957 public function isBigDeletion() {
2958 global $wgDeleteRevisionsLimit;
2960 if ( $wgDeleteRevisionsLimit ) {
2961 $revCount = $this->estimateRevisionCount();
2963 return $revCount > $wgDeleteRevisionsLimit;
2970 * @return int approximate revision count
2972 public function estimateRevisionCount() {
2973 $dbr = wfGetDB( DB_SLAVE
);
2975 // For an exact count...
2976 // return $dbr->selectField( 'revision', 'COUNT(*)',
2977 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2978 return $dbr->estimateRowCount( 'revision', '*',
2979 array( 'rev_page' => $this->getId() ), __METHOD__
);
2983 * Get the last N authors
2984 * @param $num Integer: number of revisions to get
2985 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2986 * @return array Array of authors, duplicates not removed
2988 public function getLastNAuthors( $num, $revLatest = 0 ) {
2989 wfProfileIn( __METHOD__
);
2990 // First try the slave
2991 // If that doesn't have the latest revision, try the master
2993 $db = wfGetDB( DB_SLAVE
);
2996 $res = $db->select( array( 'page', 'revision' ),
2997 array( 'rev_id', 'rev_user_text' ),
2999 'page_namespace' => $this->mTitle
->getNamespace(),
3000 'page_title' => $this->mTitle
->getDBkey(),
3001 'rev_page = page_id'
3002 ), __METHOD__
, $this->getSelectOptions( array(
3003 'ORDER BY' => 'rev_timestamp DESC',
3009 wfProfileOut( __METHOD__
);
3013 $row = $db->fetchObject( $res );
3015 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
3016 $db = wfGetDB( DB_MASTER
);
3021 } while ( $continue );
3023 $authors = array( $row->rev_user_text
);
3025 while ( $row = $db->fetchObject( $res ) ) {
3026 $authors[] = $row->rev_user_text
;
3029 wfProfileOut( __METHOD__
);
3034 * Output deletion confirmation dialog
3035 * @param $reason String: prefilled reason
3037 public function confirmDelete( $reason ) {
3038 global $wgOut, $wgUser;
3040 wfDebug( "Article::confirmDelete\n" );
3042 $deleteBackLink = $wgUser->getSkin()->link(
3047 array( 'known', 'noclasses' )
3049 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
3050 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3051 $wgOut->addWikiMsg( 'confirmdeletetext' );
3053 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
3055 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
3056 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
3058 <td class='mw-input'><strong>" .
3059 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
3060 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
3066 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
3068 $form = Xml
::openElement( 'form', array( 'method' => 'post',
3069 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
3070 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
3071 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
3072 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
3073 "<tr id=\"wpDeleteReasonListRow\">
3074 <td class='mw-label'>" .
3075 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
3077 <td class='mw-input'>" .
3078 Xml
::listDropDown( 'wpDeleteReasonList',
3079 wfMsgForContent( 'deletereason-dropdown' ),
3080 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
3083 <tr id=\"wpDeleteReasonRow\">
3084 <td class='mw-label'>" .
3085 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
3087 <td class='mw-input'>" .
3088 Html
::input( 'wpReason', $reason, 'text', array(
3090 'maxlength' => '255',
3098 # Disallow watching if user is not logged in
3099 if ( $wgUser->isLoggedIn() ) {
3103 <td class='mw-input'>" .
3104 Xml
::checkLabel( wfMsg( 'watchthis' ),
3105 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3114 <td class='mw-submit'>" .
3115 Xml
::submitButton( wfMsg( 'deletepage' ),
3116 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3119 Xml
::closeElement( 'table' ) .
3120 Xml
::closeElement( 'fieldset' ) .
3121 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
3122 Xml
::closeElement( 'form' );
3124 if ( $wgUser->isAllowed( 'editinterface' ) ) {
3125 $skin = $wgUser->getSkin();
3126 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
3127 $link = $skin->link(
3129 wfMsgHtml( 'delete-edit-reasonlist' ),
3131 array( 'action' => 'edit' )
3133 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3136 $wgOut->addHTML( $form );
3137 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3138 LogEventsList
::showLogExtract(
3141 $this->mTitle
->getPrefixedText()
3146 * Perform a deletion and output success or failure messages
3148 public function doDelete( $reason, $suppress = false ) {
3149 global $wgOut, $wgUser;
3151 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
3154 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3155 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
3156 $deleted = $this->mTitle
->getPrefixedText();
3158 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3159 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3161 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3163 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3164 $wgOut->returnToMain( false );
3165 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3168 if ( $error == '' ) {
3169 $wgOut->showFatalError(
3172 array( 'class' => 'error mw-error-cannotdelete' ),
3173 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3177 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3179 LogEventsList
::showLogExtract(
3182 $this->mTitle
->getPrefixedText()
3185 $wgOut->showFatalError( $error );
3191 * Back-end article deletion
3192 * Deletes the article with database consistency, writes logs, purges caches
3194 * @param $reason string delete reason for deletion log
3195 * @param suppress bitfield
3196 * Revision::DELETED_TEXT
3197 * Revision::DELETED_COMMENT
3198 * Revision::DELETED_USER
3199 * Revision::DELETED_RESTRICTED
3200 * @param $id int article ID
3201 * @param $commit boolean defaults to true, triggers transaction end
3202 * @return boolean true if successful
3204 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
3205 global $wgUseSquid, $wgDeferredUpdateList;
3206 global $wgUseTrackbacks;
3208 wfDebug( __METHOD__
. "\n" );
3210 $dbw = wfGetDB( DB_MASTER
);
3211 $ns = $this->mTitle
->getNamespace();
3212 $t = $this->mTitle
->getDBkey();
3213 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
3215 if ( $t == '' ||
$id == 0 ) {
3219 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3220 array_push( $wgDeferredUpdateList, $u );
3222 // Bitfields to further suppress the content
3225 // This should be 15...
3226 $bitfield |
= Revision
::DELETED_TEXT
;
3227 $bitfield |
= Revision
::DELETED_COMMENT
;
3228 $bitfield |
= Revision
::DELETED_USER
;
3229 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3231 $bitfield = 'rev_deleted';
3235 // For now, shunt the revision data into the archive table.
3236 // Text is *not* removed from the text table; bulk storage
3237 // is left intact to avoid breaking block-compression or
3238 // immutable storage schemes.
3240 // For backwards compatibility, note that some older archive
3241 // table entries will have ar_text and ar_flags fields still.
3243 // In the future, we may keep revisions and mark them with
3244 // the rev_deleted field, which is reserved for this purpose.
3245 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3247 'ar_namespace' => 'page_namespace',
3248 'ar_title' => 'page_title',
3249 'ar_comment' => 'rev_comment',
3250 'ar_user' => 'rev_user',
3251 'ar_user_text' => 'rev_user_text',
3252 'ar_timestamp' => 'rev_timestamp',
3253 'ar_minor_edit' => 'rev_minor_edit',
3254 'ar_rev_id' => 'rev_id',
3255 'ar_text_id' => 'rev_text_id',
3256 'ar_text' => '\'\'', // Be explicit to appease
3257 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3258 'ar_len' => 'rev_len',
3259 'ar_page_id' => 'page_id',
3260 'ar_deleted' => $bitfield
3263 'page_id = rev_page'
3267 # Delete restrictions for it
3268 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3270 # Now that it's safely backed up, delete it
3271 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3272 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3279 # Fix category table counts
3281 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3283 foreach ( $res as $row ) {
3284 $cats [] = $row->cl_to
;
3287 $this->updateCategoryCounts( array(), $cats );
3289 # If using cascading deletes, we can skip some explicit deletes
3290 if ( !$dbw->cascadingDeletes() ) {
3291 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3293 if ( $wgUseTrackbacks )
3294 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3296 # Delete outgoing links
3297 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3298 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3299 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3300 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3301 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3302 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3303 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3306 # If using cleanup triggers, we can skip some manual deletes
3307 if ( !$dbw->cleanupTriggers() ) {
3308 # Clean up recentchanges entries...
3309 $dbw->delete( 'recentchanges',
3310 array( 'rc_type != ' . RC_LOG
,
3311 'rc_namespace' => $this->mTitle
->getNamespace(),
3312 'rc_title' => $this->mTitle
->getDBkey() ),
3314 $dbw->delete( 'recentchanges',
3315 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3320 Article
::onArticleDelete( $this->mTitle
);
3322 # Clear the cached article id so the interface doesn't act like we exist
3323 $this->mTitle
->resetArticleID( 0 );
3325 # Log the deletion, if the page was suppressed, log it at Oversight instead
3326 $logtype = $suppress ?
'suppress' : 'delete';
3327 $log = new LogPage( $logtype );
3329 # Make sure logging got through
3330 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3340 * Roll back the most recent consecutive set of edits to a page
3341 * from the same user; fails if there are no eligible edits to
3342 * roll back to, e.g. user is the sole contributor. This function
3343 * performs permissions checks on $wgUser, then calls commitRollback()
3344 * to do the dirty work
3346 * @param $fromP String: Name of the user whose edits to rollback.
3347 * @param $summary String: Custom summary. Set to default summary if empty.
3348 * @param $token String: Rollback token.
3349 * @param $bot Boolean: If true, mark all reverted edits as bot.
3351 * @param $resultDetails Array: contains result-specific array of additional values
3352 * 'alreadyrolled' : 'current' (rev)
3353 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3355 * @return array of errors, each error formatted as
3356 * array(messagekey, param1, param2, ...).
3357 * On success, the array is empty. This array can also be passed to
3358 * OutputPage::showPermissionsErrorPage().
3360 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3363 $resultDetails = null;
3366 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3367 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3368 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3370 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3371 $errors[] = array( 'sessionfailure' );
3374 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3375 $errors[] = array( 'actionthrottledtext' );
3378 # If there were errors, bail out now
3379 if ( !empty( $errors ) ) {
3383 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3387 * Backend implementation of doRollback(), please refer there for parameter
3388 * and return value documentation
3390 * NOTE: This function does NOT check ANY permissions, it just commits the
3391 * rollback to the DB Therefore, you should only call this function direct-
3392 * ly if you want to use custom permissions checks. If you don't, use
3393 * doRollback() instead.
3395 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3396 global $wgUseRCPatrol, $wgUser, $wgLang;
3398 $dbw = wfGetDB( DB_MASTER
);
3400 if ( wfReadOnly() ) {
3401 return array( array( 'readonlytext' ) );
3404 # Get the last editor
3405 $current = Revision
::newFromTitle( $this->mTitle
);
3406 if ( is_null( $current ) ) {
3407 # Something wrong... no page?
3408 return array( array( 'notanarticle' ) );
3411 $from = str_replace( '_', ' ', $fromP );
3412 # User name given should match up with the top revision.
3413 # If the user was deleted then $from should be empty.
3414 if ( $from != $current->getUserText() ) {
3415 $resultDetails = array( 'current' => $current );
3416 return array( array( 'alreadyrolled',
3417 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3418 htmlspecialchars( $fromP ),
3419 htmlspecialchars( $current->getUserText() )
3423 # Get the last edit not by this guy...
3424 # Note: these may not be public values
3425 $user = intval( $current->getRawUser() );
3426 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3427 $s = $dbw->selectRow( 'revision',
3428 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3429 array( 'rev_page' => $current->getPage(),
3430 "rev_user != {$user} OR rev_user_text != {$user_text}"
3432 array( 'USE INDEX' => 'page_timestamp',
3433 'ORDER BY' => 'rev_timestamp DESC' )
3435 if ( $s === false ) {
3436 # No one else ever edited this page
3437 return array( array( 'cantrollback' ) );
3438 } else if ( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
3439 # Only admins can see this text
3440 return array( array( 'notvisiblerev' ) );
3444 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3445 # Mark all reverted edits as bot
3449 if ( $wgUseRCPatrol ) {
3450 # Mark all reverted edits as patrolled
3451 $set['rc_patrolled'] = 1;
3454 if ( count( $set ) ) {
3455 $dbw->update( 'recentchanges', $set,
3457 'rc_cur_id' => $current->getPage(),
3458 'rc_user_text' => $current->getUserText(),
3459 "rc_timestamp > '{$s->rev_timestamp}'",
3464 # Generate the edit summary if necessary
3465 $target = Revision
::newFromId( $s->rev_id
);
3466 if ( empty( $summary ) ) {
3467 if ( $from == '' ) { // no public user name
3468 $summary = wfMsgForContent( 'revertpage-nouser' );
3470 $summary = wfMsgForContent( 'revertpage' );
3474 # Allow the custom summary to use the same args as the default message
3476 $target->getUserText(), $from, $s->rev_id
,
3477 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3478 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3480 $summary = wfMsgReplaceArgs( $summary, $args );
3483 $flags = EDIT_UPDATE
;
3485 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3486 $flags |
= EDIT_MINOR
;
3489 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) ||
$wgUser->isAllowed( 'bot' ) ) ) {
3490 $flags |
= EDIT_FORCE_BOT
;
3493 # Actually store the edit
3494 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3495 if ( !empty( $status->value
['revision'] ) ) {
3496 $revId = $status->value
['revision']->getId();
3501 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3503 $resultDetails = array(
3504 'summary' => $summary,
3505 'current' => $current,
3506 'target' => $target,
3514 * User interface for rollback operations
3516 public function rollback() {
3517 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3521 $result = $this->doRollback(
3522 $wgRequest->getVal( 'from' ),
3523 $wgRequest->getText( 'summary' ),
3524 $wgRequest->getVal( 'token' ),
3525 $wgRequest->getBool( 'bot' ),
3529 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3530 $wgOut->rateLimited();
3534 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3535 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3536 $errArray = $result[0];
3537 $errMsg = array_shift( $errArray );
3538 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3540 if ( isset( $details['current'] ) ) {
3541 $current = $details['current'];
3543 if ( $current->getComment() != '' ) {
3544 $wgOut->addWikiMsgArray( 'editcomment', array(
3545 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3552 # Display permissions errors before read-only message -- there's no
3553 # point in misleading the user into thinking the inability to rollback
3554 # is only temporary.
3555 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3556 # array_diff is completely broken for arrays of arrays, sigh.
3557 # Remove any 'readonlytext' error manually.
3559 foreach ( $result as $error ) {
3560 if ( $error != array( 'readonlytext' ) ) {
3564 $wgOut->showPermissionsErrorPage( $out );
3569 if ( $result == array( array( 'readonlytext' ) ) ) {
3570 $wgOut->readOnlyPage();
3575 $current = $details['current'];
3576 $target = $details['target'];
3577 $newId = $details['newid'];
3578 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3579 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3581 if ( $current->getUserText() === '' ) {
3582 $old = wfMsg( 'rev-deleted-user' );
3584 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3585 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3588 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3589 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3590 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3591 $wgOut->returnToMain( false, $this->mTitle
);
3593 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3594 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3595 $de->showDiff( '', '' );
3600 * Do standard deferred updates after page view
3602 public function viewUpdates() {
3603 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3604 if ( wfReadOnly() ) {
3608 # Don't update page view counters on views from bot users (bug 14044)
3609 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3610 Article
::incViewCount( $this->getID() );
3611 $u = new SiteStatsUpdate( 1, 0, 0 );
3612 array_push( $wgDeferredUpdateList, $u );
3615 # Update newtalk / watchlist notification status
3616 $wgUser->clearNotification( $this->mTitle
);
3620 * Prepare text which is about to be saved.
3621 * Returns a stdclass with source, pst and output members
3623 public function prepareTextForEdit( $text, $revid = null ) {
3624 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3626 return $this->mPreparedEdit
;
3631 $edit = (object)array();
3632 $edit->revid
= $revid;
3633 $edit->newText
= $text;
3634 $edit->pst
= $this->preSaveTransform( $text );
3635 $options = $this->getParserOptions();
3636 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
3637 $edit->oldText
= $this->getContent();
3639 $this->mPreparedEdit
= $edit;
3645 * Do standard deferred updates after page edit.
3646 * Update links tables, site stats, search index and message cache.
3647 * Purges pages that include this page if the text was changed here.
3648 * Every 100th edit, prune the recent changes table.
3651 * @param $text New text of the article
3652 * @param $summary Edit summary
3653 * @param $minoredit Minor edit
3654 * @param $timestamp_of_pagechange Timestamp associated with the page change
3655 * @param $newid rev_id value of the new revision
3656 * @param $changed Whether or not the content actually changed
3658 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3659 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3661 wfProfileIn( __METHOD__
);
3664 # Be careful not to double-PST: $text is usually already PST-ed once
3665 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3666 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3667 $editInfo = $this->prepareTextForEdit( $text, $newid );
3669 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3670 $editInfo = $this->mPreparedEdit
;
3673 # Save it to the parser cache
3674 if ( $wgEnableParserCache ) {
3675 $popts = $this->getParserOptions();
3676 $parserCache = ParserCache
::singleton();
3677 $parserCache->save( $editInfo->output
, $this, $popts );
3680 # Update the links tables
3681 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3684 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3686 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3687 if ( 0 == mt_rand( 0, 99 ) ) {
3688 // Flush old entries from the `recentchanges` table; we do this on
3689 // random requests so as to avoid an increase in writes for no good reason
3692 $dbw = wfGetDB( DB_MASTER
);
3693 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3694 $recentchanges = $dbw->tableName( 'recentchanges' );
3695 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3697 $dbw->query( $sql );
3701 $id = $this->getID();
3702 $title = $this->mTitle
->getPrefixedDBkey();
3703 $shortTitle = $this->mTitle
->getDBkey();
3706 wfProfileOut( __METHOD__
);
3710 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3711 array_push( $wgDeferredUpdateList, $u );
3712 $u = new SearchUpdate( $id, $title, $text );
3713 array_push( $wgDeferredUpdateList, $u );
3715 # If this is another user's talk page, update newtalk
3716 # Don't do this if $changed = false otherwise some idiot can null-edit a
3717 # load of user talk pages and piss people off, nor if it's a minor edit
3718 # by a properly-flagged bot.
3719 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3720 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3722 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3723 $other = User
::newFromName( $shortTitle, false );
3725 wfDebug( __METHOD__
. ": invalid username\n" );
3726 } elseif ( User
::isIP( $shortTitle ) ) {
3727 // An anonymous user
3728 $other->setNewtalk( true );
3729 } elseif ( $other->isLoggedIn() ) {
3730 $other->setNewtalk( true );
3732 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3737 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3738 $wgMessageCache->replace( $shortTitle, $text );
3741 wfProfileOut( __METHOD__
);
3745 * Perform article updates on a special page creation.
3747 * @param $rev Revision object
3749 * @todo This is a shitty interface function. Kill it and replace the
3750 * other shitty functions like editUpdates and such so it's not needed
3753 public function createUpdates( $rev ) {
3754 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3755 $this->mTotalAdjustment
= 1;
3756 $this->editUpdates( $rev->getText(), $rev->getComment(),
3757 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3761 * Generate the navigation links when browsing through an article revisions
3762 * It shows the information as:
3763 * Revision as of \<date\>; view current revision
3764 * \<- Previous version | Next Version -\>
3766 * @param $oldid String: revision ID of this article revision
3768 public function setOldSubtitle( $oldid = 0 ) {
3769 global $wgLang, $wgOut, $wgUser, $wgRequest;
3771 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3775 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3777 # Cascade unhide param in links for easy deletion browsing
3778 $extraParams = array();
3779 if ( $wgRequest->getVal( 'unhide' ) ) {
3780 $extraParams['unhide'] = 1;
3783 $revision = Revision
::newFromId( $oldid );
3785 $current = ( $oldid == $this->mLatest
);
3786 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3787 $tddate = $wgLang->date( $this->mTimestamp
, true );
3788 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3789 $sk = $wgUser->getSkin();
3791 ?
wfMsgHtml( 'currentrevisionlink' )
3794 wfMsgHtml( 'currentrevisionlink' ),
3797 array( 'known', 'noclasses' )
3800 ?
wfMsgHtml( 'diff' )
3803 wfMsgHtml( 'diff' ),
3809 array( 'known', 'noclasses' )
3811 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3815 wfMsgHtml( 'previousrevision' ),
3818 'direction' => 'prev',
3821 array( 'known', 'noclasses' )
3823 : wfMsgHtml( 'previousrevision' );
3827 wfMsgHtml( 'diff' ),
3833 array( 'known', 'noclasses' )
3835 : wfMsgHtml( 'diff' );
3836 $nextlink = $current
3837 ?
wfMsgHtml( 'nextrevision' )
3840 wfMsgHtml( 'nextrevision' ),
3843 'direction' => 'next',
3846 array( 'known', 'noclasses' )
3848 $nextdiff = $current
3849 ?
wfMsgHtml( 'diff' )
3852 wfMsgHtml( 'diff' ),
3858 array( 'known', 'noclasses' )
3863 // User can delete revisions or view deleted revisions...
3864 $canHide = $wgUser->isAllowed( 'deleterevision' );
3865 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3866 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3867 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3870 'type' => 'revision',
3871 'target' => $this->mTitle
->getPrefixedDbkey(),
3874 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3879 # Show user links if allowed to see them. If hidden, then show them only if requested...
3880 $userlinks = $sk->revUserTools( $revision, !$unhide );
3882 $m = wfMsg( 'revision-info-current' );
3883 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3884 ?
'revision-info-current'
3887 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3890 array( 'parseinline', 'replaceafter' ),
3896 $revision->getUser()
3899 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3900 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3902 $wgOut->setSubtitle( $r );
3906 * This function is called right before saving the wikitext,
3907 * so we can do things like signatures and links-in-context.
3909 * @param $text String article contents
3910 * @return string article contents with altered wikitext markup (signatures
3911 * converted, {{subst:}}, templates, etc.)
3913 public function preSaveTransform( $text ) {
3914 global $wgParser, $wgUser;
3916 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3919 /* Caching functions */
3922 * checkLastModified returns true if it has taken care of all
3923 * output to the client that is necessary for this request.
3924 * (that is, it has sent a cached version of the page)
3926 * @return boolean true if cached version send, false otherwise
3928 protected function tryFileCache() {
3929 static $called = false;
3932 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3937 if ( $this->isFileCacheable() ) {
3938 $cache = new HTMLFileCache( $this->mTitle
);
3939 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3940 wfDebug( "Article::tryFileCache(): about to load file\n" );
3941 $cache->loadFromFileCache();
3944 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3945 ob_start( array( &$cache, 'saveToFileCache' ) );
3948 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3955 * Check if the page can be cached
3958 public function isFileCacheable() {
3961 if ( HTMLFileCache
::useFileCache() ) {
3962 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3963 // Extension may have reason to disable file caching on some pages.
3965 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3973 * Loads page_touched and returns a value indicating if it should be used
3974 * @return boolean true if not a redirect
3976 public function checkTouched() {
3977 if ( !$this->mDataLoaded
) {
3978 $this->loadPageData();
3981 return !$this->mIsRedirect
;
3985 * Get the page_touched field
3986 * @return string containing GMT timestamp
3988 public function getTouched() {
3989 # Ensure that page data has been loaded
3990 if ( !$this->mDataLoaded
) {
3991 $this->loadPageData();
3994 return $this->mTouched
;
3998 * Get the page_latest field
3999 * @return integer rev_id of current revision
4001 public function getLatest() {
4002 if ( !$this->mDataLoaded
) {
4003 $this->loadPageData();
4006 return (int)$this->mLatest
;
4010 * Edit an article without doing all that other stuff
4011 * The article must already exist; link tables etc
4012 * are not updated, caches are not flushed.
4014 * @param $text String: text submitted
4015 * @param $comment String: comment submitted
4016 * @param $minor Boolean: whereas it's a minor modification
4018 public function quickEdit( $text, $comment = '', $minor = 0 ) {
4019 wfProfileIn( __METHOD__
);
4021 $dbw = wfGetDB( DB_MASTER
);
4022 $revision = new Revision( array(
4023 'page' => $this->getId(),
4025 'comment' => $comment,
4026 'minor_edit' => $minor ?
1 : 0,
4028 $revision->insertOn( $dbw );
4029 $this->updateRevisionOn( $dbw, $revision );
4031 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
4033 wfProfileOut( __METHOD__
);
4037 * Used to increment the view counter
4039 * @param $id Integer: article id
4041 public static function incViewCount( $id ) {
4042 $id = intval( $id );
4044 global $wgHitcounterUpdateFreq;
4046 $dbw = wfGetDB( DB_MASTER
);
4047 $pageTable = $dbw->tableName( 'page' );
4048 $hitcounterTable = $dbw->tableName( 'hitcounter' );
4049 $acchitsTable = $dbw->tableName( 'acchits' );
4051 if ( $wgHitcounterUpdateFreq <= 1 ) {
4052 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
4057 # Not important enough to warrant an error page in case of failure
4058 $oldignore = $dbw->ignoreErrors( true );
4060 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
4062 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 +
1 );
4063 if ( ( rand() %
$checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
4064 # Most of the time (or on SQL errors), skip row count check
4065 $dbw->ignoreErrors( $oldignore );
4070 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
4071 $row = $dbw->fetchObject( $res );
4072 $rown = intval( $row->n
);
4074 if ( $rown >= $wgHitcounterUpdateFreq ) {
4075 wfProfileIn( 'Article::incViewCount-collect' );
4076 $old_user_abort = ignore_user_abort( true );
4078 $dbType = $dbw->getType();
4079 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__
, false );
4080 $tabletype = $dbType == 'mysql' ?
"ENGINE=HEAP " : '';
4081 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
4082 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
4083 'GROUP BY hc_id', __METHOD__
);
4084 $dbw->delete( 'hitcounter', '*', __METHOD__
);
4085 $dbw->unlockTables( __METHOD__
);
4087 if ( $dbType == 'mysql' ) {
4088 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
4089 'WHERE page_id = hc_id', __METHOD__
);
4091 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
4092 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__
);
4094 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__
);
4096 ignore_user_abort( $old_user_abort );
4097 wfProfileOut( 'Article::incViewCount-collect' );
4100 $dbw->ignoreErrors( $oldignore );
4104 * The onArticle*() functions are supposed to be a kind of hooks
4105 * which should be called whenever any of the specified actions
4108 * This is a good place to put code to clear caches, for instance.
4110 * This is called on page move and undelete, as well as edit
4112 * @param $title a title object
4114 public static function onArticleCreate( $title ) {
4115 # Update existence markers on article/talk tabs...
4116 if ( $title->isTalkPage() ) {
4117 $other = $title->getSubjectPage();
4119 $other = $title->getTalkPage();
4122 $other->invalidateCache();
4123 $other->purgeSquid();
4125 $title->touchLinks();
4126 $title->purgeSquid();
4127 $title->deleteTitleProtection();
4131 * Clears caches when article is deleted
4133 public static function onArticleDelete( $title ) {
4134 global $wgMessageCache;
4136 # Update existence markers on article/talk tabs...
4137 if ( $title->isTalkPage() ) {
4138 $other = $title->getSubjectPage();
4140 $other = $title->getTalkPage();
4143 $other->invalidateCache();
4144 $other->purgeSquid();
4146 $title->touchLinks();
4147 $title->purgeSquid();
4150 HTMLFileCache
::clearFileCache( $title );
4153 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
4154 $wgMessageCache->replace( $title->getDBkey(), false );
4158 if ( $title->getNamespace() == NS_FILE
) {
4159 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4160 $update->doUpdate();
4164 if ( $title->getNamespace() == NS_USER_TALK
) {
4165 $user = User
::newFromName( $title->getText(), false );
4166 $user->setNewtalk( false );
4170 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4174 * Purge caches on page update etc
4176 * @param $title Title object
4177 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4179 public static function onArticleEdit( $title ) {
4180 global $wgDeferredUpdateList;
4182 // Invalidate caches of articles which include this page
4183 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4185 // Invalidate the caches of all pages which redirect here
4186 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4188 # Purge squid for this page only
4189 $title->purgeSquid();
4191 # Clear file cache for this page only
4192 HTMLFileCache
::clearFileCache( $title );
4198 * Overriden by ImagePage class, only present here to avoid a fatal error
4199 * Called for ?action=revert
4201 public function revert() {
4204 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4208 * Info about this page
4209 * Called for ?action=info when $wgAllowPageInfo is on.
4211 public function info() {
4212 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4214 if ( !$wgAllowPageInfo ) {
4215 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4219 $page = $this->mTitle
->getSubjectPage();
4221 $wgOut->setPagetitle( $page->getPrefixedText() );
4222 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4223 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4225 if ( !$this->mTitle
->exists() ) {
4226 $wgOut->addHTML( '<div class="noarticletext">' );
4227 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
4228 // This doesn't quite make sense; the user is asking for
4229 // information about the _page_, not the message... -- RC
4230 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
4232 $msg = $wgUser->isLoggedIn()
4234 : 'noarticletextanon';
4235 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4238 $wgOut->addHTML( '</div>' );
4240 $dbr = wfGetDB( DB_SLAVE
);
4242 'wl_title' => $page->getDBkey(),
4243 'wl_namespace' => $page->getNamespace() );
4244 $numwatchers = $dbr->selectField(
4249 $this->getSelectOptions() );
4251 $pageInfo = $this->pageCountInfo( $page );
4252 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4254 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4255 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4258 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4261 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4264 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4267 $wgOut->addHTML( '</ul>' );
4272 * Return the total number of edits and number of unique editors
4273 * on a given page. If page does not exist, returns false.
4275 * @param $title Title object
4276 * @return mixed array or boolean false
4278 public function pageCountInfo( $title ) {
4279 $id = $title->getArticleId();
4285 $dbr = wfGetDB( DB_SLAVE
);
4286 $rev_clause = array( 'rev_page' => $id );
4287 $edits = $dbr->selectField(
4292 $this->getSelectOptions()
4294 $authors = $dbr->selectField(
4296 'COUNT(DISTINCT rev_user_text)',
4299 $this->getSelectOptions()
4302 return array( 'edits' => $edits, 'authors' => $authors );
4306 * Return a list of templates used by this article.
4307 * Uses the templatelinks table
4309 * @return Array of Title objects
4311 public function getUsedTemplates() {
4313 $id = $this->mTitle
->getArticleID();
4319 $dbr = wfGetDB( DB_SLAVE
);
4320 $res = $dbr->select( array( 'templatelinks' ),
4321 array( 'tl_namespace', 'tl_title' ),
4322 array( 'tl_from' => $id ),
4325 if ( $res !== false ) {
4326 foreach ( $res as $row ) {
4327 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4331 $dbr->freeResult( $res );
4337 * Returns a list of hidden categories this page is a member of.
4338 * Uses the page_props and categorylinks tables.
4340 * @return Array of Title objects
4342 public function getHiddenCategories() {
4344 $id = $this->mTitle
->getArticleID();
4350 $dbr = wfGetDB( DB_SLAVE
);
4351 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4353 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4354 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4357 if ( $res !== false ) {
4358 foreach ( $res as $row ) {
4359 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4363 $dbr->freeResult( $res );
4369 * Return an applicable autosummary if one exists for the given edit.
4370 * @param $oldtext String: the previous text of the page.
4371 * @param $newtext String: The submitted text of the page.
4372 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4373 * @return string An appropriate autosummary, or an empty string.
4375 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4376 # Decide what kind of autosummary is needed.
4378 # Redirect autosummaries
4379 $ot = Title
::newFromRedirect( $oldtext );
4380 $rt = Title
::newFromRedirect( $newtext );
4382 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4383 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4386 # New page autosummaries
4387 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4388 # If they're making a new article, give its text, truncated, in the summary.
4391 $truncatedtext = $wgContLang->truncate(
4392 str_replace( "\n", ' ', $newtext ),
4393 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4395 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4398 # Blanking autosummaries
4399 if ( $oldtext != '' && $newtext == '' ) {
4400 return wfMsgForContent( 'autosumm-blank' );
4401 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4402 # Removing more than 90% of the article
4405 $truncatedtext = $wgContLang->truncate(
4407 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4409 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4412 # If we reach this point, there's no applicable autosummary for our case, so our
4413 # autosummary is empty.
4418 * Add the primary page-view wikitext to the output buffer
4419 * Saves the text into the parser cache if possible.
4420 * Updates templatelinks if it is out of date.
4422 * @param $text String
4423 * @param $cache Boolean
4424 * @param $parserOptions mixed ParserOptions object, or boolean false
4426 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4429 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4430 $wgOut->addParserOutput( $this->mParserOutput
);
4434 * This does all the heavy lifting for outputWikitext, except it returns the parser
4435 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4436 * say, embedding thread pages within a discussion system (LiquidThreads)
4438 * @param $text string
4439 * @param $cache boolean
4440 * @param $parserOptions parsing options, defaults to false
4441 * @return string containing parsed output
4443 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4444 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4446 if ( !$parserOptions ) {
4447 $parserOptions = $this->getParserOptions();
4451 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4452 $parserOptions, true, true, $this->getRevIdFetched() );
4457 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4458 $this->mTitle
->getPrefixedDBkey() ) );
4461 if ( $wgEnableParserCache && $cache && $this && !$this->mParserOutput
->isCacheable() ) {
4462 $parserCache = ParserCache
::singleton();
4463 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4466 // Make sure file cache is not used on uncacheable content.
4467 // Output that has magic words in it can still use the parser cache
4468 // (if enabled), though it will generally expire sooner.
4469 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4470 $wgUseFileCache = false;
4473 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4475 return $this->mParserOutput
;
4479 * Get parser options suitable for rendering the primary article wikitext
4480 * @return mixed ParserOptions object or boolean false
4482 public function getParserOptions() {
4485 if ( !$this->mParserOptions
) {
4486 $this->mParserOptions
= new ParserOptions( $wgUser );
4487 $this->mParserOptions
->setTidy( true );
4488 $this->mParserOptions
->enableLimitReport();
4491 return $this->mParserOptions
;
4495 * Updates cascading protections
4497 * @param $parserOutput mixed ParserOptions object, or boolean false
4500 protected function doCascadeProtectionUpdates( $parserOutput ) {
4501 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4505 // templatelinks table may have become out of sync,
4506 // especially if using variable-based transclusions.
4507 // For paranoia, check if things have changed and if
4508 // so apply updates to the database. This will ensure
4509 // that cascaded protections apply as soon as the changes
4512 # Get templates from templatelinks
4513 $id = $this->mTitle
->getArticleID();
4515 $tlTemplates = array();
4517 $dbr = wfGetDB( DB_SLAVE
);
4518 $res = $dbr->select( array( 'templatelinks' ),
4519 array( 'tl_namespace', 'tl_title' ),
4520 array( 'tl_from' => $id ),
4526 foreach ( $res as $row ) {
4527 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4530 # Get templates from parser output.
4531 $poTemplates = array();
4532 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4533 foreach ( $templates as $dbk => $id ) {
4534 $poTemplates["$ns:$dbk"] = true;
4539 # Note that we simulate array_diff_key in PHP <5.0.x
4540 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4542 if ( count( $templates_diff ) > 0 ) {
4543 # Whee, link updates time.
4544 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4550 * Update all the appropriate counts in the category table, given that
4551 * we've added the categories $added and deleted the categories $deleted.
4553 * @param $added array The names of categories that were added
4554 * @param $deleted array The names of categories that were deleted
4556 public function updateCategoryCounts( $added, $deleted ) {
4557 $ns = $this->mTitle
->getNamespace();
4558 $dbw = wfGetDB( DB_MASTER
);
4560 # First make sure the rows exist. If one of the "deleted" ones didn't
4561 # exist, we might legitimately not create it, but it's simpler to just
4562 # create it and then give it a negative value, since the value is bogus
4565 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4566 $insertCats = array_merge( $added, $deleted );
4567 if ( !$insertCats ) {
4568 # Okay, nothing to do
4572 $insertRows = array();
4574 foreach ( $insertCats as $cat ) {
4575 $insertRows[] = array(
4576 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4580 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4582 $addFields = array( 'cat_pages = cat_pages + 1' );
4583 $removeFields = array( 'cat_pages = cat_pages - 1' );
4585 if ( $ns == NS_CATEGORY
) {
4586 $addFields[] = 'cat_subcats = cat_subcats + 1';
4587 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4588 } elseif ( $ns == NS_FILE
) {
4589 $addFields[] = 'cat_files = cat_files + 1';
4590 $removeFields[] = 'cat_files = cat_files - 1';
4597 array( 'cat_title' => $added ),
4606 array( 'cat_title' => $deleted ),
4613 * Lightweight method to get the parser output for a page, checking the parser cache
4614 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4615 * consider, so it's not appropriate to use there.
4617 * @param $oldid mixed integer Revision ID or null
4619 public function getParserOutput( $oldid = null ) {
4620 global $wgEnableParserCache, $wgUser, $wgOut;
4622 // Should the parser cache be used?
4623 $useParserCache = $wgEnableParserCache &&
4624 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4628 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4630 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4631 wfIncrStats( 'pcache_miss_stub' );
4634 $parserOutput = false;
4635 if ( $useParserCache ) {
4636 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4639 if ( $parserOutput === false ) {
4640 // Cache miss; parse and output it.
4641 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4643 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4645 return $parserOutput;