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 $mDataLoaded = false; // !<
25 var $mForUpdate = false; // !<
26 var $mGoodAdjustment = 0; // !<
27 var $mIsRedirect = false; // !<
28 var $mLatest = false; // !<
29 var $mMinorEdit; // !<
31 var $mPreparedEdit = false; // !< Title object if set
32 var $mRedirectedFrom = null; // !< Title object if set
33 var $mRedirectTarget = null; // !< Title object if set
34 var $mRedirectUrl = false; // !<
35 var $mRevIdFetched = 0; // !<
36 var $mRevision = null; // !< Revision object if set
37 var $mTimestamp = ''; // !<
38 var $mTitle; // !< Title object
39 var $mTotalAdjustment = 0; // !<
40 var $mTouched = '19700101000000'; // !<
41 var $mUser = -1; // !< Not loaded
42 var $mUserText = ''; // !< username from Revision if set
43 var $mParserOptions; // !< ParserOptions object for $wgUser articles
44 var $mParserOutput; // !< ParserCache object if set
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
52 public function __construct( Title
$title, $oldId = null ) {
53 // FIXME: does the reference play any role here?
54 $this->mTitle
=& $title;
55 $this->mOldId
= $oldId;
59 * Constructor from an page id
60 * @param $id Int 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
->isRedirect() ) {
90 if ( $this->mRedirectTarget
!== null ) {
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', 'rd_fragment', 'rd_interwiki' ),
98 array( 'rd_from' => $this->getID() ),
102 // rd_fragment and rd_interwiki were added later, populate them if empty
103 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
104 return $this->mRedirectTarget
= Title
::makeTitle(
105 $row->rd_namespace
, $row->rd_title
,
106 $row->rd_fragment
, $row->rd_interwiki
);
109 # This page doesn't have an entry in the redirect table
110 return $this->mRedirectTarget
= $this->insertRedirect();
114 * Insert an entry for this page into the redirect table.
116 * Don't call this function directly unless you know what you're doing.
117 * @return Title object or null if not a redirect
119 public function insertRedirect() {
120 // recurse through to only get the final target
121 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
125 $this->insertRedirectEntry( $retval );
130 * Insert or update the redirect table entry for this page to indicate
131 * it redirects to $rt .
132 * @param $rt Title redirect target
134 public function insertRedirectEntry( $rt ) {
135 $dbw = wfGetDB( DB_MASTER
);
136 $dbw->replace( 'redirect', array( 'rd_from' ),
138 'rd_from' => $this->getID(),
139 'rd_namespace' => $rt->getNamespace(),
140 'rd_title' => $rt->getDBkey(),
141 'rd_fragment' => $rt->getFragment(),
142 'rd_interwiki' => $rt->getInterwiki(),
149 * Get the Title object or URL this page redirects to
151 * @return mixed false, Title of in-wiki target, or string with URL
153 public function followRedirect() {
154 return $this->getRedirectURL( $this->getRedirectTarget() );
158 * Get the Title object this text redirects to
160 * @param $text string article content containing redirect info
161 * @return mixed false, Title of in-wiki target, or string with URL
162 * @deprecated @since 1.17
164 public function followRedirectText( $text ) {
165 // recurse through to only get the final target
166 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
170 * Get the Title object or URL to use for a redirect. We use Title
171 * objects for same-wiki, non-special redirects and URLs for everything
173 * @param $rt Title Redirect target
174 * @return mixed false, Title object of local target, or string with URL
176 public function getRedirectURL( $rt ) {
178 if ( $rt->getInterwiki() != '' ) {
179 if ( $rt->isLocal() ) {
180 // Offsite wikis need an HTTP redirect.
182 // This can be hard to reverse and may produce loops,
183 // so they may be disabled in the site configuration.
184 $source = $this->mTitle
->getFullURL( 'redirect=no' );
185 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
188 if ( $rt->getNamespace() == NS_SPECIAL
) {
189 // Gotta handle redirects to special pages differently:
190 // Fill the HTTP response "Location" header and ignore
191 // the rest of the page we're on.
193 // This can be hard to reverse, so they may be disabled.
194 if ( $rt->isSpecial( 'Userlogout' ) ) {
197 return $rt->getFullURL();
205 // No or invalid redirect
210 * Get the title object of the article
211 * @return Title object of this page
213 public function getTitle() {
214 return $this->mTitle
;
219 * FIXME: shouldn't this be public?
222 public function clear() {
223 $this->mDataLoaded
= false;
224 $this->mContentLoaded
= false;
226 $this->mUser
= $this->mCounter
= -1; # Not loaded
227 $this->mRedirectedFrom
= null; # Title object if set
228 $this->mRedirectTarget
= null; # Title object if set
230 $this->mTimestamp
= $this->mComment
= '';
231 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
232 $this->mTouched
= '19700101000000';
233 $this->mForUpdate
= false;
234 $this->mIsRedirect
= false;
235 $this->mRevIdFetched
= 0;
236 $this->mRedirectUrl
= false;
237 $this->mLatest
= false;
238 $this->mPreparedEdit
= false;
242 * Note that getContent/loadContent do not follow redirects anymore.
243 * If you need to fetch redirectable content easily, try
244 * the shortcut in Article::followRedirect()
246 * This function has side effects! Do not use this function if you
247 * only want the real revision text if any.
249 * @return Return the text of this revision
251 public function getContent() {
252 global $wgUser, $wgContLang;
254 wfProfileIn( __METHOD__
);
256 if ( $this->getID() === 0 ) {
257 # If this is a MediaWiki:x message, then load the messages
258 # and return the message value for x.
259 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
260 $text = $this->getDefaultMessageText();
261 if ( $text === false ) {
265 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
267 wfProfileOut( __METHOD__
);
271 $this->loadContent();
272 wfProfileOut( __METHOD__
);
274 return $this->mContent
;
279 * Get the default message text or false if the message doesn't exist
281 * @return String or false
283 public function getDefaultMessageText() {
286 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
) { // Just in case
290 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
291 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
293 if ( $message->exists() ) {
294 return $message->plain();
301 * Get the text of the current revision. No side-effects...
303 * @return Return the text of the current revision
305 public function getRawText() {
306 // Check process cache for current revision
307 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
308 return $this->mContent
;
311 $rev = Revision
::newFromTitle( $this->mTitle
);
312 $text = $rev ?
$rev->getRawText() : false;
318 * This function returns the text of a section, specified by a number ($section).
319 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
320 * the first section before any such heading (section 0).
322 * If a section contains subsections, these are also returned.
324 * @param $text String: text to look in
325 * @param $section Integer: section number
326 * @return string text of the requested section
329 public function getSection( $text, $section ) {
331 return $wgParser->getSection( $text, $section );
335 * Get the text that needs to be saved in order to undo all revisions
336 * between $undo and $undoafter. Revisions must belong to the same page,
337 * must exist and must not be deleted
338 * @param $undo Revision
339 * @param $undoafter Revision Must be an earlier revision than $undo
340 * @return mixed string on success, false on failure
342 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
343 $currentRev = Revision
::newFromTitle( $this->mTitle
);
344 if ( !$currentRev ) {
345 return false; // no page
347 $undo_text = $undo->getText();
348 $undoafter_text = $undoafter->getText();
349 $cur_text = $currentRev->getText();
351 if ( $cur_text == $undo_text ) {
352 # No use doing a merge if it's just a straight revert.
353 return $undoafter_text;
358 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
366 * @return int The oldid of the article that is to be shown, 0 for the
369 public function getOldID() {
370 if ( is_null( $this->mOldId
) ) {
371 $this->mOldId
= $this->getOldIDFromRequest();
374 return $this->mOldId
;
378 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
380 * @return int The old id for the request
382 public function getOldIDFromRequest() {
385 $this->mRedirectUrl
= false;
387 $oldid = $wgRequest->getVal( 'oldid' );
389 if ( isset( $oldid ) ) {
390 $oldid = intval( $oldid );
391 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
392 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
396 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
398 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
399 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
414 * Load the revision (including text) into this object
416 function loadContent() {
417 if ( $this->mContentLoaded
) {
421 wfProfileIn( __METHOD__
);
423 $this->fetchContent( $this->getOldID() );
425 wfProfileOut( __METHOD__
);
429 * Fetch a page record with the given conditions
430 * @param $dbr Database object
431 * @param $conditions Array
432 * @return mixed Database result resource, or false on failure
434 protected function pageData( $dbr, $conditions ) {
449 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
451 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
453 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
459 * Fetch a page record matching the Title object's namespace and title
460 * using a sanitized title string
462 * @param $dbr Database object
463 * @param $title Title object
464 * @return mixed Database result resource, or false on failure
466 public function pageDataFromTitle( $dbr, $title ) {
467 return $this->pageData( $dbr, array(
468 'page_namespace' => $title->getNamespace(),
469 'page_title' => $title->getDBkey() ) );
473 * Fetch a page record matching the requested ID
475 * @param $dbr Database
478 protected function pageDataFromId( $dbr, $id ) {
479 return $this->pageData( $dbr, array( 'page_id' => $id ) );
483 * Set the general counter, title etc data loaded from
486 * @param $data Database row object or "fromdb"
488 public function loadPageData( $data = 'fromdb' ) {
489 if ( $data === 'fromdb' ) {
490 $dbr = wfGetDB( DB_SLAVE
);
491 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
494 $lc = LinkCache
::singleton();
497 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
499 $this->mTitle
->mArticleID
= intval( $data->page_id
);
501 # Old-fashioned restrictions
502 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
504 $this->mCounter
= intval( $data->page_counter
);
505 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
506 $this->mIsRedirect
= intval( $data->page_is_redirect
);
507 $this->mLatest
= intval( $data->page_latest
);
509 $lc->addBadLinkObj( $this->mTitle
);
510 $this->mTitle
->mArticleID
= 0;
513 $this->mDataLoaded
= true;
517 * Get text of an article from database
518 * Does *NOT* follow redirects.
520 * @param $oldid Int: 0 for whatever the latest revision is
521 * @return mixed string containing article contents, or false if null
523 function fetchContent( $oldid = 0 ) {
524 if ( $this->mContentLoaded
) {
525 return $this->mContent
;
528 # Pre-fill content with error message so that if something
529 # fails we'll have something telling us what we intended.
530 $t = $this->mTitle
->getPrefixedText();
531 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
532 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
535 $revision = Revision
::newFromId( $oldid );
536 if ( $revision === null ) {
537 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
541 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
542 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
545 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
549 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
550 $this->loadPageData( $data );
553 if ( !$this->mDataLoaded
) {
554 $this->loadPageData();
557 if ( $this->mLatest
=== false ) {
558 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
562 $revision = Revision
::newFromId( $this->mLatest
);
563 if ( $revision === null ) {
564 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
569 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
570 // We should instead work with the Revision object when we need it...
571 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
573 if ( $revision->getId() == $this->mLatest
) {
574 $this->setLastEdit( $revision );
577 $this->mRevIdFetched
= $revision->getId();
578 $this->mContentLoaded
= true;
579 $this->mRevision
=& $revision;
581 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
583 return $this->mContent
;
587 * Read/write accessor to select FOR UPDATE
589 * @param $x Mixed: FIXME
590 * @return mixed value of $x, or value stored in Article::mForUpdate
592 public function forUpdate( $x = null ) {
593 return wfSetVar( $this->mForUpdate
, $x );
597 * Get options for all SELECT statements
599 * @param $options Array: an optional options array which'll be appended to
601 * @return Array: options
603 protected function getSelectOptions( $options = '' ) {
604 if ( $this->mForUpdate
) {
605 if ( is_array( $options ) ) {
606 $options[] = 'FOR UPDATE';
608 $options = 'FOR UPDATE';
616 * @return int Page ID
618 public function getID() {
619 return $this->mTitle
->getArticleID();
623 * @return bool Whether or not the page exists in the database
625 public function exists() {
626 return $this->getId() > 0;
630 * Check if this page is something we're going to be showing
631 * some sort of sensible content for. If we return false, page
632 * views (plain action=view) will return an HTTP 404 response,
633 * so spiders and robots can know they're following a bad link.
637 public function hasViewableContent() {
638 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
642 * @return int The view count for the page
644 public function getCount() {
645 if ( -1 == $this->mCounter
) {
646 $id = $this->getID();
651 $dbr = wfGetDB( DB_SLAVE
);
652 $this->mCounter
= $dbr->selectField( 'page',
654 array( 'page_id' => $id ),
656 $this->getSelectOptions()
661 return $this->mCounter
;
665 * Determine whether a page would be suitable for being counted as an
666 * article in the site_stats table based on the title & its content
668 * @param $text String: text to analyze
671 public function isCountable( $text ) {
672 global $wgUseCommaCount;
674 $token = $wgUseCommaCount ?
',' : '[[';
676 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
680 * Tests if the article text represents a redirect
682 * @param $text mixed string containing article contents, or boolean
685 public function isRedirect( $text = false ) {
686 if ( $text === false ) {
687 if ( !$this->mDataLoaded
) {
688 $this->loadPageData();
691 return (bool)$this->mIsRedirect
;
693 return Title
::newFromRedirect( $text ) !== null;
698 * Returns true if the currently-referenced revision is the current edit
699 * to this page (and it exists).
702 public function isCurrent() {
703 # If no oldid, this is the current version.
704 if ( $this->getOldID() == 0 ) {
708 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
712 * Loads everything except the text
713 * This isn't necessary for all uses, so it's only done if needed.
715 protected function loadLastEdit() {
716 if ( -1 != $this->mUser
) {
720 # New or non-existent articles have no user information
721 $id = $this->getID();
726 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
727 if ( !is_null( $revision ) ) {
728 $this->setLastEdit( $revision );
733 * Set the latest revision
735 protected function setLastEdit( Revision
$revision ) {
736 $this->mLastRevision
= $revision;
737 $this->mUser
= $revision->getUser();
738 $this->mUserText
= $revision->getUserText();
739 $this->mTimestamp
= $revision->getTimestamp();
740 $this->mComment
= $revision->getComment();
741 $this->mMinorEdit
= $revision->isMinor();
745 * @return string GMT timestamp of last article revision
747 public function getTimestamp() {
748 // Check if the field has been filled by ParserCache::get()
749 if ( !$this->mTimestamp
) {
750 $this->loadLastEdit();
753 return wfTimestamp( TS_MW
, $this->mTimestamp
);
757 * @return int user ID for the user that made the last article revision
759 public function getUser() {
760 $this->loadLastEdit();
765 * @return string username of the user that made the last article revision
767 public function getUserText() {
768 $this->loadLastEdit();
769 return $this->mUserText
;
773 * @return string Comment stored for the last article revision
775 public function getComment() {
776 $this->loadLastEdit();
777 return $this->mComment
;
781 * Returns true if last revision was marked as "minor edit"
783 * @return boolean Minor edit indicator for the last article revision.
785 public function getMinorEdit() {
786 $this->loadLastEdit();
787 return $this->mMinorEdit
;
791 * Use this to fetch the rev ID used on page views
793 * @return int revision ID of last article revision
795 public function getRevIdFetched() {
796 if ( $this->mRevIdFetched
) {
797 return $this->mRevIdFetched
;
799 return $this->getLatest();
804 * FIXME: this does what?
805 * @param $limit Integer: default 0.
806 * @param $offset Integer: default 0.
807 * @return UserArrayFromResult object with User objects of article contributors for requested range
809 public function getContributors( $limit = 0, $offset = 0 ) {
810 # FIXME: this is expensive; cache this info somewhere.
812 $dbr = wfGetDB( DB_SLAVE
);
813 $revTable = $dbr->tableName( 'revision' );
814 $userTable = $dbr->tableName( 'user' );
816 $pageId = $this->getId();
818 $user = $this->getUser();
821 $excludeCond = "AND rev_user != $user";
823 $userText = $dbr->addQuotes( $this->getUserText() );
824 $excludeCond = "AND rev_user_text != $userText";
827 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
); // username hidden?
829 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
830 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
831 WHERE rev_page = $pageId
834 GROUP BY rev_user, rev_user_text
835 ORDER BY timestamp DESC";
838 $sql = $dbr->limitResult( $sql, $limit, $offset );
841 $sql .= ' ' . $this->getSelectOptions();
842 $res = $dbr->query( $sql, __METHOD__
);
844 return new UserArrayFromResult( $res );
848 * This is the default action of the index.php entry point: just view the
849 * page of the given title.
851 public function view() {
852 global $wgUser, $wgOut, $wgRequest, $wgParser;
853 global $wgUseFileCache, $wgUseETag;
855 wfProfileIn( __METHOD__
);
857 # Get variables from query string
858 $oldid = $this->getOldID();
859 $parserCache = ParserCache
::singleton();
861 $parserOptions = $this->getParserOptions();
862 # Render printable version, use printable version cache
863 if ( $wgOut->isPrintable() ) {
864 $parserOptions->setIsPrintable( true );
865 $parserOptions->setEditSection( false );
866 } else if ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
867 $parserOptions->setEditSection( false );
870 # Try client and file cache
871 if ( $oldid === 0 && $this->checkTouched() ) {
873 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
876 # Is it client cached?
877 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
878 wfDebug( __METHOD__
. ": done 304\n" );
879 wfProfileOut( __METHOD__
);
883 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
884 wfDebug( __METHOD__
. ": done file cache\n" );
885 # tell wgOut that output is taken care of
887 $this->viewUpdates();
888 wfProfileOut( __METHOD__
);
894 # getOldID may want us to redirect somewhere else
895 if ( $this->mRedirectUrl
) {
896 $wgOut->redirect( $this->mRedirectUrl
);
897 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
898 wfProfileOut( __METHOD__
);
903 $wgOut->setArticleFlag( true );
904 # Set page title (may be overridden by DISPLAYTITLE)
905 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
907 # If we got diff in the query, we want to see a diff page instead of the article.
908 if ( $wgRequest->getCheck( 'diff' ) ) {
909 wfDebug( __METHOD__
. ": showing diff page\n" );
910 $this->showDiffPage();
911 wfProfileOut( __METHOD__
);
916 # Allow frames by default
917 $wgOut->allowClickjacking();
919 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
920 $parserOptions->setEditSection( false );
923 # Should the parser cache be used?
924 $useParserCache = $this->useParserCache( $oldid );
925 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
926 if ( $wgUser->getStubThreshold() ) {
927 wfIncrStats( 'pcache_miss_stub' );
930 $wasRedirected = $this->showRedirectedFromHeader();
931 $this->showNamespaceHeader();
933 # Iterate through the possible ways of constructing the output text.
934 # Keep going until $outputDone is set, or we run out of things to do.
937 $this->mParserOutput
= false;
939 while ( !$outputDone && ++
$pass ) {
942 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
945 # Try the parser cache
946 if ( $useParserCache ) {
947 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
949 if ( $this->mParserOutput
!== false ) {
950 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
951 $wgOut->addParserOutput( $this->mParserOutput
);
952 # Ensure that UI elements requiring revision ID have
953 # the correct version information.
954 $wgOut->setRevisionId( $this->mLatest
);
960 $text = $this->getContent();
961 if ( $text === false ||
$this->getID() == 0 ) {
962 wfDebug( __METHOD__
. ": showing missing article\n" );
963 $this->showMissingArticle();
964 wfProfileOut( __METHOD__
);
968 # Another whitelist check in case oldid is altering the title
969 if ( !$this->mTitle
->userCanRead() ) {
970 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
971 $wgOut->loginToUse();
974 wfProfileOut( __METHOD__
);
978 # Are we looking at an old revision
979 if ( $oldid && !is_null( $this->mRevision
) ) {
980 $this->setOldSubtitle( $oldid );
982 if ( !$this->showDeletedRevisionHeader() ) {
983 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
984 wfProfileOut( __METHOD__
);
988 # If this "old" version is the current, then try the parser cache...
989 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
990 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
991 if ( $this->mParserOutput
) {
992 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
993 $wgOut->addParserOutput( $this->mParserOutput
);
994 $wgOut->setRevisionId( $this->mLatest
);
1001 # Ensure that UI elements requiring revision ID have
1002 # the correct version information.
1003 $wgOut->setRevisionId( $this->getRevIdFetched() );
1005 # Pages containing custom CSS or JavaScript get special treatment
1006 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1007 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1008 $this->showCssOrJsPage();
1011 $rt = Title
::newFromRedirectArray( $text );
1013 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1014 # Viewing a redirect page (e.g. with parameter redirect=no)
1015 # Don't append the subtitle if this was an old revision
1016 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1017 # Parse just to get categories, displaytitle, etc.
1018 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1019 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1025 # Run the parse, protected by a pool counter
1026 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1028 $key = $parserCache->getKey( $this, $parserOptions );
1029 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1031 if ( !$poolArticleView->execute() ) {
1032 # Connection or timeout error
1033 wfProfileOut( __METHOD__
);
1039 # Should be unreachable, but just in case...
1045 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1046 if ( $this->mParserOutput
) {
1047 $titleText = $this->mParserOutput
->getTitleText();
1049 if ( strval( $titleText ) !== '' ) {
1050 $wgOut->setPageTitle( $titleText );
1054 # For the main page, overwrite the <title> element with the con-
1055 # tents of 'pagetitle-view-mainpage' instead of the default (if
1056 # that's not empty).
1057 # This message always exists because it is in the i18n files
1058 if ( $this->mTitle
->equals( Title
::newMainPage() )
1059 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
1061 $wgOut->setHTMLTitle( $m );
1064 # Now that we've filled $this->mParserOutput, we know whether
1065 # there are any __NOINDEX__ tags on the page
1066 $policy = $this->getRobotPolicy( 'view' );
1067 $wgOut->setIndexPolicy( $policy['index'] );
1068 $wgOut->setFollowPolicy( $policy['follow'] );
1070 $this->showViewFooter();
1071 $this->viewUpdates();
1072 wfProfileOut( __METHOD__
);
1076 * Show a diff page according to current request variables. For use within
1077 * Article::view() only, other callers should use the DifferenceEngine class.
1079 public function showDiffPage() {
1080 global $wgRequest, $wgUser;
1082 $diff = $wgRequest->getVal( 'diff' );
1083 $rcid = $wgRequest->getVal( 'rcid' );
1084 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1085 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1086 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1087 $oldid = $this->getOldID();
1089 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1090 // DifferenceEngine directly fetched the revision:
1091 $this->mRevIdFetched
= $de->mNewid
;
1092 $de->showDiffPage( $diffOnly );
1094 // Needed to get the page's current revision
1095 $this->loadPageData();
1096 if ( $diff == 0 ||
$diff == $this->mLatest
) {
1097 # Run view updates for current revision only
1098 $this->viewUpdates();
1103 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1104 * Article::view() only.
1106 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1109 protected function showCssOrJsPage() {
1112 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1114 // Give hooks a chance to customise the output
1115 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1116 // Wrap the whole lot in a <pre> and don't parse
1118 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1119 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1120 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1121 $wgOut->addHTML( "\n</pre>\n" );
1126 * Get the robot policy to be used for the current view
1127 * @param $action String the action= GET parameter
1128 * @return Array the policy that should be set
1129 * TODO: actions other than 'view'
1131 public function getRobotPolicy( $action ) {
1132 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1133 global $wgDefaultRobotPolicy, $wgRequest;
1135 $ns = $this->mTitle
->getNamespace();
1137 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1138 # Don't index user and user talk pages for blocked users (bug 11443)
1139 if ( !$this->mTitle
->isSubpage() ) {
1140 $block = new Block();
1141 if ( $block->load( $this->mTitle
->getText() ) ) {
1143 'index' => 'noindex',
1144 'follow' => 'nofollow'
1150 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1151 # Non-articles (special pages etc), and old revisions
1153 'index' => 'noindex',
1154 'follow' => 'nofollow'
1156 } elseif ( $wgOut->isPrintable() ) {
1157 # Discourage indexing of printable versions, but encourage following
1159 'index' => 'noindex',
1160 'follow' => 'follow'
1162 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1163 # For ?curid=x urls, disallow indexing
1165 'index' => 'noindex',
1166 'follow' => 'follow'
1170 # Otherwise, construct the policy based on the various config variables.
1171 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1173 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1174 # Honour customised robot policies for this namespace
1175 $policy = array_merge(
1177 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1180 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1181 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1182 # a final sanity check that we have really got the parser output.
1183 $policy = array_merge(
1185 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1189 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1190 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1191 $policy = array_merge(
1193 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1201 * Converts a String robot policy into an associative array, to allow
1202 * merging of several policies using array_merge().
1203 * @param $policy Mixed, returns empty array on null/false/'', transparent
1204 * to already-converted arrays, converts String.
1205 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1207 public static function formatRobotPolicy( $policy ) {
1208 if ( is_array( $policy ) ) {
1210 } elseif ( !$policy ) {
1214 $policy = explode( ',', $policy );
1215 $policy = array_map( 'trim', $policy );
1218 foreach ( $policy as $var ) {
1219 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1220 $arr['index'] = $var;
1221 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1222 $arr['follow'] = $var;
1230 * If this request is a redirect view, send "redirected from" subtitle to
1231 * $wgOut. Returns true if the header was needed, false if this is not a
1232 * redirect view. Handles both local and remote redirects.
1236 public function showRedirectedFromHeader() {
1237 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1239 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1240 $sk = $wgUser->getSkin();
1242 if ( isset( $this->mRedirectedFrom
) ) {
1243 // This is an internally redirected page view.
1244 // We'll need a backlink to the source page for navigation.
1245 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1247 $this->mRedirectedFrom
,
1250 array( 'redirect' => 'no' ),
1251 array( 'known', 'noclasses' )
1254 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1255 $wgOut->setSubtitle( $s );
1257 // Set the fragment if one was specified in the redirect
1258 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1259 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1260 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1263 // Add a <link rel="canonical"> tag
1264 $wgOut->addLink( array( 'rel' => 'canonical',
1265 'href' => $this->mTitle
->getLocalURL() )
1270 } elseif ( $rdfrom ) {
1271 // This is an externally redirected view, from some other wiki.
1272 // If it was reported from a trusted site, supply a backlink.
1273 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1274 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1275 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1276 $wgOut->setSubtitle( $s );
1286 * Show a header specific to the namespace currently being viewed, like
1287 * [[MediaWiki:Talkpagetext]]. For Article::view().
1289 public function showNamespaceHeader() {
1292 if ( $this->mTitle
->isTalkPage() ) {
1293 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1294 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1300 * Show the footer section of an ordinary page view
1302 public function showViewFooter() {
1303 global $wgOut, $wgUseTrackbacks;
1305 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1306 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1307 $wgOut->addWikiMsg( 'anontalkpagetext' );
1310 # If we have been passed an &rcid= parameter, we want to give the user a
1311 # chance to mark this new article as patrolled.
1312 $this->showPatrolFooter();
1315 if ( $wgUseTrackbacks ) {
1316 $this->addTrackbacks();
1319 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1324 * If patrol is possible, output a patrol UI box. This is called from the
1325 * footer section of ordinary page views. If patrol is not possible or not
1326 * desired, does nothing.
1328 public function showPatrolFooter() {
1329 global $wgOut, $wgRequest, $wgUser;
1331 $rcid = $wgRequest->getVal( 'rcid' );
1333 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1337 $sk = $wgUser->getSkin();
1338 $token = $wgUser->editToken( $rcid );
1339 $wgOut->preventClickjacking();
1342 "<div class='patrollink'>" .
1344 'markaspatrolledlink',
1347 wfMsgHtml( 'markaspatrolledtext' ),
1350 'action' => 'markpatrolled',
1354 array( 'known', 'noclasses' )
1362 * Show the error text for a missing article. For articles in the MediaWiki
1363 * namespace, show the default message text. To be called from Article::view().
1365 public function showMissingArticle() {
1366 global $wgOut, $wgRequest, $wgUser;
1368 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1369 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1370 $parts = explode( '/', $this->mTitle
->getText() );
1371 $rootPart = $parts[0];
1372 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1373 $ip = User
::isIP( $rootPart );
1375 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1376 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1377 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1378 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1379 LogEventsList
::showLogExtract(
1382 $user->getUserPage()->getPrefixedText(),
1386 'showIfEmpty' => false,
1388 'blocked-notice-logextract',
1389 $user->getName() # Support GENDER in notice
1396 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1398 # Show delete and move logs
1399 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1401 'conds' => array( "log_action != 'revision'" ),
1402 'showIfEmpty' => false,
1403 'msgKey' => array( 'moveddeleted-notice' ) )
1406 # Show error message
1407 $oldid = $this->getOldID();
1409 $text = wfMsgNoTrans( 'missing-article',
1410 $this->mTitle
->getPrefixedText(),
1411 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1412 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1413 // Use the default message text
1414 $text = $this->getDefaultMessageText();
1416 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1417 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1418 $errors = array_merge( $createErrors, $editErrors );
1420 if ( !count( $errors ) ) {
1421 $text = wfMsgNoTrans( 'noarticletext' );
1423 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1426 $text = "<div class='noarticletext'>\n$text\n</div>";
1428 if ( !$this->hasViewableContent() ) {
1429 // If there's no backing content, send a 404 Not Found
1430 // for better machine handling of broken links.
1431 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1434 $wgOut->addWikiText( $text );
1438 * If the revision requested for view is deleted, check permissions.
1439 * Send either an error message or a warning header to $wgOut.
1441 * @return boolean true if the view is allowed, false if not.
1443 public function showDeletedRevisionHeader() {
1444 global $wgOut, $wgRequest;
1446 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1451 // If the user is not allowed to see it...
1452 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1453 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1454 'rev-deleted-text-permission' );
1457 // If the user needs to confirm that they want to see it...
1458 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1459 # Give explanation and add a link to view the revision...
1460 $oldid = intval( $this->getOldID() );
1461 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1462 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1463 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1464 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1465 array( $msg, $link ) );
1468 // We are allowed to see...
1470 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1471 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1472 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1479 * Should the parser cache be used?
1483 public function useParserCache( $oldid ) {
1484 global $wgUser, $wgEnableParserCache;
1486 return $wgEnableParserCache
1487 && $wgUser->getStubThreshold() == 0
1490 && !$this->mTitle
->isCssOrJsPage()
1491 && !$this->mTitle
->isCssJsSubpage();
1495 * Execute the uncached parse for action=view
1497 public function doViewParse() {
1500 $oldid = $this->getOldID();
1501 $parserOptions = $this->getParserOptions();
1503 # Render printable version, use printable version cache
1504 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1506 # Don't show section-edit links on old revisions... this way lies madness.
1507 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1508 $parserOptions->setEditSection( false );
1511 $useParserCache = $this->useParserCache( $oldid );
1512 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1518 * Try to fetch an expired entry from the parser cache. If it is present,
1519 * output it and return true. If it is not present, output nothing and
1520 * return false. This is used as a callback function for
1521 * PoolCounter::executeProtected().
1525 public function tryDirtyCache() {
1527 $parserCache = ParserCache
::singleton();
1528 $options = $this->getParserOptions();
1530 if ( $wgOut->isPrintable() ) {
1531 $options->setIsPrintable( true );
1532 $options->setEditSection( false );
1535 $output = $parserCache->getDirty( $this, $options );
1538 wfDebug( __METHOD__
. ": sending dirty output\n" );
1539 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1540 $wgOut->setSquidMaxage( 0 );
1541 $this->mParserOutput
= $output;
1542 $wgOut->addParserOutput( $output );
1543 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1547 wfDebugLog( 'dirty', "dirty missing\n" );
1548 wfDebug( __METHOD__
. ": no dirty cache\n" );
1557 * @param $target Title|Array of destination(s) to redirect
1558 * @param $appendSubtitle Boolean [optional]
1559 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1560 * @return string containing HMTL with redirect link
1562 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1563 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1565 if ( !is_array( $target ) ) {
1566 $target = array( $target );
1569 $imageDir = $wgContLang->getDir();
1571 if ( $appendSubtitle ) {
1572 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1575 $sk = $wgUser->getSkin();
1576 // the loop prepends the arrow image before the link, so the first case needs to be outside
1577 $title = array_shift( $target );
1579 if ( $forceKnown ) {
1580 $link = $sk->linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1582 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1585 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1586 $alt = $wgContLang->isRTL() ?
'←' : '→';
1587 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1588 // FIXME: where this happens?
1589 foreach ( $target as $rt ) {
1590 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1591 if ( $forceKnown ) {
1592 $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText() ) );
1594 $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1598 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1599 return '<div class="redirectMsg">' .
1600 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1601 '<span class="redirectText">' . $link . '</span></div>';
1605 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1607 public function addTrackbacks() {
1608 global $wgOut, $wgUser;
1610 $dbr = wfGetDB( DB_SLAVE
);
1611 $tbs = $dbr->select( 'trackbacks',
1612 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1613 array( 'tb_page' => $this->getID() )
1616 if ( !$dbr->numRows( $tbs ) ) {
1620 $wgOut->preventClickjacking();
1623 foreach ( $tbs as $o ) {
1626 if ( $wgUser->isAllowed( 'trackback' ) ) {
1627 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1628 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1629 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1633 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1641 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1645 * Removes trackback record for current article from trackbacks table
1647 public function deletetrackback() {
1648 global $wgUser, $wgRequest, $wgOut;
1650 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1651 $wgOut->addWikiMsg( 'sessionfailure' );
1656 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1658 if ( count( $permission_errors ) ) {
1659 $wgOut->showPermissionsErrorPage( $permission_errors );
1664 $db = wfGetDB( DB_MASTER
);
1665 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1667 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1668 $this->mTitle
->invalidateCache();
1672 * Handle action=render
1675 public function render() {
1678 $wgOut->setArticleBodyOnly( true );
1683 * Handle action=purge
1685 public function purge() {
1686 global $wgUser, $wgRequest, $wgOut;
1688 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1689 //FIXME: shouldn't this be in doPurge()?
1690 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1695 $formParams = array(
1697 'action' => $wgRequest->getRequestURL(),
1700 $wgOut->addWikiMsg( 'confirm-purge-top' );
1702 $form = Html
::openElement( 'form', $formParams );
1703 $form .= Xml
::submitButton( wfMsg( 'confirm_purge_button' ) );
1704 $form .= Html
::closeElement( 'form' );
1706 $wgOut->addHTML( $form );
1707 $wgOut->addWikiMsg( 'confirm-purge-bottom' );
1709 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1710 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1715 * Perform the actions of a page purging
1717 public function doPurge() {
1720 // Invalidate the cache
1721 $this->mTitle
->invalidateCache();
1724 if ( $wgUseSquid ) {
1725 // Commit the transaction before the purge is sent
1726 $dbw = wfGetDB( DB_MASTER
);
1730 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1731 $update->doUpdate();
1734 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1735 if ( $this->getID() == 0 ) {
1738 $text = $this->getRawText();
1741 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1746 * Insert a new empty page record for this article.
1747 * This *must* be followed up by creating a revision
1748 * and running $this->updateRevisionOn( ... );
1749 * or else the record will be left in a funky state.
1750 * Best if all done inside a transaction.
1752 * @param $dbw Database
1753 * @return int The newly created page_id key, or false if the title already existed
1756 public function insertOn( $dbw ) {
1757 wfProfileIn( __METHOD__
);
1759 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1760 $dbw->insert( 'page', array(
1761 'page_id' => $page_id,
1762 'page_namespace' => $this->mTitle
->getNamespace(),
1763 'page_title' => $this->mTitle
->getDBkey(),
1764 'page_counter' => 0,
1765 'page_restrictions' => '',
1766 'page_is_redirect' => 0, # Will set this shortly...
1768 'page_random' => wfRandom(),
1769 'page_touched' => $dbw->timestamp(),
1770 'page_latest' => 0, # Fill this in shortly...
1771 'page_len' => 0, # Fill this in shortly...
1772 ), __METHOD__
, 'IGNORE' );
1774 $affected = $dbw->affectedRows();
1777 $newid = $dbw->insertId();
1778 $this->mTitle
->resetArticleId( $newid );
1780 wfProfileOut( __METHOD__
);
1782 return $affected ?
$newid : false;
1786 * Update the page record to point to a newly saved revision.
1788 * @param $dbw DatabaseBase: object
1789 * @param $revision Revision: For ID number, and text used to set
1790 length and redirect status fields
1791 * @param $lastRevision Integer: if given, will not overwrite the page field
1792 * when different from the currently set value.
1793 * Giving 0 indicates the new page flag should be set
1795 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1796 * removing rows in redirect table.
1797 * @param $setNewFlag Boolean: Set to true if a page flag should be set
1798 * Needed when $lastRevision has to be set to sth. !=0
1799 * @return bool true on success, false on failure
1802 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
1803 wfProfileIn( __METHOD__
);
1805 $text = $revision->getText();
1806 $rt = Title
::newFromRedirectRecurse( $text );
1808 $conditions = array( 'page_id' => $this->getId() );
1810 if ( !is_null( $lastRevision ) ) {
1811 # An extra check against threads stepping on each other
1812 $conditions['page_latest'] = $lastRevision;
1815 if ( !$setNewFlag ) {
1816 $setNewFlag = ( $lastRevision === 0 );
1819 $dbw->update( 'page',
1821 'page_latest' => $revision->getId(),
1822 'page_touched' => $dbw->timestamp(),
1823 'page_is_new' => $setNewFlag,
1824 'page_is_redirect' => $rt !== null ?
1 : 0,
1825 'page_len' => strlen( $text ),
1830 $result = $dbw->affectedRows() != 0;
1832 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1835 wfProfileOut( __METHOD__
);
1840 * Add row to the redirect table if this is a redirect, remove otherwise.
1842 * @param $dbw Database
1843 * @param $redirectTitle Title object pointing to the redirect target,
1844 * or NULL if this is not a redirect
1845 * @param $lastRevIsRedirect If given, will optimize adding and
1846 * removing rows in redirect table.
1847 * @return bool true on success, false on failure
1850 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1851 // Always update redirects (target link might have changed)
1852 // Update/Insert if we don't know if the last revision was a redirect or not
1853 // Delete if changing from redirect to non-redirect
1854 $isRedirect = !is_null( $redirectTitle );
1856 if ( $isRedirect ||
is_null( $lastRevIsRedirect ) ||
$lastRevIsRedirect !== $isRedirect ) {
1857 wfProfileIn( __METHOD__
);
1858 if ( $isRedirect ) {
1859 $this->insertRedirectEntry( $redirectTitle );
1861 // This is not a redirect, remove row from redirect table
1862 $where = array( 'rd_from' => $this->getId() );
1863 $dbw->delete( 'redirect', $where, __METHOD__
);
1866 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1867 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1869 wfProfileOut( __METHOD__
);
1871 return ( $dbw->affectedRows() != 0 );
1878 * If the given revision is newer than the currently set page_latest,
1879 * update the page record. Otherwise, do nothing.
1881 * @param $dbw Database object
1882 * @param $revision Revision object
1885 public function updateIfNewerOn( &$dbw, $revision ) {
1886 wfProfileIn( __METHOD__
);
1888 $row = $dbw->selectRow(
1889 array( 'revision', 'page' ),
1890 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1892 'page_id' => $this->getId(),
1893 'page_latest=rev_id' ),
1897 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1898 wfProfileOut( __METHOD__
);
1901 $prev = $row->rev_id
;
1902 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1904 # No or missing previous revision; mark the page as new
1906 $lastRevIsRedirect = null;
1909 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1911 wfProfileOut( __METHOD__
);
1916 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1917 * @param $text String: new text of the section
1918 * @param $summary String: new section's subject, only if $section is 'new'
1919 * @param $edittime String: revision timestamp or null to use the current revision
1920 * @return string Complete article text, or null if error
1922 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1923 wfProfileIn( __METHOD__
);
1925 if ( strval( $section ) == '' ) {
1926 // Whole-page edit; let the whole text through
1928 if ( is_null( $edittime ) ) {
1929 $rev = Revision
::newFromTitle( $this->mTitle
);
1931 $dbw = wfGetDB( DB_MASTER
);
1932 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1936 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1937 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1941 $oldtext = $rev->getText();
1943 if ( $section == 'new' ) {
1944 # Inserting a new section
1945 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1946 $text = strlen( trim( $oldtext ) ) > 0
1947 ?
"{$oldtext}\n\n{$subject}{$text}"
1948 : "{$subject}{$text}";
1950 # Replacing an existing section; roll out the big guns
1953 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1957 wfProfileOut( __METHOD__
);
1962 * @deprecated @since 1.7 use Article::doEdit()
1964 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1965 wfDeprecated( __METHOD__
);
1967 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1968 ( $isminor ? EDIT_MINOR
: 0 ) |
1969 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1970 ( $bot ? EDIT_FORCE_BOT
: 0 );
1972 # If this is a comment, add the summary as headline
1973 if ( $comment && $summary != "" ) {
1974 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
1976 $this->doEdit( $text, $summary, $flags );
1978 $dbw = wfGetDB( DB_MASTER
);
1980 if ( !$this->mTitle
->userIsWatching() ) {
1986 if ( $this->mTitle
->userIsWatching() ) {
1992 $this->doRedirect( $this->isRedirect( $text ) );
1996 * @deprecated @since 1.7 use Article::doEdit()
1998 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1999 wfDeprecated( __METHOD__
);
2001 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
2002 ( $minor ? EDIT_MINOR
: 0 ) |
2003 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
2005 $status = $this->doEdit( $text, $summary, $flags );
2007 if ( !$status->isOK() ) {
2011 $dbw = wfGetDB( DB_MASTER
);
2013 if ( !$this->mTitle
->userIsWatching() ) {
2019 if ( $this->mTitle
->userIsWatching() ) {
2026 $extraQuery = ''; // Give extensions a chance to modify URL query on update
2027 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
2029 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
2034 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
2036 * @return Int updated $flags
2038 function checkFlags( $flags ) {
2039 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
2040 if ( $this->mTitle
->getArticleID() ) {
2041 $flags |
= EDIT_UPDATE
;
2053 * Change an existing article or create a new article. Updates RC and all necessary caches,
2054 * optionally via the deferred update array.
2056 * $wgUser must be set before calling this function.
2058 * @param $text String: new text
2059 * @param $summary String: edit summary
2060 * @param $flags Integer bitfield:
2062 * Article is known or assumed to be non-existent, create a new one
2064 * Article is known or assumed to be pre-existing, update it
2066 * Mark this edit minor, if the user is allowed to do so
2068 * Do not log the change in recentchanges
2070 * Mark the edit a "bot" edit regardless of user rights
2071 * EDIT_DEFER_UPDATES
2072 * Defer some of the updates until the end of index.php
2074 * Fill in blank summaries with generated text where possible
2076 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2077 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2078 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2079 * edit-already-exists error will be returned. These two conditions are also possible with
2080 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2082 * @param $baseRevId the revision ID this edit was based off, if any
2083 * @param $user User (optional), $wgUser will be used if not passed
2085 * @return Status object. Possible errors:
2086 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2087 * edit-gone-missing: In update mode, but the article didn't exist
2088 * edit-conflict: In update mode, the article changed unexpectedly
2089 * edit-no-change: Warning that the text was the same as before
2090 * edit-already-exists: In creation mode, but the article already exists
2092 * Extensions may define additional errors.
2094 * $return->value will contain an associative array with members as follows:
2095 * new: Boolean indicating if the function attempted to create a new article
2096 * revision: The revision object for the inserted revision, or null
2098 * Compatibility note: this function previously returned a boolean value indicating success/failure
2100 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2101 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2103 # Low-level sanity check
2104 if ( $this->mTitle
->getText() === '' ) {
2105 throw new MWException( 'Something is trying to edit an article with an empty title' );
2108 wfProfileIn( __METHOD__
);
2110 $user = is_null( $user ) ?
$wgUser : $user;
2111 $status = Status
::newGood( array() );
2113 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2114 $this->loadPageData();
2116 $flags = $this->checkFlags( $flags );
2118 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2119 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2121 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2122 wfProfileOut( __METHOD__
);
2124 if ( $status->isOK() ) {
2125 $status->fatal( 'edit-hook-aborted' );
2131 # Silently ignore EDIT_MINOR if not allowed
2132 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2133 $bot = $flags & EDIT_FORCE_BOT
;
2135 $oldtext = $this->getRawText(); // current revision
2136 $oldsize = strlen( $oldtext );
2138 # Provide autosummaries if one is not provided and autosummaries are enabled.
2139 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2140 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2143 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2144 $text = $editInfo->pst
;
2145 $newsize = strlen( $text );
2147 $dbw = wfGetDB( DB_MASTER
);
2148 $now = wfTimestampNow();
2149 $this->mTimestamp
= $now;
2151 if ( $flags & EDIT_UPDATE
) {
2152 # Update article, but only if changed.
2153 $status->value
['new'] = false;
2155 # Make sure the revision is either completely inserted or not inserted at all
2156 if ( !$wgDBtransactions ) {
2157 $userAbort = ignore_user_abort( true );
2160 $changed = ( strcmp( $text, $oldtext ) != 0 );
2163 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
2164 - (int)$this->isCountable( $oldtext );
2165 $this->mTotalAdjustment
= 0;
2167 if ( !$this->mLatest
) {
2168 # Article gone missing
2169 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2170 $status->fatal( 'edit-gone-missing' );
2172 wfProfileOut( __METHOD__
);
2176 $revision = new Revision( array(
2177 'page' => $this->getId(),
2178 'comment' => $summary,
2179 'minor_edit' => $isminor,
2181 'parent_id' => $this->mLatest
,
2182 'user' => $user->getId(),
2183 'user_text' => $user->getName(),
2188 $revisionId = $revision->insertOn( $dbw );
2192 # Note that we use $this->mLatest instead of fetching a value from the master DB
2193 # during the course of this function. This makes sure that EditPage can detect
2194 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2195 # before this function is called. A previous function used a separate query, this
2196 # creates a window where concurrent edits can cause an ignored edit conflict.
2197 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2200 /* Belated edit conflict! Run away!! */
2201 $status->fatal( 'edit-conflict' );
2203 # Delete the invalid revision if the DB is not transactional
2204 if ( !$wgDBtransactions ) {
2205 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2211 global $wgUseRCPatrol;
2212 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2213 # Update recentchanges
2214 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2215 # Mark as patrolled if the user can do so
2216 $patrolled = $wgUseRCPatrol && !count(
2217 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2218 # Add RC row to the DB
2219 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2220 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2221 $revisionId, $patrolled
2224 # Log auto-patrolled edits
2226 PatrolLog
::record( $rc, true );
2229 $user->incEditCount();
2233 $status->warning( 'edit-no-change' );
2235 // Keep the same revision ID, but do some updates on it
2236 $revisionId = $this->getLatest();
2237 // Update page_touched, this is usually implicit in the page update
2238 // Other cache updates are done in onArticleEdit()
2239 $this->mTitle
->invalidateCache();
2242 if ( !$wgDBtransactions ) {
2243 ignore_user_abort( $userAbort );
2246 // Now that ignore_user_abort is restored, we can respond to fatal errors
2247 if ( !$status->isOK() ) {
2248 wfProfileOut( __METHOD__
);
2252 # Invalidate cache of this article and all pages using this article
2253 # as a template. Partly deferred.
2254 Article
::onArticleEdit( $this->mTitle
);
2255 # Update links tables, site stats, etc.
2256 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2258 # Create new article
2259 $status->value
['new'] = true;
2261 # Set statistics members
2262 # We work out if it's countable after PST to avoid counter drift
2263 # when articles are created with {{subst:}}
2264 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2265 $this->mTotalAdjustment
= 1;
2269 # Add the page record; stake our claim on this title!
2270 # This will return false if the article already exists
2271 $newid = $this->insertOn( $dbw );
2273 if ( $newid === false ) {
2275 $status->fatal( 'edit-already-exists' );
2277 wfProfileOut( __METHOD__
);
2281 # Save the revision text...
2282 $revision = new Revision( array(
2284 'comment' => $summary,
2285 'minor_edit' => $isminor,
2287 'user' => $user->getId(),
2288 'user_text' => $user->getName(),
2291 $revisionId = $revision->insertOn( $dbw );
2293 $this->mTitle
->resetArticleID( $newid );
2295 # Update the page record with revision data
2296 $this->updateRevisionOn( $dbw, $revision, 0 );
2298 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2300 # Update recentchanges
2301 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2302 global $wgUseRCPatrol, $wgUseNPPatrol;
2304 # Mark as patrolled if the user can do so
2305 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2306 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2307 # Add RC row to the DB
2308 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2309 '', strlen( $text ), $revisionId, $patrolled );
2311 # Log auto-patrolled edits
2313 PatrolLog
::record( $rc, true );
2316 $user->incEditCount();
2319 # Update links, etc.
2320 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user );
2323 Article
::onArticleCreate( $this->mTitle
);
2325 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2326 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2329 # Do updates right now unless deferral was requested
2330 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2334 // Return the new revision (or null) to the caller
2335 $status->value
['revision'] = $revision;
2337 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2338 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2340 wfProfileOut( __METHOD__
);
2345 * Output a redirect back to the article.
2346 * This is typically used after an edit.
2348 * @param $noRedir Boolean: add redirect=no
2349 * @param $sectionAnchor String: section to redirect to, including "#"
2350 * @param $extraQuery String: extra query params
2352 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2356 $query = 'redirect=no';
2358 $query .= "&$extraQuery";
2360 $query = $extraQuery;
2363 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2367 * Mark this particular edit/page as patrolled
2369 public function markpatrolled() {
2370 global $wgOut, $wgUser, $wgRequest;
2372 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2374 # If we haven't been given an rc_id value, we can't do anything
2375 $rcid = (int) $wgRequest->getVal( 'rcid' );
2377 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2378 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2382 $rc = RecentChange
::newFromId( $rcid );
2384 if ( is_null( $rc ) ) {
2385 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2389 # It would be nice to see where the user had actually come from, but for now just guess
2390 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2391 $return = SpecialPage
::getTitleFor( $returnto );
2393 $errors = $rc->doMarkPatrolled();
2395 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2396 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2401 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2402 // The hook itself has handled any output
2406 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2407 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2408 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2409 $wgOut->returnToMain( false, $return );
2414 if ( !empty( $errors ) ) {
2415 $wgOut->showPermissionsErrorPage( $errors );
2421 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2422 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2423 $wgOut->returnToMain( false, $return );
2427 * User-interface handler for the "watch" action
2429 public function watch() {
2430 global $wgUser, $wgOut;
2432 if ( $wgUser->isAnon() ) {
2433 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2437 if ( wfReadOnly() ) {
2438 $wgOut->readOnlyPage();
2442 if ( $this->doWatch() ) {
2443 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2444 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2445 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
2448 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2452 * Add this page to $wgUser's watchlist
2453 * @return bool true on successful watch operation
2455 public function doWatch() {
2458 if ( $wgUser->isAnon() ) {
2462 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2463 $wgUser->addWatch( $this->mTitle
);
2464 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2471 * User interface handler for the "unwatch" action.
2473 public function unwatch() {
2474 global $wgUser, $wgOut;
2476 if ( $wgUser->isAnon() ) {
2477 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2481 if ( wfReadOnly() ) {
2482 $wgOut->readOnlyPage();
2486 if ( $this->doUnwatch() ) {
2487 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2488 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2489 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
2492 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2496 * Stop watching a page
2497 * @return bool true on successful unwatch
2499 public function doUnwatch() {
2502 if ( $wgUser->isAnon() ) {
2506 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2507 $wgUser->removeWatch( $this->mTitle
);
2508 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2515 * action=protect handler
2517 public function protect() {
2518 $form = new ProtectionForm( $this );
2523 * action=unprotect handler (alias)
2525 public function unprotect() {
2530 * Update the article's restriction field, and leave a log entry.
2532 * @param $limit Array: set of restriction keys
2533 * @param $reason String
2534 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2535 * @param $expiry Array: per restriction type expiration
2536 * @return bool true on success
2538 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2539 global $wgUser, $wgContLang;
2541 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2543 $id = $this->mTitle
->getArticleID();
2546 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2550 if ( wfReadOnly() ) {
2551 wfDebug( "updateRestrictions failed: read-only\n" );
2555 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2556 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2564 // Take this opportunity to purge out expired restrictions
2565 Title
::purgeExpiredRestrictions();
2567 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2568 # we expect a single selection, but the schema allows otherwise.
2570 $updated = Article
::flattenRestrictions( $limit );
2573 foreach ( $restrictionTypes as $action ) {
2574 if ( isset( $expiry[$action] ) ) {
2575 # Get current restrictions on $action
2576 $aLimits = $this->mTitle
->getRestrictions( $action );
2577 $current[$action] = implode( '', $aLimits );
2578 # Are any actual restrictions being dealt with here?
2579 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2581 # If something changed, we need to log it. Checking $aRChanged
2582 # assures that "unprotecting" a page that is not protected does
2583 # not log just because the expiry was "changed".
2584 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2590 $current = Article
::flattenRestrictions( $current );
2592 $changed = ( $changed ||
$current != $updated );
2593 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2594 $protect = ( $updated != '' );
2596 # If nothing's changed, do nothing
2598 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2599 $dbw = wfGetDB( DB_MASTER
);
2601 # Prepare a null revision to be added to the history
2602 $modified = $current != '' && $protect;
2605 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2607 $comment_type = 'unprotectedarticle';
2610 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2612 # Only restrictions with the 'protect' right can cascade...
2613 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2614 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2616 # The schema allows multiple restrictions
2617 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2621 $cascade_description = '';
2624 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2628 $comment .= ": $reason";
2631 $editComment = $comment;
2632 $encodedExpiry = array();
2633 $protect_description = '';
2634 foreach ( $limit as $action => $restrictions ) {
2635 if ( !isset( $expiry[$action] ) )
2636 $expiry[$action] = Block
::infinity();
2638 $encodedExpiry[$action] = Block
::encodeExpiry( $expiry[$action], $dbw );
2639 if ( $restrictions != '' ) {
2640 $protect_description .= "[$action=$restrictions] (";
2641 if ( $encodedExpiry[$action] != 'infinity' ) {
2642 $protect_description .= wfMsgForContent( 'protect-expiring',
2643 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2644 $wgContLang->date( $expiry[$action], false, false ) ,
2645 $wgContLang->time( $expiry[$action], false, false ) );
2647 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2650 $protect_description .= ') ';
2653 $protect_description = trim( $protect_description );
2655 if ( $protect_description && $protect ) {
2656 $editComment .= " ($protect_description)";
2660 $editComment .= "$cascade_description";
2663 # Update restrictions table
2664 foreach ( $limit as $action => $restrictions ) {
2665 if ( $restrictions != '' ) {
2666 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2667 array( 'pr_page' => $id,
2668 'pr_type' => $action,
2669 'pr_level' => $restrictions,
2670 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2671 'pr_expiry' => $encodedExpiry[$action]
2676 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2677 'pr_type' => $action ), __METHOD__
);
2681 # Insert a null revision
2682 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2683 $nullRevId = $nullRevision->insertOn( $dbw );
2685 $latest = $this->getLatest();
2686 # Update page record
2687 $dbw->update( 'page',
2689 'page_touched' => $dbw->timestamp(),
2690 'page_restrictions' => '',
2691 'page_latest' => $nullRevId
2692 ), array( /* WHERE */
2694 ), 'Article::protect'
2697 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2698 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2700 # Update the protection log
2701 $log = new LogPage( 'protect' );
2703 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2704 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2706 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2709 } # End "changed" check
2715 * Take an array of page restrictions and flatten it to a string
2716 * suitable for insertion into the page_restrictions field.
2717 * @param $limit Array
2720 protected static function flattenRestrictions( $limit ) {
2721 if ( !is_array( $limit ) ) {
2722 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2728 foreach ( $limit as $action => $restrictions ) {
2729 if ( $restrictions != '' ) {
2730 $bits[] = "$action=$restrictions";
2734 return implode( ':', $bits );
2738 * Auto-generates a deletion reason
2740 * @param &$hasHistory Boolean: whether the page has a history
2741 * @return mixed String containing deletion reason or empty string, or boolean false
2742 * if no revision occurred
2744 public function generateReason( &$hasHistory ) {
2747 $dbw = wfGetDB( DB_MASTER
);
2748 // Get the last revision
2749 $rev = Revision
::newFromTitle( $this->mTitle
);
2751 if ( is_null( $rev ) ) {
2755 // Get the article's contents
2756 $contents = $rev->getText();
2759 // If the page is blank, use the text from the previous revision,
2760 // which can only be blank if there's a move/import/protect dummy revision involved
2761 if ( $contents == '' ) {
2762 $prev = $rev->getPrevious();
2765 $contents = $prev->getText();
2770 // Find out if there was only one contributor
2771 // Only scan the last 20 revisions
2772 $res = $dbw->select( 'revision', 'rev_user_text',
2773 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2775 array( 'LIMIT' => 20 )
2778 if ( $res === false ) {
2779 // This page has no revisions, which is very weird
2783 $hasHistory = ( $res->numRows() > 1 );
2784 $row = $dbw->fetchObject( $res );
2786 if ( $row ) { // $row is false if the only contributor is hidden
2787 $onlyAuthor = $row->rev_user_text
;
2788 // Try to find a second contributor
2789 foreach ( $res as $row ) {
2790 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2791 $onlyAuthor = false;
2796 $onlyAuthor = false;
2799 // Generate the summary with a '$1' placeholder
2801 // The current revision is blank and the one before is also
2802 // blank. It's just not our lucky day
2803 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2805 if ( $onlyAuthor ) {
2806 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2808 $reason = wfMsgForContent( 'excontent', '$1' );
2812 if ( $reason == '-' ) {
2813 // Allow these UI messages to be blanked out cleanly
2817 // Replace newlines with spaces to prevent uglyness
2818 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2819 // Calculate the maximum amount of chars to get
2820 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2821 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2822 $contents = $wgContLang->truncate( $contents, $maxLength );
2823 // Remove possible unfinished links
2824 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2825 // Now replace the '$1' placeholder
2826 $reason = str_replace( '$1', $contents, $reason );
2833 * UI entry point for page deletion
2835 public function delete() {
2836 global $wgUser, $wgOut, $wgRequest;
2838 $confirm = $wgRequest->wasPosted() &&
2839 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2841 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2842 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2844 $reason = $this->DeleteReasonList
;
2846 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2847 // Entry from drop down menu + additional comment
2848 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2849 } elseif ( $reason == 'other' ) {
2850 $reason = $this->DeleteReason
;
2853 # Flag to hide all contents of the archived revisions
2854 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2856 # This code desperately needs to be totally rewritten
2858 # Read-only check...
2859 if ( wfReadOnly() ) {
2860 $wgOut->readOnlyPage();
2866 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2868 if ( count( $permission_errors ) > 0 ) {
2869 $wgOut->showPermissionsErrorPage( $permission_errors );
2874 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2876 # Better double-check that it hasn't been deleted yet!
2877 $dbw = wfGetDB( DB_MASTER
);
2878 $conds = $this->mTitle
->pageCond();
2879 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2880 if ( $latest === false ) {
2881 $wgOut->showFatalError(
2884 array( 'class' => 'error mw-error-cannotdelete' ),
2885 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2888 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2889 LogEventsList
::showLogExtract(
2892 $this->mTitle
->getPrefixedText()
2898 # Hack for big sites
2899 $bigHistory = $this->isBigDeletion();
2900 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2901 global $wgLang, $wgDeleteRevisionsLimit;
2903 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2904 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2910 $this->doDelete( $reason, $suppress );
2912 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2914 } elseif ( $this->mTitle
->userIsWatching() ) {
2921 // Generate deletion reason
2922 $hasHistory = false;
2924 $reason = $this->generateReason( $hasHistory );
2927 // If the page has a history, insert a warning
2928 if ( $hasHistory && !$confirm ) {
2931 $skin = $wgUser->getSkin();
2932 $revisions = $this->estimateRevisionCount();
2934 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2935 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2936 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2940 if ( $bigHistory ) {
2941 global $wgDeleteRevisionsLimit;
2942 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2943 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2947 return $this->confirmDelete( $reason );
2951 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2953 public function isBigDeletion() {
2954 global $wgDeleteRevisionsLimit;
2956 if ( $wgDeleteRevisionsLimit ) {
2957 $revCount = $this->estimateRevisionCount();
2959 return $revCount > $wgDeleteRevisionsLimit;
2966 * @return int approximate revision count
2968 public function estimateRevisionCount() {
2969 $dbr = wfGetDB( DB_SLAVE
);
2971 // For an exact count...
2972 // return $dbr->selectField( 'revision', 'COUNT(*)',
2973 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2974 return $dbr->estimateRowCount( 'revision', '*',
2975 array( 'rev_page' => $this->getId() ), __METHOD__
);
2979 * Get the last N authors
2980 * @param $num Integer: number of revisions to get
2981 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2982 * @return array Array of authors, duplicates not removed
2984 public function getLastNAuthors( $num, $revLatest = 0 ) {
2985 wfProfileIn( __METHOD__
);
2986 // First try the slave
2987 // If that doesn't have the latest revision, try the master
2989 $db = wfGetDB( DB_SLAVE
);
2992 $res = $db->select( array( 'page', 'revision' ),
2993 array( 'rev_id', 'rev_user_text' ),
2995 'page_namespace' => $this->mTitle
->getNamespace(),
2996 'page_title' => $this->mTitle
->getDBkey(),
2997 'rev_page = page_id'
2998 ), __METHOD__
, $this->getSelectOptions( array(
2999 'ORDER BY' => 'rev_timestamp DESC',
3005 wfProfileOut( __METHOD__
);
3009 $row = $db->fetchObject( $res );
3011 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
3012 $db = wfGetDB( DB_MASTER
);
3017 } while ( $continue );
3019 $authors = array( $row->rev_user_text
);
3021 foreach ( $res as $row ) {
3022 $authors[] = $row->rev_user_text
;
3025 wfProfileOut( __METHOD__
);
3030 * Output deletion confirmation dialog
3031 * FIXME: Move to another file?
3032 * @param $reason String: prefilled reason
3034 public function confirmDelete( $reason ) {
3035 global $wgOut, $wgUser;
3037 wfDebug( "Article::confirmDelete\n" );
3039 $deleteBackLink = $wgUser->getSkin()->linkKnown( $this->mTitle
);
3040 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
3041 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3042 $wgOut->addWikiMsg( 'confirmdeletetext' );
3044 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
3046 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
3047 $suppress = "<tr id=\"wpDeleteSuppressRow\">
3049 <td class='mw-input'><strong>" .
3050 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
3051 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
3057 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
3059 $form = Xml
::openElement( 'form', array( 'method' => 'post',
3060 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
3061 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
3062 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
3063 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
3064 "<tr id=\"wpDeleteReasonListRow\">
3065 <td class='mw-label'>" .
3066 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
3068 <td class='mw-input'>" .
3069 Xml
::listDropDown( 'wpDeleteReasonList',
3070 wfMsgForContent( 'deletereason-dropdown' ),
3071 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
3074 <tr id=\"wpDeleteReasonRow\">
3075 <td class='mw-label'>" .
3076 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
3078 <td class='mw-input'>" .
3079 Html
::input( 'wpReason', $reason, 'text', array(
3081 'maxlength' => '255',
3089 # Disallow watching if user is not logged in
3090 if ( $wgUser->isLoggedIn() ) {
3094 <td class='mw-input'>" .
3095 Xml
::checkLabel( wfMsg( 'watchthis' ),
3096 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3105 <td class='mw-submit'>" .
3106 Xml
::submitButton( wfMsg( 'deletepage' ),
3107 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3110 Xml
::closeElement( 'table' ) .
3111 Xml
::closeElement( 'fieldset' ) .
3112 Html
::hidden( 'wpEditToken', $wgUser->editToken() ) .
3113 Xml
::closeElement( 'form' );
3115 if ( $wgUser->isAllowed( 'editinterface' ) ) {
3116 $skin = $wgUser->getSkin();
3117 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
3118 $link = $skin->link(
3120 wfMsgHtml( 'delete-edit-reasonlist' ),
3122 array( 'action' => 'edit' )
3124 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3127 $wgOut->addHTML( $form );
3128 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3129 LogEventsList
::showLogExtract( $wgOut, 'delete',
3130 $this->mTitle
->getPrefixedText()
3135 * Perform a deletion and output success or failure messages
3137 public function doDelete( $reason, $suppress = false ) {
3138 global $wgOut, $wgUser;
3140 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3143 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3144 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
3145 $deleted = $this->mTitle
->getPrefixedText();
3147 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3148 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3150 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3152 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3153 $wgOut->returnToMain( false );
3154 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3157 if ( $error == '' ) {
3158 $wgOut->showFatalError(
3161 array( 'class' => 'error mw-error-cannotdelete' ),
3162 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3166 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3168 LogEventsList
::showLogExtract(
3171 $this->mTitle
->getPrefixedText()
3174 $wgOut->showFatalError( $error );
3180 * Back-end article deletion
3181 * Deletes the article with database consistency, writes logs, purges caches
3183 * @param $reason string delete reason for deletion log
3184 * @param suppress bitfield
3185 * Revision::DELETED_TEXT
3186 * Revision::DELETED_COMMENT
3187 * Revision::DELETED_USER
3188 * Revision::DELETED_RESTRICTED
3189 * @param $id int article ID
3190 * @param $commit boolean defaults to true, triggers transaction end
3191 * @return boolean true if successful
3193 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
3194 global $wgDeferredUpdateList, $wgUseTrackbacks;
3196 wfDebug( __METHOD__
. "\n" );
3198 $dbw = wfGetDB( DB_MASTER
);
3199 $t = $this->mTitle
->getDBkey();
3200 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3202 if ( $t === '' ||
$id == 0 ) {
3206 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3207 array_push( $wgDeferredUpdateList, $u );
3209 // Bitfields to further suppress the content
3212 // This should be 15...
3213 $bitfield |
= Revision
::DELETED_TEXT
;
3214 $bitfield |
= Revision
::DELETED_COMMENT
;
3215 $bitfield |
= Revision
::DELETED_USER
;
3216 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3218 $bitfield = 'rev_deleted';
3222 // For now, shunt the revision data into the archive table.
3223 // Text is *not* removed from the text table; bulk storage
3224 // is left intact to avoid breaking block-compression or
3225 // immutable storage schemes.
3227 // For backwards compatibility, note that some older archive
3228 // table entries will have ar_text and ar_flags fields still.
3230 // In the future, we may keep revisions and mark them with
3231 // the rev_deleted field, which is reserved for this purpose.
3232 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3234 'ar_namespace' => 'page_namespace',
3235 'ar_title' => 'page_title',
3236 'ar_comment' => 'rev_comment',
3237 'ar_user' => 'rev_user',
3238 'ar_user_text' => 'rev_user_text',
3239 'ar_timestamp' => 'rev_timestamp',
3240 'ar_minor_edit' => 'rev_minor_edit',
3241 'ar_rev_id' => 'rev_id',
3242 'ar_text_id' => 'rev_text_id',
3243 'ar_text' => '\'\'', // Be explicit to appease
3244 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3245 'ar_len' => 'rev_len',
3246 'ar_page_id' => 'page_id',
3247 'ar_deleted' => $bitfield
3250 'page_id = rev_page'
3254 # Delete restrictions for it
3255 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3257 # Now that it's safely backed up, delete it
3258 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3259 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3266 # Fix category table counts
3268 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3270 foreach ( $res as $row ) {
3271 $cats [] = $row->cl_to
;
3274 $this->updateCategoryCounts( array(), $cats );
3276 # If using cascading deletes, we can skip some explicit deletes
3277 if ( !$dbw->cascadingDeletes() ) {
3278 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3280 if ( $wgUseTrackbacks )
3281 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3283 # Delete outgoing links
3284 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3285 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3286 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3287 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3288 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3289 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3290 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3293 # If using cleanup triggers, we can skip some manual deletes
3294 if ( !$dbw->cleanupTriggers() ) {
3295 # Clean up recentchanges entries...
3296 $dbw->delete( 'recentchanges',
3297 array( 'rc_type != ' . RC_LOG
,
3298 'rc_namespace' => $this->mTitle
->getNamespace(),
3299 'rc_title' => $this->mTitle
->getDBkey() ),
3301 $dbw->delete( 'recentchanges',
3302 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3307 Article
::onArticleDelete( $this->mTitle
);
3309 # Clear the cached article id so the interface doesn't act like we exist
3310 $this->mTitle
->resetArticleID( 0 );
3312 # Log the deletion, if the page was suppressed, log it at Oversight instead
3313 $logtype = $suppress ?
'suppress' : 'delete';
3314 $log = new LogPage( $logtype );
3316 # Make sure logging got through
3317 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3327 * Roll back the most recent consecutive set of edits to a page
3328 * from the same user; fails if there are no eligible edits to
3329 * roll back to, e.g. user is the sole contributor. This function
3330 * performs permissions checks on $wgUser, then calls commitRollback()
3331 * to do the dirty work
3333 * @param $fromP String: Name of the user whose edits to rollback.
3334 * @param $summary String: Custom summary. Set to default summary if empty.
3335 * @param $token String: Rollback token.
3336 * @param $bot Boolean: If true, mark all reverted edits as bot.
3338 * @param $resultDetails Array: contains result-specific array of additional values
3339 * 'alreadyrolled' : 'current' (rev)
3340 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3342 * @return array of errors, each error formatted as
3343 * array(messagekey, param1, param2, ...).
3344 * On success, the array is empty. This array can also be passed to
3345 * OutputPage::showPermissionsErrorPage().
3347 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3350 $resultDetails = null;
3353 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3354 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3355 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3357 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3358 $errors[] = array( 'sessionfailure' );
3361 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3362 $errors[] = array( 'actionthrottledtext' );
3365 # If there were errors, bail out now
3366 if ( !empty( $errors ) ) {
3370 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3374 * Backend implementation of doRollback(), please refer there for parameter
3375 * and return value documentation
3377 * NOTE: This function does NOT check ANY permissions, it just commits the
3378 * rollback to the DB Therefore, you should only call this function direct-
3379 * ly if you want to use custom permissions checks. If you don't, use
3380 * doRollback() instead.
3382 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3383 global $wgUseRCPatrol, $wgUser, $wgLang;
3385 $dbw = wfGetDB( DB_MASTER
);
3387 if ( wfReadOnly() ) {
3388 return array( array( 'readonlytext' ) );
3391 # Get the last editor
3392 $current = Revision
::newFromTitle( $this->mTitle
);
3393 if ( is_null( $current ) ) {
3394 # Something wrong... no page?
3395 return array( array( 'notanarticle' ) );
3398 $from = str_replace( '_', ' ', $fromP );
3399 # User name given should match up with the top revision.
3400 # If the user was deleted then $from should be empty.
3401 if ( $from != $current->getUserText() ) {
3402 $resultDetails = array( 'current' => $current );
3403 return array( array( 'alreadyrolled',
3404 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3405 htmlspecialchars( $fromP ),
3406 htmlspecialchars( $current->getUserText() )
3410 # Get the last edit not by this guy...
3411 # Note: these may not be public values
3412 $user = intval( $current->getRawUser() );
3413 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3414 $s = $dbw->selectRow( 'revision',
3415 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3416 array( 'rev_page' => $current->getPage(),
3417 "rev_user != {$user} OR rev_user_text != {$user_text}"
3419 array( 'USE INDEX' => 'page_timestamp',
3420 'ORDER BY' => 'rev_timestamp DESC' )
3422 if ( $s === false ) {
3423 # No one else ever edited this page
3424 return array( array( 'cantrollback' ) );
3425 } else if ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3426 # Only admins can see this text
3427 return array( array( 'notvisiblerev' ) );
3431 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3432 # Mark all reverted edits as bot
3436 if ( $wgUseRCPatrol ) {
3437 # Mark all reverted edits as patrolled
3438 $set['rc_patrolled'] = 1;
3441 if ( count( $set ) ) {
3442 $dbw->update( 'recentchanges', $set,
3444 'rc_cur_id' => $current->getPage(),
3445 'rc_user_text' => $current->getUserText(),
3446 "rc_timestamp > '{$s->rev_timestamp}'",
3451 # Generate the edit summary if necessary
3452 $target = Revision
::newFromId( $s->rev_id
);
3453 if ( empty( $summary ) ) {
3454 if ( $from == '' ) { // no public user name
3455 $summary = wfMsgForContent( 'revertpage-nouser' );
3457 $summary = wfMsgForContent( 'revertpage' );
3461 # Allow the custom summary to use the same args as the default message
3463 $target->getUserText(), $from, $s->rev_id
,
3464 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3465 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3467 $summary = wfMsgReplaceArgs( $summary, $args );
3470 $flags = EDIT_UPDATE
;
3472 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3473 $flags |
= EDIT_MINOR
;
3476 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) ||
$wgUser->isAllowed( 'bot' ) ) ) {
3477 $flags |
= EDIT_FORCE_BOT
;
3480 # Actually store the edit
3481 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3482 if ( !empty( $status->value
['revision'] ) ) {
3483 $revId = $status->value
['revision']->getId();
3488 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3490 $resultDetails = array(
3491 'summary' => $summary,
3492 'current' => $current,
3493 'target' => $target,
3501 * User interface for rollback operations
3503 public function rollback() {
3504 global $wgUser, $wgOut, $wgRequest;
3508 $result = $this->doRollback(
3509 $wgRequest->getVal( 'from' ),
3510 $wgRequest->getText( 'summary' ),
3511 $wgRequest->getVal( 'token' ),
3512 $wgRequest->getBool( 'bot' ),
3516 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3517 $wgOut->rateLimited();
3521 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3522 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3523 $errArray = $result[0];
3524 $errMsg = array_shift( $errArray );
3525 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3527 if ( isset( $details['current'] ) ) {
3528 $current = $details['current'];
3530 if ( $current->getComment() != '' ) {
3531 $wgOut->addWikiMsgArray( 'editcomment', array(
3532 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3539 # Display permissions errors before read-only message -- there's no
3540 # point in misleading the user into thinking the inability to rollback
3541 # is only temporary.
3542 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3543 # array_diff is completely broken for arrays of arrays, sigh.
3544 # Remove any 'readonlytext' error manually.
3546 foreach ( $result as $error ) {
3547 if ( $error != array( 'readonlytext' ) ) {
3551 $wgOut->showPermissionsErrorPage( $out );
3556 if ( $result == array( array( 'readonlytext' ) ) ) {
3557 $wgOut->readOnlyPage();
3562 $current = $details['current'];
3563 $target = $details['target'];
3564 $newId = $details['newid'];
3565 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3566 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3568 if ( $current->getUserText() === '' ) {
3569 $old = wfMsg( 'rev-deleted-user' );
3571 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3572 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3575 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3576 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3577 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3578 $wgOut->returnToMain( false, $this->mTitle
);
3580 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3581 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3582 $de->showDiff( '', '' );
3587 * Do standard deferred updates after page view
3589 public function viewUpdates() {
3590 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3591 if ( wfReadOnly() ) {
3595 # Don't update page view counters on views from bot users (bug 14044)
3596 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3597 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3598 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3601 # Update newtalk / watchlist notification status
3602 $wgUser->clearNotification( $this->mTitle
);
3606 * Prepare text which is about to be saved.
3607 * Returns a stdclass with source, pst and output members
3609 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3610 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3612 return $this->mPreparedEdit
;
3617 if( $user === null ) {
3621 $popts = ParserOptions
::newFromUser( $user );
3622 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3624 $edit = (object)array();
3625 $edit->revid
= $revid;
3626 $edit->newText
= $text;
3627 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3628 $edit->popts
= $this->getParserOptions( true );
3629 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3630 $edit->oldText
= $this->getRawText();
3632 $this->mPreparedEdit
= $edit;
3638 * Do standard deferred updates after page edit.
3639 * Update links tables, site stats, search index and message cache.
3640 * Purges pages that include this page if the text was changed here.
3641 * Every 100th edit, prune the recent changes table.
3644 * @param $text String: New text of the article
3645 * @param $summary String: Edit summary
3646 * @param $minoredit Boolean: Minor edit
3647 * @param $timestamp_of_pagechange String timestamp associated with the page change
3648 * @param $newid Integer: rev_id value of the new revision
3649 * @param $changed Boolean: Whether or not the content actually changed
3650 * @param $user User object: User doing the edit
3652 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User
$user = null ) {
3653 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3655 wfProfileIn( __METHOD__
);
3658 # Be careful not to double-PST: $text is usually already PST-ed once
3659 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3660 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3661 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3663 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3664 $editInfo = $this->mPreparedEdit
;
3667 # Save it to the parser cache
3668 if ( $wgEnableParserCache ) {
3669 $parserCache = ParserCache
::singleton();
3670 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3673 # Update the links tables
3674 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3677 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3679 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3680 if ( 0 == mt_rand( 0, 99 ) ) {
3681 // Flush old entries from the `recentchanges` table; we do this on
3682 // random requests so as to avoid an increase in writes for no good reason
3685 $dbw = wfGetDB( DB_MASTER
);
3686 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3687 $recentchanges = $dbw->tableName( 'recentchanges' );
3688 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3690 $dbw->query( $sql );
3694 $id = $this->getID();
3695 $title = $this->mTitle
->getPrefixedDBkey();
3696 $shortTitle = $this->mTitle
->getDBkey();
3699 wfProfileOut( __METHOD__
);
3703 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3704 array_push( $wgDeferredUpdateList, $u );
3705 $u = new SearchUpdate( $id, $title, $text );
3706 array_push( $wgDeferredUpdateList, $u );
3708 # If this is another user's talk page, update newtalk
3709 # Don't do this if $changed = false otherwise some idiot can null-edit a
3710 # load of user talk pages and piss people off, nor if it's a minor edit
3711 # by a properly-flagged bot.
3712 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3713 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3715 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3716 $other = User
::newFromName( $shortTitle, false );
3718 wfDebug( __METHOD__
. ": invalid username\n" );
3719 } elseif ( User
::isIP( $shortTitle ) ) {
3720 // An anonymous user
3721 $other->setNewtalk( true );
3722 } elseif ( $other->isLoggedIn() ) {
3723 $other->setNewtalk( true );
3725 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3730 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3731 MessageCache
::singleton()->replace( $shortTitle, $text );
3734 wfProfileOut( __METHOD__
);
3738 * Perform article updates on a special page creation.
3740 * @param $rev Revision object
3742 * @todo This is a shitty interface function. Kill it and replace the
3743 * other shitty functions like editUpdates and such so it's not needed
3746 public function createUpdates( $rev ) {
3747 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3748 $this->mTotalAdjustment
= 1;
3749 $this->editUpdates( $rev->getText(), $rev->getComment(),
3750 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3754 * Generate the navigation links when browsing through an article revisions
3755 * It shows the information as:
3756 * Revision as of \<date\>; view current revision
3757 * \<- Previous version | Next Version -\>
3759 * @param $oldid String: revision ID of this article revision
3761 public function setOldSubtitle( $oldid = 0 ) {
3762 global $wgLang, $wgOut, $wgUser, $wgRequest;
3764 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3768 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3770 # Cascade unhide param in links for easy deletion browsing
3771 $extraParams = array();
3772 if ( $wgRequest->getVal( 'unhide' ) ) {
3773 $extraParams['unhide'] = 1;
3776 $revision = Revision
::newFromId( $oldid );
3778 $current = ( $oldid == $this->mLatest
);
3779 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3780 $tddate = $wgLang->date( $this->mTimestamp
, true );
3781 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3782 $sk = $wgUser->getSkin();
3784 ?
wfMsgHtml( 'currentrevisionlink' )
3787 wfMsgHtml( 'currentrevisionlink' ),
3790 array( 'known', 'noclasses' )
3793 ?
wfMsgHtml( 'diff' )
3796 wfMsgHtml( 'diff' ),
3802 array( 'known', 'noclasses' )
3804 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3808 wfMsgHtml( 'previousrevision' ),
3811 'direction' => 'prev',
3814 array( 'known', 'noclasses' )
3816 : wfMsgHtml( 'previousrevision' );
3820 wfMsgHtml( 'diff' ),
3826 array( 'known', 'noclasses' )
3828 : wfMsgHtml( 'diff' );
3829 $nextlink = $current
3830 ?
wfMsgHtml( 'nextrevision' )
3833 wfMsgHtml( 'nextrevision' ),
3836 'direction' => 'next',
3839 array( 'known', 'noclasses' )
3841 $nextdiff = $current
3842 ?
wfMsgHtml( 'diff' )
3845 wfMsgHtml( 'diff' ),
3851 array( 'known', 'noclasses' )
3856 // User can delete revisions or view deleted revisions...
3857 $canHide = $wgUser->isAllowed( 'deleterevision' );
3858 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3859 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3860 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3863 'type' => 'revision',
3864 'target' => $this->mTitle
->getPrefixedDbkey(),
3867 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3872 # Show user links if allowed to see them. If hidden, then show them only if requested...
3873 $userlinks = $sk->revUserTools( $revision, !$unhide );
3875 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3876 ?
'revision-info-current'
3879 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3882 array( 'parseinline', 'replaceafter' ),
3888 $revision->getUser()
3891 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3892 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3894 $wgOut->setSubtitle( $r );
3898 * This function is called right before saving the wikitext,
3899 * so we can do things like signatures and links-in-context.
3901 * @param $text String article contents
3902 * @param $user User object: user doing the edit, $wgUser will be used if
3904 * @param $popts ParserOptions object: parser options, default options for
3905 * the user loaded if null given
3906 * @return string article contents with altered wikitext markup (signatures
3907 * converted, {{subst:}}, templates, etc.)
3909 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3912 if ( $user === null ) {
3917 if ( $popts === null ) {
3918 $popts = ParserOptions
::newFromUser( $user );
3921 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3924 /* Caching functions */
3927 * checkLastModified returns true if it has taken care of all
3928 * output to the client that is necessary for this request.
3929 * (that is, it has sent a cached version of the page)
3931 * @return boolean true if cached version send, false otherwise
3933 protected function tryFileCache() {
3934 static $called = false;
3937 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3942 if ( $this->isFileCacheable() ) {
3943 $cache = new HTMLFileCache( $this->mTitle
);
3944 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3945 wfDebug( "Article::tryFileCache(): about to load file\n" );
3946 $cache->loadFromFileCache();
3949 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3950 ob_start( array( &$cache, 'saveToFileCache' ) );
3953 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3960 * Check if the page can be cached
3963 public function isFileCacheable() {
3966 if ( HTMLFileCache
::useFileCache() ) {
3967 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3968 // Extension may have reason to disable file caching on some pages.
3970 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3978 * Loads page_touched and returns a value indicating if it should be used
3979 * @return boolean true if not a redirect
3981 public function checkTouched() {
3982 if ( !$this->mDataLoaded
) {
3983 $this->loadPageData();
3986 return !$this->mIsRedirect
;
3990 * Get the page_touched field
3991 * @return string containing GMT timestamp
3993 public function getTouched() {
3994 if ( !$this->mDataLoaded
) {
3995 $this->loadPageData();
3998 return $this->mTouched
;
4002 * Get the page_latest field
4003 * @return integer rev_id of current revision
4005 public function getLatest() {
4006 if ( !$this->mDataLoaded
) {
4007 $this->loadPageData();
4010 return (int)$this->mLatest
;
4014 * Edit an article without doing all that other stuff
4015 * The article must already exist; link tables etc
4016 * are not updated, caches are not flushed.
4018 * @param $text String: text submitted
4019 * @param $comment String: comment submitted
4020 * @param $minor Boolean: whereas it's a minor modification
4022 public function quickEdit( $text, $comment = '', $minor = 0 ) {
4023 wfProfileIn( __METHOD__
);
4025 $dbw = wfGetDB( DB_MASTER
);
4026 $revision = new Revision( array(
4027 'page' => $this->getId(),
4029 'comment' => $comment,
4030 'minor_edit' => $minor ?
1 : 0,
4032 $revision->insertOn( $dbw );
4033 $this->updateRevisionOn( $dbw, $revision );
4036 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
4038 wfProfileOut( __METHOD__
);
4042 * The onArticle*() functions are supposed to be a kind of hooks
4043 * which should be called whenever any of the specified actions
4046 * This is a good place to put code to clear caches, for instance.
4048 * This is called on page move and undelete, as well as edit
4050 * @param $title Title object
4052 public static function onArticleCreate( $title ) {
4053 # Update existence markers on article/talk tabs...
4054 if ( $title->isTalkPage() ) {
4055 $other = $title->getSubjectPage();
4057 $other = $title->getTalkPage();
4060 $other->invalidateCache();
4061 $other->purgeSquid();
4063 $title->touchLinks();
4064 $title->purgeSquid();
4065 $title->deleteTitleProtection();
4069 * Clears caches when article is deleted
4071 public static function onArticleDelete( $title ) {
4072 # Update existence markers on article/talk tabs...
4073 if ( $title->isTalkPage() ) {
4074 $other = $title->getSubjectPage();
4076 $other = $title->getTalkPage();
4079 $other->invalidateCache();
4080 $other->purgeSquid();
4082 $title->touchLinks();
4083 $title->purgeSquid();
4086 HTMLFileCache
::clearFileCache( $title );
4089 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
4090 MessageCache
::singleton()->replace( $title->getDBkey(), false );
4094 if ( $title->getNamespace() == NS_FILE
) {
4095 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4096 $update->doUpdate();
4100 if ( $title->getNamespace() == NS_USER_TALK
) {
4101 $user = User
::newFromName( $title->getText(), false );
4102 $user->setNewtalk( false );
4106 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4110 * Purge caches on page update etc
4112 * @param $title Title object
4113 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4115 public static function onArticleEdit( $title ) {
4116 global $wgDeferredUpdateList;
4118 // Invalidate caches of articles which include this page
4119 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4121 // Invalidate the caches of all pages which redirect here
4122 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4124 # Purge squid for this page only
4125 $title->purgeSquid();
4127 # Clear file cache for this page only
4128 HTMLFileCache
::clearFileCache( $title );
4134 * Overriden by ImagePage class, only present here to avoid a fatal error
4135 * Called for ?action=revert
4137 public function revert() {
4139 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4143 * Info about this page
4144 * Called for ?action=info when $wgAllowPageInfo is on.
4146 public function info() {
4147 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4149 if ( !$wgAllowPageInfo ) {
4150 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4154 $page = $this->mTitle
->getSubjectPage();
4156 $wgOut->setPagetitle( $page->getPrefixedText() );
4157 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4158 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4160 if ( !$this->mTitle
->exists() ) {
4161 $wgOut->addHTML( '<div class="noarticletext">' );
4162 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
4163 // This doesn't quite make sense; the user is asking for
4164 // information about the _page_, not the message... -- RC
4165 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
4167 $msg = $wgUser->isLoggedIn()
4169 : 'noarticletextanon';
4170 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4173 $wgOut->addHTML( '</div>' );
4175 $dbr = wfGetDB( DB_SLAVE
);
4177 'wl_title' => $page->getDBkey(),
4178 'wl_namespace' => $page->getNamespace() );
4179 $numwatchers = $dbr->selectField(
4184 $this->getSelectOptions() );
4186 $pageInfo = $this->pageCountInfo( $page );
4187 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4190 //FIXME: unescaped messages
4191 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4192 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4195 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4198 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4201 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4204 $wgOut->addHTML( '</ul>' );
4209 * Return the total number of edits and number of unique editors
4210 * on a given page. If page does not exist, returns false.
4212 * @param $title Title object
4213 * @return mixed array or boolean false
4215 public function pageCountInfo( $title ) {
4216 $id = $title->getArticleId();
4222 $dbr = wfGetDB( DB_SLAVE
);
4223 $rev_clause = array( 'rev_page' => $id );
4224 $edits = $dbr->selectField(
4229 $this->getSelectOptions()
4231 $authors = $dbr->selectField(
4233 'COUNT(DISTINCT rev_user_text)',
4236 $this->getSelectOptions()
4239 return array( 'edits' => $edits, 'authors' => $authors );
4243 * Return a list of templates used by this article.
4244 * Uses the templatelinks table
4246 * @return Array of Title objects
4248 public function getUsedTemplates() {
4250 $id = $this->mTitle
->getArticleID();
4256 $dbr = wfGetDB( DB_SLAVE
);
4257 $res = $dbr->select( array( 'templatelinks' ),
4258 array( 'tl_namespace', 'tl_title' ),
4259 array( 'tl_from' => $id ),
4262 if ( $res !== false ) {
4263 foreach ( $res as $row ) {
4264 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4272 * Returns a list of hidden categories this page is a member of.
4273 * Uses the page_props and categorylinks tables.
4275 * @return Array of Title objects
4277 public function getHiddenCategories() {
4279 $id = $this->mTitle
->getArticleID();
4285 $dbr = wfGetDB( DB_SLAVE
);
4286 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4288 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4289 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4292 if ( $res !== false ) {
4293 foreach ( $res as $row ) {
4294 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4302 * Return an applicable autosummary if one exists for the given edit.
4303 * @param $oldtext String: the previous text of the page.
4304 * @param $newtext String: The submitted text of the page.
4305 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4306 * @return string An appropriate autosummary, or an empty string.
4308 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4311 # Decide what kind of autosummary is needed.
4313 # Redirect autosummaries
4314 $ot = Title
::newFromRedirect( $oldtext );
4315 $rt = Title
::newFromRedirect( $newtext );
4317 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4318 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4321 # New page autosummaries
4322 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4323 # If they're making a new article, give its text, truncated, in the summary.
4325 $truncatedtext = $wgContLang->truncate(
4326 str_replace( "\n", ' ', $newtext ),
4327 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4329 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4332 # Blanking autosummaries
4333 if ( $oldtext != '' && $newtext == '' ) {
4334 return wfMsgForContent( 'autosumm-blank' );
4335 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4336 # Removing more than 90% of the article
4338 $truncatedtext = $wgContLang->truncate(
4340 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4342 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4345 # If we reach this point, there's no applicable autosummary for our case, so our
4346 # autosummary is empty.
4351 * Add the primary page-view wikitext to the output buffer
4352 * Saves the text into the parser cache if possible.
4353 * Updates templatelinks if it is out of date.
4355 * @param $text String
4356 * @param $cache Boolean
4357 * @param $parserOptions mixed ParserOptions object, or boolean false
4359 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4362 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4363 $wgOut->addParserOutput( $this->mParserOutput
);
4367 * This does all the heavy lifting for outputWikitext, except it returns the parser
4368 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4369 * say, embedding thread pages within a discussion system (LiquidThreads)
4371 * @param $text string
4372 * @param $cache boolean
4373 * @param $parserOptions parsing options, defaults to false
4374 * @return string containing parsed output
4376 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4377 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4379 if ( !$parserOptions ) {
4380 $parserOptions = $this->getParserOptions();
4384 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4385 $parserOptions, true, true, $this->getRevIdFetched() );
4390 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4391 $this->mTitle
->getPrefixedDBkey() ) );
4394 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4395 $parserCache = ParserCache
::singleton();
4396 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4399 // Make sure file cache is not used on uncacheable content.
4400 // Output that has magic words in it can still use the parser cache
4401 // (if enabled), though it will generally expire sooner.
4402 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4403 $wgUseFileCache = false;
4406 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4408 return $this->mParserOutput
;
4412 * Get parser options suitable for rendering the primary article wikitext
4413 * @param $canonical boolean Determines that the generated must not depend on user preferences (see bug 14404)
4414 * @return mixed ParserOptions object or boolean false
4416 public function getParserOptions( $canonical = false ) {
4417 global $wgUser, $wgLanguageCode;
4419 if ( !$this->mParserOptions ||
$canonical ) {
4420 $user = !$canonical ?
$wgUser : new User
;
4421 $parserOptions = new ParserOptions( $user );
4422 $parserOptions->setTidy( true );
4423 $parserOptions->enableLimitReport();
4426 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
4427 return $parserOptions;
4429 $this->mParserOptions
= $parserOptions;
4432 // Clone to allow modifications of the return value without affecting
4434 return clone $this->mParserOptions
;
4438 * Updates cascading protections
4440 * @param $parserOutput mixed ParserOptions object, or boolean false
4442 protected function doCascadeProtectionUpdates( $parserOutput ) {
4443 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4447 // templatelinks table may have become out of sync,
4448 // especially if using variable-based transclusions.
4449 // For paranoia, check if things have changed and if
4450 // so apply updates to the database. This will ensure
4451 // that cascaded protections apply as soon as the changes
4454 # Get templates from templatelinks
4455 $id = $this->mTitle
->getArticleID();
4457 $tlTemplates = array();
4459 $dbr = wfGetDB( DB_SLAVE
);
4460 $res = $dbr->select( array( 'templatelinks' ),
4461 array( 'tl_namespace', 'tl_title' ),
4462 array( 'tl_from' => $id ),
4466 foreach ( $res as $row ) {
4467 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4470 # Get templates from parser output.
4471 $poTemplates = array();
4472 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4473 foreach ( $templates as $dbk => $id ) {
4474 $poTemplates["$ns:$dbk"] = true;
4479 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4481 if ( count( $templates_diff ) > 0 ) {
4482 # Whee, link updates time.
4483 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4489 * Update all the appropriate counts in the category table, given that
4490 * we've added the categories $added and deleted the categories $deleted.
4492 * @param $added array The names of categories that were added
4493 * @param $deleted array The names of categories that were deleted
4495 public function updateCategoryCounts( $added, $deleted ) {
4496 $ns = $this->mTitle
->getNamespace();
4497 $dbw = wfGetDB( DB_MASTER
);
4499 # First make sure the rows exist. If one of the "deleted" ones didn't
4500 # exist, we might legitimately not create it, but it's simpler to just
4501 # create it and then give it a negative value, since the value is bogus
4504 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4505 $insertCats = array_merge( $added, $deleted );
4506 if ( !$insertCats ) {
4507 # Okay, nothing to do
4511 $insertRows = array();
4513 foreach ( $insertCats as $cat ) {
4514 $insertRows[] = array(
4515 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4519 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4521 $addFields = array( 'cat_pages = cat_pages + 1' );
4522 $removeFields = array( 'cat_pages = cat_pages - 1' );
4524 if ( $ns == NS_CATEGORY
) {
4525 $addFields[] = 'cat_subcats = cat_subcats + 1';
4526 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4527 } elseif ( $ns == NS_FILE
) {
4528 $addFields[] = 'cat_files = cat_files + 1';
4529 $removeFields[] = 'cat_files = cat_files - 1';
4536 array( 'cat_title' => $added ),
4545 array( 'cat_title' => $deleted ),
4552 * Lightweight method to get the parser output for a page, checking the parser cache
4553 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4554 * consider, so it's not appropriate to use there.
4556 * @since 1.16 (r52326) for LiquidThreads
4558 * @param $oldid mixed integer Revision ID or null
4559 * @return ParserOutput
4561 public function getParserOutput( $oldid = null ) {
4562 global $wgEnableParserCache, $wgUser;
4564 // Should the parser cache be used?
4565 $useParserCache = $wgEnableParserCache &&
4566 $wgUser->getStubThreshold() == 0 &&
4570 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4572 if ( $wgUser->getStubThreshold() ) {
4573 wfIncrStats( 'pcache_miss_stub' );
4576 $parserOutput = false;
4577 if ( $useParserCache ) {
4578 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4581 if ( $parserOutput === false ) {
4582 // Cache miss; parse and output it.
4583 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4585 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4587 return $parserOutput;
4593 class PoolWorkArticleView
extends PoolCounterWork
{
4596 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4597 parent
::__construct( 'ArticleView', $key );
4598 $this->mArticle
= $article;
4599 $this->cacheable
= $useParserCache;
4600 $this->parserOptions
= $parserOptions;
4604 return $this->mArticle
->doViewParse();
4607 function getCachedWork() {
4610 $parserCache = ParserCache
::singleton();
4611 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4613 if ( $this->mArticle
->mParserOutput
!== false ) {
4614 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4615 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4616 # Ensure that UI elements requiring revision ID have
4617 # the correct version information.
4618 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4624 function fallback() {
4625 return $this->mArticle
->tryDirtyCache();
4628 function error( $status ) {
4631 $wgOut->clearHTML(); // for release() errors
4632 $wgOut->enableClientCache( false );
4633 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4635 $errortext = $status->getWikiText( false, 'view-pool-error' );
4636 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );