ff8546f0742690e7c1f084102d08829f74e7720c
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
27 var $mContentLoaded = false; // !<
28 var $mCounter = -1; // !< Not loaded
29 var $mDataLoaded = false; // !<
30 var $mIsRedirect = false; // !<
31 var $mLatest = false; // !<
33 var $mPreparedEdit = false;
38 var $mRedirectedFrom = null;
43 var $mRedirectTarget = null;
48 var $mRedirectUrl = false; // !<
49 var $mRevIdFetched = 0; // !<
54 var $mLastRevision = null;
59 var $mRevision = null;
61 var $mTimestamp = ''; // !<
62 var $mTitle; // !< Title object
63 var $mTouched = '19700101000000'; // !<
78 * Constructor and clear the article
79 * @param $title Reference to a Title object.
80 * @param $oldId Integer revision ID, null to fetch from request, zero for current
82 public function __construct( Title
$title, $oldId = null ) {
83 // @todo FIXME: Does the reference play any role here?
84 $this->mTitle
=& $title;
85 $this->mOldId
= $oldId;
89 * Constructor from an page id
90 * @param $id Int article ID to load
92 public static function newFromID( $id ) {
93 $t = Title
::newFromID( $id );
94 # @todo FIXME: Doesn't inherit right
95 return $t == null ?
null : new self( $t );
96 # return $t == null ? null : new static( $t ); // PHP 5.3
100 * Tell the page view functions that this view was redirected
101 * from another page on the wiki.
102 * @param $from Title object.
104 public function setRedirectedFrom( Title
$from ) {
105 $this->mRedirectedFrom
= $from;
109 * If this page is a redirect, get its target
111 * The target will be fetched from the redirect table if possible.
112 * If this page doesn't have an entry there, call insertRedirect()
113 * @return mixed Title object, or null if this page is not a redirect
115 public function getRedirectTarget() {
116 if ( !$this->mTitle
->isRedirect() ) {
120 if ( $this->mRedirectTarget
!== null ) {
121 return $this->mRedirectTarget
;
124 # Query the redirect table
125 $dbr = wfGetDB( DB_SLAVE
);
126 $row = $dbr->selectRow( 'redirect',
127 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
128 array( 'rd_from' => $this->getID() ),
132 // rd_fragment and rd_interwiki were added later, populate them if empty
133 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
134 return $this->mRedirectTarget
= Title
::makeTitle(
135 $row->rd_namespace
, $row->rd_title
,
136 $row->rd_fragment
, $row->rd_interwiki
);
139 # This page doesn't have an entry in the redirect table
140 return $this->mRedirectTarget
= $this->insertRedirect();
144 * Insert an entry for this page into the redirect table.
146 * Don't call this function directly unless you know what you're doing.
147 * @return Title object or null if not a redirect
149 public function insertRedirect() {
150 // recurse through to only get the final target
151 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
155 $this->insertRedirectEntry( $retval );
160 * Insert or update the redirect table entry for this page to indicate
161 * it redirects to $rt .
162 * @param $rt Title redirect target
164 public function insertRedirectEntry( $rt ) {
165 $dbw = wfGetDB( DB_MASTER
);
166 $dbw->replace( 'redirect', array( 'rd_from' ),
168 'rd_from' => $this->getID(),
169 'rd_namespace' => $rt->getNamespace(),
170 'rd_title' => $rt->getDBkey(),
171 'rd_fragment' => $rt->getFragment(),
172 'rd_interwiki' => $rt->getInterwiki(),
179 * Get the Title object or URL this page redirects to
181 * @return mixed false, Title of in-wiki target, or string with URL
183 public function followRedirect() {
184 return $this->getRedirectURL( $this->getRedirectTarget() );
188 * Get the Title object this text redirects to
190 * @param $text string article content containing redirect info
191 * @return mixed false, Title of in-wiki target, or string with URL
192 * @deprecated since 1.17
194 public function followRedirectText( $text ) {
195 // recurse through to only get the final target
196 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
200 * Get the Title object or URL to use for a redirect. We use Title
201 * objects for same-wiki, non-special redirects and URLs for everything
203 * @param $rt Title Redirect target
204 * @return mixed false, Title object of local target, or string with URL
206 public function getRedirectURL( $rt ) {
208 if ( $rt->getInterwiki() != '' ) {
209 if ( $rt->isLocal() ) {
210 // Offsite wikis need an HTTP redirect.
212 // This can be hard to reverse and may produce loops,
213 // so they may be disabled in the site configuration.
214 $source = $this->mTitle
->getFullURL( 'redirect=no' );
215 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
218 if ( $rt->getNamespace() == NS_SPECIAL
) {
219 // Gotta handle redirects to special pages differently:
220 // Fill the HTTP response "Location" header and ignore
221 // the rest of the page we're on.
223 // This can be hard to reverse, so they may be disabled.
224 if ( $rt->isSpecial( 'Userlogout' ) ) {
227 return $rt->getFullURL();
235 // No or invalid redirect
240 * Get the title object of the article
241 * @return Title object of this page
243 public function getTitle() {
244 return $this->mTitle
;
249 * @todo FIXME: Shouldn't this be public?
252 public function clear() {
253 $this->mDataLoaded
= false;
254 $this->mContentLoaded
= false;
256 $this->mCounter
= -1; # Not loaded
257 $this->mRedirectedFrom
= null; # Title object if set
258 $this->mRedirectTarget
= null; # Title object if set
259 $this->mLastRevision
= null; # Latest revision
260 $this->mTimestamp
= '';
261 $this->mTouched
= '19700101000000';
262 $this->mIsRedirect
= false;
263 $this->mRevIdFetched
= 0;
264 $this->mRedirectUrl
= false;
265 $this->mLatest
= false;
266 $this->mPreparedEdit
= false;
270 * Note that getContent/loadContent do not follow redirects anymore.
271 * If you need to fetch redirectable content easily, try
272 * the shortcut in Article::followRedirect()
274 * This function has side effects! Do not use this function if you
275 * only want the real revision text if any.
277 * @return Return the text of this revision
279 public function getContent() {
282 wfProfileIn( __METHOD__
);
284 if ( $this->getID() === 0 ) {
285 # If this is a MediaWiki:x message, then load the messages
286 # and return the message value for x.
287 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
288 $text = $this->mTitle
->getDefaultMessageText();
289 if ( $text === false ) {
293 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
295 wfProfileOut( __METHOD__
);
299 $this->loadContent();
300 wfProfileOut( __METHOD__
);
302 return $this->mContent
;
307 * Get the text of the current revision. No side-effects...
309 * @return Return the text of the current revision
311 public function getRawText() {
312 // Check process cache for current revision
313 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
314 return $this->mContent
;
317 $rev = Revision
::newFromTitle( $this->mTitle
);
318 $text = $rev ?
$rev->getRawText() : false;
324 * Get the text that needs to be saved in order to undo all revisions
325 * between $undo and $undoafter. Revisions must belong to the same page,
326 * must exist and must not be deleted
327 * @param $undo Revision
328 * @param $undoafter Revision Must be an earlier revision than $undo
329 * @return mixed string on success, false on failure
331 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
332 $currentRev = Revision
::newFromTitle( $this->mTitle
);
333 if ( !$currentRev ) {
334 return false; // no page
336 $undo_text = $undo->getText();
337 $undoafter_text = $undoafter->getText();
338 $cur_text = $currentRev->getText();
340 if ( $cur_text == $undo_text ) {
341 # No use doing a merge if it's just a straight revert.
342 return $undoafter_text;
347 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
355 * @return int The oldid of the article that is to be shown, 0 for the
358 public function getOldID() {
359 if ( is_null( $this->mOldId
) ) {
360 $this->mOldId
= $this->getOldIDFromRequest();
363 return $this->mOldId
;
367 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
369 * @return int The old id for the request
371 public function getOldIDFromRequest() {
374 $this->mRedirectUrl
= false;
376 $oldid = $wgRequest->getVal( 'oldid' );
378 if ( isset( $oldid ) ) {
379 $oldid = intval( $oldid );
380 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
381 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
385 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
387 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
388 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
403 * Load the revision (including text) into this object
405 function loadContent() {
406 if ( $this->mContentLoaded
) {
410 wfProfileIn( __METHOD__
);
412 $this->fetchContent( $this->getOldID() );
414 wfProfileOut( __METHOD__
);
418 * Return the list of revision fields that should be selected to create
421 public static function selectFields() {
438 * Fetch a page record with the given conditions
439 * @param $dbr DatabaseBase object
440 * @param $conditions Array
441 * @return mixed Database result resource, or false on failure
443 protected function pageData( $dbr, $conditions ) {
444 $fields = self
::selectFields();
446 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
448 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
450 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
456 * Fetch a page record matching the Title object's namespace and title
457 * using a sanitized title string
459 * @param $dbr DatabaseBase object
460 * @param $title Title object
461 * @return mixed Database result resource, or false on failure
463 protected function pageDataFromTitle( $dbr, $title ) {
464 return $this->pageData( $dbr, array(
465 'page_namespace' => $title->getNamespace(),
466 'page_title' => $title->getDBkey() ) );
470 * Fetch a page record matching the requested ID
472 * @param $dbr DatabaseBase
474 * @return mixed Database result resource, or false on failure
476 protected function pageDataFromId( $dbr, $id ) {
477 return $this->pageData( $dbr, array( 'page_id' => $id ) );
481 * Set the general counter, title etc data loaded from
484 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
486 public function loadPageData( $data = 'fromdb' ) {
487 if ( $data === 'fromdb' ) {
488 $dbr = wfGetDB( DB_SLAVE
);
489 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
492 $lc = LinkCache
::singleton();
495 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
497 $this->mTitle
->mArticleID
= intval( $data->page_id
);
499 # Old-fashioned restrictions
500 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
502 $this->mCounter
= intval( $data->page_counter
);
503 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
504 $this->mIsRedirect
= intval( $data->page_is_redirect
);
505 $this->mLatest
= intval( $data->page_latest
);
507 $lc->addBadLinkObj( $this->mTitle
);
508 $this->mTitle
->mArticleID
= 0;
511 $this->mDataLoaded
= true;
515 * Get text of an article from database
516 * Does *NOT* follow redirects.
518 * @param $oldid Int: 0 for whatever the latest revision is
519 * @return mixed string containing article contents, or false if null
521 function fetchContent( $oldid = 0 ) {
522 if ( $this->mContentLoaded
) {
523 return $this->mContent
;
526 # Pre-fill content with error message so that if something
527 # fails we'll have something telling us what we intended.
528 $t = $this->mTitle
->getPrefixedText();
529 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
530 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
533 $revision = Revision
::newFromId( $oldid );
534 if ( $revision === null ) {
535 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
539 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
540 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
543 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
547 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
548 $this->loadPageData( $data );
551 if ( !$this->mDataLoaded
) {
552 $this->loadPageData();
555 if ( $this->mLatest
=== false ) {
556 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
560 $revision = Revision
::newFromId( $this->mLatest
);
561 if ( $revision === null ) {
562 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
567 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
568 // We should instead work with the Revision object when we need it...
569 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
571 if ( $revision->getId() == $this->mLatest
) {
572 $this->setLastEdit( $revision );
575 $this->mRevIdFetched
= $revision->getId();
576 $this->mContentLoaded
= true;
577 $this->mRevision
=& $revision;
579 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
581 return $this->mContent
;
586 * @deprecated since 1.18
588 public function forUpdate() {
589 wfDeprecated( __METHOD__
);
593 * @return int Page ID
595 public function getID() {
596 return $this->mTitle
->getArticleID();
600 * @return bool Whether or not the page exists in the database
602 public function exists() {
603 return $this->getId() > 0;
607 * Check if this page is something we're going to be showing
608 * some sort of sensible content for. If we return false, page
609 * views (plain action=view) will return an HTTP 404 response,
610 * so spiders and robots can know they're following a bad link.
614 public function hasViewableContent() {
615 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
619 * @return int The view count for the page
621 public function getCount() {
622 if ( -1 == $this->mCounter
) {
623 $id = $this->getID();
628 $dbr = wfGetDB( DB_SLAVE
);
629 $this->mCounter
= $dbr->selectField( 'page',
631 array( 'page_id' => $id ),
637 return $this->mCounter
;
641 * Determine whether a page would be suitable for being counted as an
642 * article in the site_stats table based on the title & its content
644 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
645 * if false, the current database state will be used
648 public function isCountable( $editInfo = false ) {
649 global $wgArticleCountMethod;
651 if ( !$this->mTitle
->isContentPage() ) {
655 $text = $editInfo ?
$editInfo->pst
: false;
657 if ( $this->isRedirect( $text ) ) {
661 switch ( $wgArticleCountMethod ) {
665 if ( $text === false ) {
666 $text = $this->getRawText();
668 return in_string( ',', $text );
671 // ParserOutput::getLinks() is a 2D array of page links, so
672 // to be really correct we would need to recurse in the array
673 // but the main array should only have items in it if there are
675 return (bool)count( $editInfo->output
->getLinks() );
677 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
678 array( 'pl_from' => $this->getId() ), __METHOD__
);
684 * Tests if the article text represents a redirect
686 * @param $text mixed string containing article contents, or boolean
689 public function isRedirect( $text = false ) {
690 if ( $text === false ) {
691 if ( !$this->mDataLoaded
) {
692 $this->loadPageData();
695 return (bool)$this->mIsRedirect
;
697 return Title
::newFromRedirect( $text ) !== null;
702 * Returns true if the currently-referenced revision is the current edit
703 * to this page (and it exists).
706 public function isCurrent() {
707 # If no oldid, this is the current version.
708 if ( $this->getOldID() == 0 ) {
712 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
716 * Loads everything except the text
717 * This isn't necessary for all uses, so it's only done if needed.
719 protected function loadLastEdit() {
720 if ( $this->mLastRevision
!== null ) {
721 return; // already loaded
724 # New or non-existent articles have no user information
725 $id = $this->getID();
730 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
732 $this->setLastEdit( $revision );
737 * Set the latest revision
739 protected function setLastEdit( Revision
$revision ) {
740 $this->mLastRevision
= $revision;
741 $this->mTimestamp
= $revision->getTimestamp();
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();
752 return wfTimestamp( TS_MW
, $this->mTimestamp
);
756 * @param $audience Integer: one of:
757 * Revision::FOR_PUBLIC to be displayed to all users
758 * Revision::FOR_THIS_USER to be displayed to $wgUser
759 * Revision::RAW get the text regardless of permissions
760 * @return int user ID for the user that made the last article revision
762 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
763 $this->loadLastEdit();
764 if ( $this->mLastRevision
) {
765 return $this->mLastRevision
->getUser( $audience );
772 * @param $audience Integer: one of:
773 * Revision::FOR_PUBLIC to be displayed to all users
774 * Revision::FOR_THIS_USER to be displayed to $wgUser
775 * Revision::RAW get the text regardless of permissions
776 * @return string username of the user that made the last article revision
778 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
779 $this->loadLastEdit();
780 if ( $this->mLastRevision
) {
781 return $this->mLastRevision
->getUserText( $audience );
788 * @param $audience Integer: one of:
789 * Revision::FOR_PUBLIC to be displayed to all users
790 * Revision::FOR_THIS_USER to be displayed to $wgUser
791 * Revision::RAW get the text regardless of permissions
792 * @return string Comment stored for the last article revision
794 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
795 $this->loadLastEdit();
796 if ( $this->mLastRevision
) {
797 return $this->mLastRevision
->getComment( $audience );
804 * Returns true if last revision was marked as "minor edit"
806 * @return boolean Minor edit indicator for the last article revision.
808 public function getMinorEdit() {
809 $this->loadLastEdit();
810 if ( $this->mLastRevision
) {
811 return $this->mLastRevision
->isMinor();
818 * Use this to fetch the rev ID used on page views
820 * @return int revision ID of last article revision
822 public function getRevIdFetched() {
823 if ( $this->mRevIdFetched
) {
824 return $this->mRevIdFetched
;
826 return $this->getLatest();
831 * Get a list of users who have edited this article, not including the user who made
832 * the most recent revision, which you can get from $article->getUser() if you want it
835 public function getContributors() {
836 # @todo FIXME: This is expensive; cache this info somewhere.
838 $dbr = wfGetDB( DB_SLAVE
);
839 $userTable = $dbr->tableName( 'user' );
841 if ( $dbr->implicitGroupby() ) {
842 $realNameField = 'user_real_name';
844 $realNameField = 'FIRST(user_real_name) AS user_real_name';
847 $tables = array( 'revision', 'user' );
850 'rev_user as user_id',
851 'rev_user_text AS user_name',
853 'MAX(rev_timestamp) AS timestamp',
856 $conds = array( 'rev_page' => $this->getId() );
858 // The user who made the top revision gets credited as "this page was last edited by
859 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
860 $user = $this->getUser();
862 $conds[] = "rev_user != $user";
864 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
867 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
870 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
874 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
875 'ORDER BY' => 'timestamp DESC',
878 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
879 return new UserArrayFromResult( $res );
883 * This is the default action of the index.php entry point: just view the
884 * page of the given title.
886 public function view() {
887 global $wgUser, $wgOut, $wgRequest, $wgParser;
888 global $wgUseFileCache, $wgUseETag;
890 wfProfileIn( __METHOD__
);
892 # Get variables from query string
893 $oldid = $this->getOldID();
895 # getOldID may want us to redirect somewhere else
896 if ( $this->mRedirectUrl
) {
897 $wgOut->redirect( $this->mRedirectUrl
);
898 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
899 wfProfileOut( __METHOD__
);
904 $wgOut->setArticleFlag( true );
905 # Set page title (may be overridden by DISPLAYTITLE)
906 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
908 # If we got diff in the query, we want to see a diff page instead of the article.
909 if ( $wgRequest->getCheck( 'diff' ) ) {
910 wfDebug( __METHOD__
. ": showing diff page\n" );
911 $this->showDiffPage();
912 wfProfileOut( __METHOD__
);
917 # Allow frames by default
918 $wgOut->allowClickjacking();
920 $parserCache = ParserCache
::singleton();
922 $parserOptions = $this->getParserOptions();
923 # Render printable version, use printable version cache
924 if ( $wgOut->isPrintable() ) {
925 $parserOptions->setIsPrintable( true );
926 $parserOptions->setEditSection( false );
927 } else if ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
928 $parserOptions->setEditSection( false );
931 # Try client and file cache
932 if ( $oldid === 0 && $this->checkTouched() ) {
934 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
937 # Is it client cached?
938 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
939 wfDebug( __METHOD__
. ": done 304\n" );
940 wfProfileOut( __METHOD__
);
944 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
945 wfDebug( __METHOD__
. ": done file cache\n" );
946 # tell wgOut that output is taken care of
948 $this->viewUpdates();
949 wfProfileOut( __METHOD__
);
955 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
956 $parserOptions->setEditSection( false );
959 # Should the parser cache be used?
960 $useParserCache = $this->useParserCache( $oldid );
961 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
962 if ( $wgUser->getStubThreshold() ) {
963 wfIncrStats( 'pcache_miss_stub' );
966 $wasRedirected = $this->showRedirectedFromHeader();
967 $this->showNamespaceHeader();
969 # Iterate through the possible ways of constructing the output text.
970 # Keep going until $outputDone is set, or we run out of things to do.
973 $this->mParserOutput
= false;
975 while ( !$outputDone && ++
$pass ) {
978 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
981 # Try the parser cache
982 if ( $useParserCache ) {
983 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
985 if ( $this->mParserOutput
!== false ) {
986 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
987 $wgOut->addParserOutput( $this->mParserOutput
);
988 # Ensure that UI elements requiring revision ID have
989 # the correct version information.
990 $wgOut->setRevisionId( $this->mLatest
);
996 $text = $this->getContent();
997 if ( $text === false ||
$this->getID() == 0 ) {
998 wfDebug( __METHOD__
. ": showing missing article\n" );
999 $this->showMissingArticle();
1000 wfProfileOut( __METHOD__
);
1004 # Another whitelist check in case oldid is altering the title
1005 if ( !$this->mTitle
->userCanRead() ) {
1006 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
1007 $wgOut->loginToUse();
1010 wfProfileOut( __METHOD__
);
1014 # Are we looking at an old revision
1015 if ( $oldid && !is_null( $this->mRevision
) ) {
1016 $this->setOldSubtitle( $oldid );
1018 if ( !$this->showDeletedRevisionHeader() ) {
1019 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
1020 wfProfileOut( __METHOD__
);
1024 # If this "old" version is the current, then try the parser cache...
1025 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
1026 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1027 if ( $this->mParserOutput
) {
1028 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
1029 $wgOut->addParserOutput( $this->mParserOutput
);
1030 $wgOut->setRevisionId( $this->mLatest
);
1037 # Ensure that UI elements requiring revision ID have
1038 # the correct version information.
1039 $wgOut->setRevisionId( $this->getRevIdFetched() );
1041 # Pages containing custom CSS or JavaScript get special treatment
1042 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1043 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1044 $this->showCssOrJsPage();
1047 $rt = Title
::newFromRedirectArray( $text );
1049 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1050 # Viewing a redirect page (e.g. with parameter redirect=no)
1051 # Don't append the subtitle if this was an old revision
1052 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1053 # Parse just to get categories, displaytitle, etc.
1054 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1055 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1061 # Run the parse, protected by a pool counter
1062 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1064 $key = $parserCache->getKey( $this, $parserOptions );
1065 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1067 if ( !$poolArticleView->execute() ) {
1068 # Connection or timeout error
1069 wfProfileOut( __METHOD__
);
1075 # Should be unreachable, but just in case...
1081 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1082 if ( $this->mParserOutput
) {
1083 $titleText = $this->mParserOutput
->getTitleText();
1085 if ( strval( $titleText ) !== '' ) {
1086 $wgOut->setPageTitle( $titleText );
1090 # For the main page, overwrite the <title> element with the con-
1091 # tents of 'pagetitle-view-mainpage' instead of the default (if
1092 # that's not empty).
1093 # This message always exists because it is in the i18n files
1094 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1095 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1096 if ( !$msg->isDisabled() ) {
1097 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1101 # Now that we've filled $this->mParserOutput, we know whether
1102 # there are any __NOINDEX__ tags on the page
1103 $policy = $this->getRobotPolicy( 'view' );
1104 $wgOut->setIndexPolicy( $policy['index'] );
1105 $wgOut->setFollowPolicy( $policy['follow'] );
1107 $this->showViewFooter();
1108 $this->viewUpdates();
1109 wfProfileOut( __METHOD__
);
1113 * Show a diff page according to current request variables. For use within
1114 * Article::view() only, other callers should use the DifferenceEngine class.
1116 public function showDiffPage() {
1117 global $wgRequest, $wgUser;
1119 $diff = $wgRequest->getVal( 'diff' );
1120 $rcid = $wgRequest->getVal( 'rcid' );
1121 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1122 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1123 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1124 $oldid = $this->getOldID();
1126 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1127 // DifferenceEngine directly fetched the revision:
1128 $this->mRevIdFetched
= $de->mNewid
;
1129 $de->showDiffPage( $diffOnly );
1131 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1132 # Run view updates for current revision only
1133 $this->viewUpdates();
1138 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1139 * Article::view() only.
1141 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1144 protected function showCssOrJsPage() {
1147 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1149 // Give hooks a chance to customise the output
1150 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1151 // Wrap the whole lot in a <pre> and don't parse
1153 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1154 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1155 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1156 $wgOut->addHTML( "\n</pre>\n" );
1161 * Get the robot policy to be used for the current view
1162 * @param $action String the action= GET parameter
1163 * @return Array the policy that should be set
1164 * TODO: actions other than 'view'
1166 public function getRobotPolicy( $action ) {
1167 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1168 global $wgDefaultRobotPolicy, $wgRequest;
1170 $ns = $this->mTitle
->getNamespace();
1172 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1173 # Don't index user and user talk pages for blocked users (bug 11443)
1174 if ( !$this->mTitle
->isSubpage() ) {
1175 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1177 'index' => 'noindex',
1178 'follow' => 'nofollow'
1184 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1185 # Non-articles (special pages etc), and old revisions
1187 'index' => 'noindex',
1188 'follow' => 'nofollow'
1190 } elseif ( $wgOut->isPrintable() ) {
1191 # Discourage indexing of printable versions, but encourage following
1193 'index' => 'noindex',
1194 'follow' => 'follow'
1196 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1197 # For ?curid=x urls, disallow indexing
1199 'index' => 'noindex',
1200 'follow' => 'follow'
1204 # Otherwise, construct the policy based on the various config variables.
1205 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1207 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1208 # Honour customised robot policies for this namespace
1209 $policy = array_merge(
1211 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1214 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1215 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1216 # a final sanity check that we have really got the parser output.
1217 $policy = array_merge(
1219 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1223 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1224 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1225 $policy = array_merge(
1227 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1235 * Converts a String robot policy into an associative array, to allow
1236 * merging of several policies using array_merge().
1237 * @param $policy Mixed, returns empty array on null/false/'', transparent
1238 * to already-converted arrays, converts String.
1239 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1241 public static function formatRobotPolicy( $policy ) {
1242 if ( is_array( $policy ) ) {
1244 } elseif ( !$policy ) {
1248 $policy = explode( ',', $policy );
1249 $policy = array_map( 'trim', $policy );
1252 foreach ( $policy as $var ) {
1253 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1254 $arr['index'] = $var;
1255 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1256 $arr['follow'] = $var;
1264 * If this request is a redirect view, send "redirected from" subtitle to
1265 * $wgOut. Returns true if the header was needed, false if this is not a
1266 * redirect view. Handles both local and remote redirects.
1270 public function showRedirectedFromHeader() {
1271 global $wgOut, $wgRequest, $wgRedirectSources;
1273 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1275 if ( isset( $this->mRedirectedFrom
) ) {
1276 // This is an internally redirected page view.
1277 // We'll need a backlink to the source page for navigation.
1278 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1279 $redir = Linker
::link(
1280 $this->mRedirectedFrom
,
1283 array( 'redirect' => 'no' ),
1284 array( 'known', 'noclasses' )
1287 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1288 $wgOut->setSubtitle( $s );
1290 // Set the fragment if one was specified in the redirect
1291 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1292 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1293 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1296 // Add a <link rel="canonical"> tag
1297 $wgOut->addLink( array( 'rel' => 'canonical',
1298 'href' => $this->mTitle
->getLocalURL() )
1303 } elseif ( $rdfrom ) {
1304 // This is an externally redirected view, from some other wiki.
1305 // If it was reported from a trusted site, supply a backlink.
1306 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1307 $redir = Linker
::makeExternalLink( $rdfrom, $rdfrom );
1308 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1309 $wgOut->setSubtitle( $s );
1319 * Show a header specific to the namespace currently being viewed, like
1320 * [[MediaWiki:Talkpagetext]]. For Article::view().
1322 public function showNamespaceHeader() {
1325 if ( $this->mTitle
->isTalkPage() ) {
1326 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1327 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1333 * Show the footer section of an ordinary page view
1335 public function showViewFooter() {
1336 global $wgOut, $wgUseTrackbacks;
1338 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1339 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1340 $wgOut->addWikiMsg( 'anontalkpagetext' );
1343 # If we have been passed an &rcid= parameter, we want to give the user a
1344 # chance to mark this new article as patrolled.
1345 $this->showPatrolFooter();
1348 if ( $wgUseTrackbacks ) {
1349 $this->addTrackbacks();
1352 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1357 * If patrol is possible, output a patrol UI box. This is called from the
1358 * footer section of ordinary page views. If patrol is not possible or not
1359 * desired, does nothing.
1361 public function showPatrolFooter() {
1362 global $wgOut, $wgRequest, $wgUser;
1364 $rcid = $wgRequest->getVal( 'rcid' );
1366 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1370 $token = $wgUser->editToken( $rcid );
1371 $wgOut->preventClickjacking();
1374 "<div class='patrollink'>" .
1376 'markaspatrolledlink',
1379 wfMsgHtml( 'markaspatrolledtext' ),
1382 'action' => 'markpatrolled',
1386 array( 'known', 'noclasses' )
1394 * Show the error text for a missing article. For articles in the MediaWiki
1395 * namespace, show the default message text. To be called from Article::view().
1397 public function showMissingArticle() {
1398 global $wgOut, $wgRequest, $wgUser;
1400 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1401 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1402 $parts = explode( '/', $this->mTitle
->getText() );
1403 $rootPart = $parts[0];
1404 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1405 $ip = User
::isIP( $rootPart );
1407 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1408 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1409 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1410 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1411 LogEventsList
::showLogExtract(
1414 $user->getUserPage()->getPrefixedText(),
1418 'showIfEmpty' => false,
1420 'blocked-notice-logextract',
1421 $user->getName() # Support GENDER in notice
1428 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1430 # Show delete and move logs
1431 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1433 'conds' => array( "log_action != 'revision'" ),
1434 'showIfEmpty' => false,
1435 'msgKey' => array( 'moveddeleted-notice' ) )
1438 # Show error message
1439 $oldid = $this->getOldID();
1441 $text = wfMsgNoTrans( 'missing-article',
1442 $this->mTitle
->getPrefixedText(),
1443 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1444 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1445 // Use the default message text
1446 $text = $this->mTitle
->getDefaultMessageText();
1448 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1449 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1450 $errors = array_merge( $createErrors, $editErrors );
1452 if ( !count( $errors ) ) {
1453 $text = wfMsgNoTrans( 'noarticletext' );
1455 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1458 $text = "<div class='noarticletext'>\n$text\n</div>";
1460 if ( !$this->hasViewableContent() ) {
1461 // If there's no backing content, send a 404 Not Found
1462 // for better machine handling of broken links.
1463 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1466 $wgOut->addWikiText( $text );
1470 * If the revision requested for view is deleted, check permissions.
1471 * Send either an error message or a warning header to $wgOut.
1473 * @return boolean true if the view is allowed, false if not.
1475 public function showDeletedRevisionHeader() {
1476 global $wgOut, $wgRequest;
1478 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1483 // If the user is not allowed to see it...
1484 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1485 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1486 'rev-deleted-text-permission' );
1489 // If the user needs to confirm that they want to see it...
1490 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1491 # Give explanation and add a link to view the revision...
1492 $oldid = intval( $this->getOldID() );
1493 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1494 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1495 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1496 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1497 array( $msg, $link ) );
1500 // We are allowed to see...
1502 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1503 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1504 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1511 * Should the parser cache be used?
1515 public function useParserCache( $oldid ) {
1516 global $wgUser, $wgEnableParserCache;
1518 return $wgEnableParserCache
1519 && $wgUser->getStubThreshold() == 0
1522 && !$this->mTitle
->isCssOrJsPage()
1523 && !$this->mTitle
->isCssJsSubpage();
1527 * Execute the uncached parse for action=view
1529 public function doViewParse() {
1532 $oldid = $this->getOldID();
1533 $parserOptions = $this->getParserOptions();
1535 # Render printable version, use printable version cache
1536 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1538 # Don't show section-edit links on old revisions... this way lies madness.
1539 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1540 $parserOptions->setEditSection( false );
1543 $useParserCache = $this->useParserCache( $oldid );
1544 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1550 * Try to fetch an expired entry from the parser cache. If it is present,
1551 * output it and return true. If it is not present, output nothing and
1552 * return false. This is used as a callback function for
1553 * PoolCounter::executeProtected().
1557 public function tryDirtyCache() {
1559 $parserCache = ParserCache
::singleton();
1560 $options = $this->getParserOptions();
1562 if ( $wgOut->isPrintable() ) {
1563 $options->setIsPrintable( true );
1564 $options->setEditSection( false );
1567 $output = $parserCache->getDirty( $this, $options );
1570 wfDebug( __METHOD__
. ": sending dirty output\n" );
1571 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1572 $wgOut->setSquidMaxage( 0 );
1573 $this->mParserOutput
= $output;
1574 $wgOut->addParserOutput( $output );
1575 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1579 wfDebugLog( 'dirty', "dirty missing\n" );
1580 wfDebug( __METHOD__
. ": no dirty cache\n" );
1589 * @param $target Title|Array of destination(s) to redirect
1590 * @param $appendSubtitle Boolean [optional]
1591 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1592 * @return string containing HMTL with redirect link
1594 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1595 global $wgOut, $wgContLang, $wgStylePath;
1597 if ( !is_array( $target ) ) {
1598 $target = array( $target );
1601 $imageDir = $wgContLang->getDir();
1603 if ( $appendSubtitle ) {
1604 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1607 // the loop prepends the arrow image before the link, so the first case needs to be outside
1608 $title = array_shift( $target );
1610 if ( $forceKnown ) {
1611 $link = Linker
::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1613 $link = Linker
::link( $title, htmlspecialchars( $title->getFullText() ) );
1616 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1617 $alt = $wgContLang->isRTL() ?
'←' : '→';
1618 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1619 foreach ( $target as $rt ) {
1620 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1621 if ( $forceKnown ) {
1622 $link .= Linker
::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1624 $link .= Linker
::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1628 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1629 return '<div class="redirectMsg">' .
1630 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1631 '<span class="redirectText">' . $link . '</span></div>';
1635 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1637 public function addTrackbacks() {
1640 $dbr = wfGetDB( DB_SLAVE
);
1641 $tbs = $dbr->select( 'trackbacks',
1642 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1643 array( 'tb_page' => $this->getID() )
1646 if ( !$dbr->numRows( $tbs ) ) {
1650 $wgOut->preventClickjacking();
1653 foreach ( $tbs as $o ) {
1656 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1657 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1658 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1659 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1663 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1671 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1675 * Removes trackback record for current article from trackbacks table
1677 public function deletetrackback() {
1678 global $wgRequest, $wgOut;
1680 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1681 $wgOut->addWikiMsg( 'sessionfailure' );
1686 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
1688 if ( count( $permission_errors ) ) {
1689 $wgOut->showPermissionsErrorPage( $permission_errors );
1694 $db = wfGetDB( DB_MASTER
);
1695 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1697 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1698 $this->mTitle
->invalidateCache();
1702 * Handle action=render
1705 public function render() {
1708 $wgOut->setArticleBodyOnly( true );
1713 * Handle action=purge
1715 public function purge() {
1716 return Action
::factory( 'purge', $this )->show();
1720 * Perform the actions of a page purging
1722 public function doPurge() {
1725 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1729 // Invalidate the cache
1730 $this->mTitle
->invalidateCache();
1733 if ( $wgUseSquid ) {
1734 // Commit the transaction before the purge is sent
1735 $dbw = wfGetDB( DB_MASTER
);
1739 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1740 $update->doUpdate();
1743 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1744 if ( $this->getID() == 0 ) {
1747 $text = $this->getRawText();
1750 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1755 * Insert a new empty page record for this article.
1756 * This *must* be followed up by creating a revision
1757 * and running $this->updateRevisionOn( ... );
1758 * or else the record will be left in a funky state.
1759 * Best if all done inside a transaction.
1761 * @param $dbw DatabaseBase
1762 * @return int The newly created page_id key, or false if the title already existed
1765 public function insertOn( $dbw ) {
1766 wfProfileIn( __METHOD__
);
1768 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1769 $dbw->insert( 'page', array(
1770 'page_id' => $page_id,
1771 'page_namespace' => $this->mTitle
->getNamespace(),
1772 'page_title' => $this->mTitle
->getDBkey(),
1773 'page_counter' => 0,
1774 'page_restrictions' => '',
1775 'page_is_redirect' => 0, # Will set this shortly...
1777 'page_random' => wfRandom(),
1778 'page_touched' => $dbw->timestamp(),
1779 'page_latest' => 0, # Fill this in shortly...
1780 'page_len' => 0, # Fill this in shortly...
1781 ), __METHOD__
, 'IGNORE' );
1783 $affected = $dbw->affectedRows();
1786 $newid = $dbw->insertId();
1787 $this->mTitle
->resetArticleID( $newid );
1789 wfProfileOut( __METHOD__
);
1791 return $affected ?
$newid : false;
1795 * Update the page record to point to a newly saved revision.
1797 * @param $dbw DatabaseBase: object
1798 * @param $revision Revision: For ID number, and text used to set
1799 length and redirect status fields
1800 * @param $lastRevision Integer: if given, will not overwrite the page field
1801 * when different from the currently set value.
1802 * Giving 0 indicates the new page flag should be set
1804 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1805 * removing rows in redirect table.
1806 * @return bool true on success, false on failure
1809 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1810 wfProfileIn( __METHOD__
);
1812 $text = $revision->getText();
1813 $rt = Title
::newFromRedirectRecurse( $text );
1815 $conditions = array( 'page_id' => $this->getId() );
1817 if ( !is_null( $lastRevision ) ) {
1818 # An extra check against threads stepping on each other
1819 $conditions['page_latest'] = $lastRevision;
1822 $dbw->update( 'page',
1824 'page_latest' => $revision->getId(),
1825 'page_touched' => $dbw->timestamp(),
1826 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1827 'page_is_redirect' => $rt !== null ?
1 : 0,
1828 'page_len' => strlen( $text ),
1833 $result = $dbw->affectedRows() != 0;
1835 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1838 wfProfileOut( __METHOD__
);
1843 * Add row to the redirect table if this is a redirect, remove otherwise.
1845 * @param $dbw DatabaseBase
1846 * @param $redirectTitle Title object pointing to the redirect target,
1847 * or NULL if this is not a redirect
1848 * @param $lastRevIsRedirect If given, will optimize adding and
1849 * removing rows in redirect table.
1850 * @return bool true on success, false on failure
1853 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1854 // Always update redirects (target link might have changed)
1855 // Update/Insert if we don't know if the last revision was a redirect or not
1856 // Delete if changing from redirect to non-redirect
1857 $isRedirect = !is_null( $redirectTitle );
1859 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1863 wfProfileIn( __METHOD__
);
1864 if ( $isRedirect ) {
1865 $this->insertRedirectEntry( $redirectTitle );
1867 // This is not a redirect, remove row from redirect table
1868 $where = array( 'rd_from' => $this->getId() );
1869 $dbw->delete( 'redirect', $where, __METHOD__
);
1872 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1873 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1875 wfProfileOut( __METHOD__
);
1877 return ( $dbw->affectedRows() != 0 );
1881 * If the given revision is newer than the currently set page_latest,
1882 * update the page record. Otherwise, do nothing.
1884 * @param $dbw Database object
1885 * @param $revision Revision object
1888 public function updateIfNewerOn( &$dbw, $revision ) {
1889 wfProfileIn( __METHOD__
);
1891 $row = $dbw->selectRow(
1892 array( 'revision', 'page' ),
1893 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1895 'page_id' => $this->getId(),
1896 'page_latest=rev_id' ),
1900 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1901 wfProfileOut( __METHOD__
);
1904 $prev = $row->rev_id
;
1905 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1907 # No or missing previous revision; mark the page as new
1909 $lastRevIsRedirect = null;
1912 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1914 wfProfileOut( __METHOD__
);
1919 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1920 * @param $text String: new text of the section
1921 * @param $summary String: new section's subject, only if $section is 'new'
1922 * @param $edittime String: revision timestamp or null to use the current revision
1923 * @return string Complete article text, or null if error
1925 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1926 wfProfileIn( __METHOD__
);
1928 if ( strval( $section ) == '' ) {
1929 // Whole-page edit; let the whole text through
1931 if ( is_null( $edittime ) ) {
1932 $rev = Revision
::newFromTitle( $this->mTitle
);
1934 $dbw = wfGetDB( DB_MASTER
);
1935 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1939 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1940 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1941 wfProfileOut( __METHOD__
);
1945 $oldtext = $rev->getText();
1947 if ( $section == 'new' ) {
1948 # Inserting a new section
1949 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1950 $text = strlen( trim( $oldtext ) ) > 0
1951 ?
"{$oldtext}\n\n{$subject}{$text}"
1952 : "{$subject}{$text}";
1954 # Replacing an existing section; roll out the big guns
1957 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1961 wfProfileOut( __METHOD__
);
1966 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1968 * @return Int updated $flags
1970 function checkFlags( $flags ) {
1971 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1972 if ( $this->mTitle
->getArticleID() ) {
1973 $flags |
= EDIT_UPDATE
;
1985 * Change an existing article or create a new article. Updates RC and all necessary caches,
1986 * optionally via the deferred update array.
1988 * $wgUser must be set before calling this function.
1990 * @param $text String: new text
1991 * @param $summary String: edit summary
1992 * @param $flags Integer bitfield:
1994 * Article is known or assumed to be non-existent, create a new one
1996 * Article is known or assumed to be pre-existing, update it
1998 * Mark this edit minor, if the user is allowed to do so
2000 * Do not log the change in recentchanges
2002 * Mark the edit a "bot" edit regardless of user rights
2003 * EDIT_DEFER_UPDATES
2004 * Defer some of the updates until the end of index.php
2006 * Fill in blank summaries with generated text where possible
2008 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2009 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2010 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2011 * edit-already-exists error will be returned. These two conditions are also possible with
2012 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2014 * @param $baseRevId the revision ID this edit was based off, if any
2015 * @param $user User (optional), $wgUser will be used if not passed
2017 * @return Status object. Possible errors:
2018 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2019 * edit-gone-missing: In update mode, but the article didn't exist
2020 * edit-conflict: In update mode, the article changed unexpectedly
2021 * edit-no-change: Warning that the text was the same as before
2022 * edit-already-exists: In creation mode, but the article already exists
2024 * Extensions may define additional errors.
2026 * $return->value will contain an associative array with members as follows:
2027 * new: Boolean indicating if the function attempted to create a new article
2028 * revision: The revision object for the inserted revision, or null
2030 * Compatibility note: this function previously returned a boolean value indicating success/failure
2032 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2033 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2035 # Low-level sanity check
2036 if ( $this->mTitle
->getText() === '' ) {
2037 throw new MWException( 'Something is trying to edit an article with an empty title' );
2040 wfProfileIn( __METHOD__
);
2042 $user = is_null( $user ) ?
$wgUser : $user;
2043 $status = Status
::newGood( array() );
2045 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2046 $this->loadPageData();
2048 $flags = $this->checkFlags( $flags );
2050 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2051 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2053 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2055 if ( $status->isOK() ) {
2056 $status->fatal( 'edit-hook-aborted' );
2059 wfProfileOut( __METHOD__
);
2063 # Silently ignore EDIT_MINOR if not allowed
2064 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2065 $bot = $flags & EDIT_FORCE_BOT
;
2067 $oldtext = $this->getRawText(); // current revision
2068 $oldsize = strlen( $oldtext );
2070 # Provide autosummaries if one is not provided and autosummaries are enabled.
2071 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2072 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2075 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2076 $text = $editInfo->pst
;
2077 $newsize = strlen( $text );
2079 $dbw = wfGetDB( DB_MASTER
);
2080 $now = wfTimestampNow();
2081 $this->mTimestamp
= $now;
2083 if ( $flags & EDIT_UPDATE
) {
2084 # Update article, but only if changed.
2085 $status->value
['new'] = false;
2087 # Make sure the revision is either completely inserted or not inserted at all
2088 if ( !$wgDBtransactions ) {
2089 $userAbort = ignore_user_abort( true );
2092 $changed = ( strcmp( $text, $oldtext ) != 0 );
2095 if ( !$this->mLatest
) {
2096 # Article gone missing
2097 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2098 $status->fatal( 'edit-gone-missing' );
2100 wfProfileOut( __METHOD__
);
2104 $revision = new Revision( array(
2105 'page' => $this->getId(),
2106 'comment' => $summary,
2107 'minor_edit' => $isminor,
2109 'parent_id' => $this->mLatest
,
2110 'user' => $user->getId(),
2111 'user_text' => $user->getName(),
2116 $revisionId = $revision->insertOn( $dbw );
2120 # Note that we use $this->mLatest instead of fetching a value from the master DB
2121 # during the course of this function. This makes sure that EditPage can detect
2122 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2123 # before this function is called. A previous function used a separate query, this
2124 # creates a window where concurrent edits can cause an ignored edit conflict.
2125 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2128 /* Belated edit conflict! Run away!! */
2129 $status->fatal( 'edit-conflict' );
2131 # Delete the invalid revision if the DB is not transactional
2132 if ( !$wgDBtransactions ) {
2133 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2139 global $wgUseRCPatrol;
2140 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2141 # Update recentchanges
2142 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2143 # Mark as patrolled if the user can do so
2144 $patrolled = $wgUseRCPatrol && !count(
2145 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2146 # Add RC row to the DB
2147 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2148 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2149 $revisionId, $patrolled
2152 # Log auto-patrolled edits
2154 PatrolLog
::record( $rc, true );
2157 $user->incEditCount();
2161 $status->warning( 'edit-no-change' );
2163 // Keep the same revision ID, but do some updates on it
2164 $revisionId = $this->getLatest();
2165 // Update page_touched, this is usually implicit in the page update
2166 // Other cache updates are done in onArticleEdit()
2167 $this->mTitle
->invalidateCache();
2170 if ( !$wgDBtransactions ) {
2171 ignore_user_abort( $userAbort );
2174 // Now that ignore_user_abort is restored, we can respond to fatal errors
2175 if ( !$status->isOK() ) {
2176 wfProfileOut( __METHOD__
);
2180 # Invalidate cache of this article and all pages using this article
2181 # as a template. Partly deferred.
2182 Article
::onArticleEdit( $this->mTitle
);
2183 # Update links tables, site stats, etc.
2184 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2186 # Create new article
2187 $status->value
['new'] = true;
2191 # Add the page record; stake our claim on this title!
2192 # This will return false if the article already exists
2193 $newid = $this->insertOn( $dbw );
2195 if ( $newid === false ) {
2197 $status->fatal( 'edit-already-exists' );
2199 wfProfileOut( __METHOD__
);
2203 # Save the revision text...
2204 $revision = new Revision( array(
2206 'comment' => $summary,
2207 'minor_edit' => $isminor,
2209 'user' => $user->getId(),
2210 'user_text' => $user->getName(),
2213 $revisionId = $revision->insertOn( $dbw );
2215 $this->mTitle
->resetArticleID( $newid );
2216 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
2218 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2220 # Update the page record with revision data
2221 $this->updateRevisionOn( $dbw, $revision, 0 );
2223 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2225 # Update recentchanges
2226 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2227 global $wgUseRCPatrol, $wgUseNPPatrol;
2229 # Mark as patrolled if the user can do so
2230 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2231 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2232 # Add RC row to the DB
2233 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2234 '', strlen( $text ), $revisionId, $patrolled );
2236 # Log auto-patrolled edits
2238 PatrolLog
::record( $rc, true );
2241 $user->incEditCount();
2244 # Update links, etc.
2245 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user, true );
2248 Article
::onArticleCreate( $this->mTitle
);
2250 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2251 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2254 # Do updates right now unless deferral was requested
2255 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2259 // Return the new revision (or null) to the caller
2260 $status->value
['revision'] = $revision;
2262 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2263 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2265 wfProfileOut( __METHOD__
);
2270 * Output a redirect back to the article.
2271 * This is typically used after an edit.
2273 * @param $noRedir Boolean: add redirect=no
2274 * @param $sectionAnchor String: section to redirect to, including "#"
2275 * @param $extraQuery String: extra query params
2277 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2281 $query = 'redirect=no';
2283 $query .= "&$extraQuery";
2285 $query = $extraQuery;
2288 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2292 * Mark this particular edit/page as patrolled
2294 public function markpatrolled() {
2295 global $wgOut, $wgRequest;
2297 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2299 # If we haven't been given an rc_id value, we can't do anything
2300 $rcid = (int) $wgRequest->getVal( 'rcid' );
2302 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2303 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2307 $rc = RecentChange
::newFromId( $rcid );
2309 if ( is_null( $rc ) ) {
2310 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2314 # It would be nice to see where the user had actually come from, but for now just guess
2315 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2316 $return = SpecialPage
::getTitleFor( $returnto );
2318 $errors = $rc->doMarkPatrolled();
2320 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2321 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2326 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2327 // The hook itself has handled any output
2331 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2332 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2333 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2334 $wgOut->returnToMain( null, $return );
2339 if ( !empty( $errors ) ) {
2340 $wgOut->showPermissionsErrorPage( $errors );
2346 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2347 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2348 $wgOut->returnToMain( null, $return );
2352 * User-interface handler for the "watch" action
2353 * @deprecated since 1.18
2355 public function watch() {
2356 Action
::factory( 'watch', $this )->show();
2360 * Add this page to $wgUser's watchlist
2362 * This is safe to be called multiple times
2364 * @return bool true on successful watch operation
2365 * @deprecated since 1.18
2367 public function doWatch() {
2368 return Action
::factory( 'watch', $this )->execute();
2372 * User interface handler for the "unwatch" action.
2373 * @deprecated since 1.18
2375 public function unwatch() {
2376 Action
::factory( 'unwatch', $this )->show();
2380 * Stop watching a page
2381 * @return bool true on successful unwatch
2382 * @deprecated since 1.18
2384 public function doUnwatch() {
2385 return Action
::factory( 'unwatch', $this )->execute();
2389 * action=protect handler
2391 public function protect() {
2392 $form = new ProtectionForm( $this );
2397 * action=unprotect handler (alias)
2399 public function unprotect() {
2404 * Update the article's restriction field, and leave a log entry.
2406 * @param $limit Array: set of restriction keys
2407 * @param $reason String
2408 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2409 * @param $expiry Array: per restriction type expiration
2410 * @return bool true on success
2412 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2413 global $wgUser, $wgContLang;
2415 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2417 $id = $this->mTitle
->getArticleID();
2420 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2424 if ( wfReadOnly() ) {
2425 wfDebug( "updateRestrictions failed: read-only\n" );
2429 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2430 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2438 // Take this opportunity to purge out expired restrictions
2439 Title
::purgeExpiredRestrictions();
2441 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2442 # we expect a single selection, but the schema allows otherwise.
2444 $updated = Article
::flattenRestrictions( $limit );
2447 foreach ( $restrictionTypes as $action ) {
2448 if ( isset( $expiry[$action] ) ) {
2449 # Get current restrictions on $action
2450 $aLimits = $this->mTitle
->getRestrictions( $action );
2451 $current[$action] = implode( '', $aLimits );
2452 # Are any actual restrictions being dealt with here?
2453 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2455 # If something changed, we need to log it. Checking $aRChanged
2456 # assures that "unprotecting" a page that is not protected does
2457 # not log just because the expiry was "changed".
2458 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2464 $current = Article
::flattenRestrictions( $current );
2466 $changed = ( $changed ||
$current != $updated );
2467 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2468 $protect = ( $updated != '' );
2470 # If nothing's changed, do nothing
2472 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2473 $dbw = wfGetDB( DB_MASTER
);
2475 # Prepare a null revision to be added to the history
2476 $modified = $current != '' && $protect;
2479 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2481 $comment_type = 'unprotectedarticle';
2484 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2486 # Only restrictions with the 'protect' right can cascade...
2487 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2488 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2490 # The schema allows multiple restrictions
2491 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2495 $cascade_description = '';
2498 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2502 $comment .= ": $reason";
2505 $editComment = $comment;
2506 $encodedExpiry = array();
2507 $protect_description = '';
2508 foreach ( $limit as $action => $restrictions ) {
2509 if ( !isset( $expiry[$action] ) )
2510 $expiry[$action] = $dbw->getInfinity();
2512 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2513 if ( $restrictions != '' ) {
2514 $protect_description .= "[$action=$restrictions] (";
2515 if ( $encodedExpiry[$action] != 'infinity' ) {
2516 $protect_description .= wfMsgForContent( 'protect-expiring',
2517 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2518 $wgContLang->date( $expiry[$action], false, false ) ,
2519 $wgContLang->time( $expiry[$action], false, false ) );
2521 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2524 $protect_description .= ') ';
2527 $protect_description = trim( $protect_description );
2529 if ( $protect_description && $protect ) {
2530 $editComment .= " ($protect_description)";
2534 $editComment .= "$cascade_description";
2537 # Update restrictions table
2538 foreach ( $limit as $action => $restrictions ) {
2539 if ( $restrictions != '' ) {
2540 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2541 array( 'pr_page' => $id,
2542 'pr_type' => $action,
2543 'pr_level' => $restrictions,
2544 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2545 'pr_expiry' => $encodedExpiry[$action]
2550 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2551 'pr_type' => $action ), __METHOD__
);
2555 # Insert a null revision
2556 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2557 $nullRevId = $nullRevision->insertOn( $dbw );
2559 $latest = $this->getLatest();
2560 # Update page record
2561 $dbw->update( 'page',
2563 'page_touched' => $dbw->timestamp(),
2564 'page_restrictions' => '',
2565 'page_latest' => $nullRevId
2566 ), array( /* WHERE */
2568 ), 'Article::protect'
2571 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2572 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2574 # Update the protection log
2575 $log = new LogPage( 'protect' );
2577 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2578 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2580 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2583 } # End "changed" check
2589 * Take an array of page restrictions and flatten it to a string
2590 * suitable for insertion into the page_restrictions field.
2591 * @param $limit Array
2594 protected static function flattenRestrictions( $limit ) {
2595 if ( !is_array( $limit ) ) {
2596 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2602 foreach ( $limit as $action => $restrictions ) {
2603 if ( $restrictions != '' ) {
2604 $bits[] = "$action=$restrictions";
2608 return implode( ':', $bits );
2612 * Auto-generates a deletion reason
2614 * @param &$hasHistory Boolean: whether the page has a history
2615 * @return mixed String containing deletion reason or empty string, or boolean false
2616 * if no revision occurred
2618 public function generateReason( &$hasHistory ) {
2621 $dbw = wfGetDB( DB_MASTER
);
2622 // Get the last revision
2623 $rev = Revision
::newFromTitle( $this->mTitle
);
2625 if ( is_null( $rev ) ) {
2629 // Get the article's contents
2630 $contents = $rev->getText();
2633 // If the page is blank, use the text from the previous revision,
2634 // which can only be blank if there's a move/import/protect dummy revision involved
2635 if ( $contents == '' ) {
2636 $prev = $rev->getPrevious();
2639 $contents = $prev->getText();
2644 // Find out if there was only one contributor
2645 // Only scan the last 20 revisions
2646 $res = $dbw->select( 'revision', 'rev_user_text',
2647 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2649 array( 'LIMIT' => 20 )
2652 if ( $res === false ) {
2653 // This page has no revisions, which is very weird
2657 $hasHistory = ( $res->numRows() > 1 );
2658 $row = $dbw->fetchObject( $res );
2660 if ( $row ) { // $row is false if the only contributor is hidden
2661 $onlyAuthor = $row->rev_user_text
;
2662 // Try to find a second contributor
2663 foreach ( $res as $row ) {
2664 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2665 $onlyAuthor = false;
2670 $onlyAuthor = false;
2673 // Generate the summary with a '$1' placeholder
2675 // The current revision is blank and the one before is also
2676 // blank. It's just not our lucky day
2677 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2679 if ( $onlyAuthor ) {
2680 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2682 $reason = wfMsgForContent( 'excontent', '$1' );
2686 if ( $reason == '-' ) {
2687 // Allow these UI messages to be blanked out cleanly
2691 // Replace newlines with spaces to prevent uglyness
2692 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2693 // Calculate the maximum amount of chars to get
2694 // Max content length = max comment length - length of the comment (excl. $1)
2695 $maxLength = 255 - ( strlen( $reason ) - 2 );
2696 $contents = $wgContLang->truncate( $contents, $maxLength );
2697 // Remove possible unfinished links
2698 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2699 // Now replace the '$1' placeholder
2700 $reason = str_replace( '$1', $contents, $reason );
2707 * UI entry point for page deletion
2709 public function delete() {
2710 global $wgOut, $wgRequest;
2712 $confirm = $wgRequest->wasPosted() &&
2713 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2715 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2716 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2718 $reason = $this->DeleteReasonList
;
2720 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2721 // Entry from drop down menu + additional comment
2722 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2723 } elseif ( $reason == 'other' ) {
2724 $reason = $this->DeleteReason
;
2727 # Flag to hide all contents of the archived revisions
2728 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2730 # This code desperately needs to be totally rewritten
2732 # Read-only check...
2733 if ( wfReadOnly() ) {
2734 $wgOut->readOnlyPage();
2740 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2742 if ( count( $permission_errors ) > 0 ) {
2743 $wgOut->showPermissionsErrorPage( $permission_errors );
2748 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2750 # Better double-check that it hasn't been deleted yet!
2751 $dbw = wfGetDB( DB_MASTER
);
2752 $conds = $this->mTitle
->pageCond();
2753 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2754 if ( $latest === false ) {
2755 $wgOut->showFatalError(
2758 array( 'class' => 'error mw-error-cannotdelete' ),
2759 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2762 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2763 LogEventsList
::showLogExtract(
2766 $this->mTitle
->getPrefixedText()
2772 # Hack for big sites
2773 $bigHistory = $this->isBigDeletion();
2774 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2775 global $wgLang, $wgDeleteRevisionsLimit;
2777 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2778 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2784 $this->doDelete( $reason, $suppress );
2786 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2788 } elseif ( $this->mTitle
->userIsWatching() ) {
2795 // Generate deletion reason
2796 $hasHistory = false;
2798 $reason = $this->generateReason( $hasHistory );
2801 // If the page has a history, insert a warning
2802 if ( $hasHistory && !$confirm ) {
2805 $revisions = $this->estimateRevisionCount();
2806 // @todo FIXME: i18n issue/patchwork message
2807 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2808 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2809 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->mTitle
,
2810 wfMsgHtml( 'history' ),
2811 array( 'rel' => 'archives' ),
2812 array( 'action' => 'history' ) ) .
2816 if ( $bigHistory ) {
2817 global $wgDeleteRevisionsLimit;
2818 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2819 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2823 return $this->confirmDelete( $reason );
2827 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2829 public function isBigDeletion() {
2830 global $wgDeleteRevisionsLimit;
2832 if ( $wgDeleteRevisionsLimit ) {
2833 $revCount = $this->estimateRevisionCount();
2835 return $revCount > $wgDeleteRevisionsLimit;
2842 * @return int approximate revision count
2844 public function estimateRevisionCount() {
2845 $dbr = wfGetDB( DB_SLAVE
);
2847 // For an exact count...
2848 // return $dbr->selectField( 'revision', 'COUNT(*)',
2849 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2850 return $dbr->estimateRowCount( 'revision', '*',
2851 array( 'rev_page' => $this->getId() ), __METHOD__
);
2855 * Get the last N authors
2856 * @param $num Integer: number of revisions to get
2857 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2858 * @return array Array of authors, duplicates not removed
2860 public function getLastNAuthors( $num, $revLatest = 0 ) {
2861 wfProfileIn( __METHOD__
);
2862 // First try the slave
2863 // If that doesn't have the latest revision, try the master
2865 $db = wfGetDB( DB_SLAVE
);
2868 $res = $db->select( array( 'page', 'revision' ),
2869 array( 'rev_id', 'rev_user_text' ),
2871 'page_namespace' => $this->mTitle
->getNamespace(),
2872 'page_title' => $this->mTitle
->getDBkey(),
2873 'rev_page = page_id'
2876 'ORDER BY' => 'rev_timestamp DESC',
2882 wfProfileOut( __METHOD__
);
2886 $row = $db->fetchObject( $res );
2888 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2889 $db = wfGetDB( DB_MASTER
);
2894 } while ( $continue );
2896 $authors = array( $row->rev_user_text
);
2898 foreach ( $res as $row ) {
2899 $authors[] = $row->rev_user_text
;
2902 wfProfileOut( __METHOD__
);
2907 * Output deletion confirmation dialog
2908 * @todo FIXME: Move to another file?
2909 * @param $reason String: prefilled reason
2911 public function confirmDelete( $reason ) {
2914 wfDebug( "Article::confirmDelete\n" );
2916 $deleteBackLink = Linker
::linkKnown( $this->mTitle
);
2917 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2918 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2919 $wgOut->addWikiMsg( 'confirmdeletetext' );
2921 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2923 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2924 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2926 <td class='mw-input'><strong>" .
2927 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2928 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2934 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2936 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2937 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2938 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2939 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2940 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2941 "<tr id=\"wpDeleteReasonListRow\">
2942 <td class='mw-label'>" .
2943 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2945 <td class='mw-input'>" .
2946 Xml
::listDropDown( 'wpDeleteReasonList',
2947 wfMsgForContent( 'deletereason-dropdown' ),
2948 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2951 <tr id=\"wpDeleteReasonRow\">
2952 <td class='mw-label'>" .
2953 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2955 <td class='mw-input'>" .
2956 Html
::input( 'wpReason', $reason, 'text', array(
2958 'maxlength' => '255',
2966 # Disallow watching if user is not logged in
2967 if ( $wgOut->getUser()->isLoggedIn() ) {
2971 <td class='mw-input'>" .
2972 Xml
::checkLabel( wfMsg( 'watchthis' ),
2973 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2982 <td class='mw-submit'>" .
2983 Xml
::submitButton( wfMsg( 'deletepage' ),
2984 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2987 Xml
::closeElement( 'table' ) .
2988 Xml
::closeElement( 'fieldset' ) .
2989 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2990 Xml
::closeElement( 'form' );
2992 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2993 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2994 $link = Linker
::link(
2996 wfMsgHtml( 'delete-edit-reasonlist' ),
2998 array( 'action' => 'edit' )
3000 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3003 $wgOut->addHTML( $form );
3004 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3005 LogEventsList
::showLogExtract( $wgOut, 'delete',
3006 $this->mTitle
->getPrefixedText()
3011 * Perform a deletion and output success or failure messages
3013 public function doDelete( $reason, $suppress = false ) {
3016 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3019 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
3020 $deleted = $this->mTitle
->getPrefixedText();
3022 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3023 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3025 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3027 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3028 $wgOut->returnToMain( false );
3030 if ( $error == '' ) {
3031 $wgOut->showFatalError(
3034 array( 'class' => 'error mw-error-cannotdelete' ),
3035 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3039 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3041 LogEventsList
::showLogExtract(
3044 $this->mTitle
->getPrefixedText()
3047 $wgOut->showFatalError( $error );
3053 * Back-end article deletion
3054 * Deletes the article with database consistency, writes logs, purges caches
3056 * @param $reason string delete reason for deletion log
3057 * @param suppress bitfield
3058 * Revision::DELETED_TEXT
3059 * Revision::DELETED_COMMENT
3060 * Revision::DELETED_USER
3061 * Revision::DELETED_RESTRICTED
3062 * @param $id int article ID
3063 * @param $commit boolean defaults to true, triggers transaction end
3064 * @return boolean true if successful
3066 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3067 global $wgDeferredUpdateList, $wgUseTrackbacks;
3070 wfDebug( __METHOD__
. "\n" );
3072 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3075 $dbw = wfGetDB( DB_MASTER
);
3076 $t = $this->mTitle
->getDBkey();
3077 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3079 if ( $t === '' ||
$id == 0 ) {
3083 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
3084 array_push( $wgDeferredUpdateList, $u );
3086 // Bitfields to further suppress the content
3089 // This should be 15...
3090 $bitfield |
= Revision
::DELETED_TEXT
;
3091 $bitfield |
= Revision
::DELETED_COMMENT
;
3092 $bitfield |
= Revision
::DELETED_USER
;
3093 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3095 $bitfield = 'rev_deleted';
3099 // For now, shunt the revision data into the archive table.
3100 // Text is *not* removed from the text table; bulk storage
3101 // is left intact to avoid breaking block-compression or
3102 // immutable storage schemes.
3104 // For backwards compatibility, note that some older archive
3105 // table entries will have ar_text and ar_flags fields still.
3107 // In the future, we may keep revisions and mark them with
3108 // the rev_deleted field, which is reserved for this purpose.
3109 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3111 'ar_namespace' => 'page_namespace',
3112 'ar_title' => 'page_title',
3113 'ar_comment' => 'rev_comment',
3114 'ar_user' => 'rev_user',
3115 'ar_user_text' => 'rev_user_text',
3116 'ar_timestamp' => 'rev_timestamp',
3117 'ar_minor_edit' => 'rev_minor_edit',
3118 'ar_rev_id' => 'rev_id',
3119 'ar_text_id' => 'rev_text_id',
3120 'ar_text' => '\'\'', // Be explicit to appease
3121 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3122 'ar_len' => 'rev_len',
3123 'ar_page_id' => 'page_id',
3124 'ar_deleted' => $bitfield
3127 'page_id = rev_page'
3131 # Delete restrictions for it
3132 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3134 # Now that it's safely backed up, delete it
3135 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3136 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3143 # Fix category table counts
3145 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3147 foreach ( $res as $row ) {
3148 $cats [] = $row->cl_to
;
3151 $this->updateCategoryCounts( array(), $cats );
3153 # If using cascading deletes, we can skip some explicit deletes
3154 if ( !$dbw->cascadingDeletes() ) {
3155 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3157 if ( $wgUseTrackbacks )
3158 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3160 # Delete outgoing links
3161 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3162 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3163 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3164 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3165 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3166 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3167 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3168 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3171 # If using cleanup triggers, we can skip some manual deletes
3172 if ( !$dbw->cleanupTriggers() ) {
3173 # Clean up recentchanges entries...
3174 $dbw->delete( 'recentchanges',
3175 array( 'rc_type != ' . RC_LOG
,
3176 'rc_namespace' => $this->mTitle
->getNamespace(),
3177 'rc_title' => $this->mTitle
->getDBkey() ),
3179 $dbw->delete( 'recentchanges',
3180 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3185 Article
::onArticleDelete( $this->mTitle
);
3187 # Clear the cached article id so the interface doesn't act like we exist
3188 $this->mTitle
->resetArticleID( 0 );
3190 # Log the deletion, if the page was suppressed, log it at Oversight instead
3191 $logtype = $suppress ?
'suppress' : 'delete';
3192 $log = new LogPage( $logtype );
3194 # Make sure logging got through
3195 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3201 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3206 * Roll back the most recent consecutive set of edits to a page
3207 * from the same user; fails if there are no eligible edits to
3208 * roll back to, e.g. user is the sole contributor. This function
3209 * performs permissions checks on $wgUser, then calls commitRollback()
3210 * to do the dirty work
3212 * @param $fromP String: Name of the user whose edits to rollback.
3213 * @param $summary String: Custom summary. Set to default summary if empty.
3214 * @param $token String: Rollback token.
3215 * @param $bot Boolean: If true, mark all reverted edits as bot.
3217 * @param $resultDetails Array: contains result-specific array of additional values
3218 * 'alreadyrolled' : 'current' (rev)
3219 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3221 * @return array of errors, each error formatted as
3222 * array(messagekey, param1, param2, ...).
3223 * On success, the array is empty. This array can also be passed to
3224 * OutputPage::showPermissionsErrorPage().
3226 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3229 $resultDetails = null;
3232 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3233 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3234 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3236 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3237 $errors[] = array( 'sessionfailure' );
3240 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3241 $errors[] = array( 'actionthrottledtext' );
3244 # If there were errors, bail out now
3245 if ( !empty( $errors ) ) {
3249 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3253 * Backend implementation of doRollback(), please refer there for parameter
3254 * and return value documentation
3256 * NOTE: This function does NOT check ANY permissions, it just commits the
3257 * rollback to the DB Therefore, you should only call this function direct-
3258 * ly if you want to use custom permissions checks. If you don't, use
3259 * doRollback() instead.
3261 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3262 global $wgUseRCPatrol, $wgUser, $wgLang;
3264 $dbw = wfGetDB( DB_MASTER
);
3266 if ( wfReadOnly() ) {
3267 return array( array( 'readonlytext' ) );
3270 # Get the last editor
3271 $current = Revision
::newFromTitle( $this->mTitle
);
3272 if ( is_null( $current ) ) {
3273 # Something wrong... no page?
3274 return array( array( 'notanarticle' ) );
3277 $from = str_replace( '_', ' ', $fromP );
3278 # User name given should match up with the top revision.
3279 # If the user was deleted then $from should be empty.
3280 if ( $from != $current->getUserText() ) {
3281 $resultDetails = array( 'current' => $current );
3282 return array( array( 'alreadyrolled',
3283 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3284 htmlspecialchars( $fromP ),
3285 htmlspecialchars( $current->getUserText() )
3289 # Get the last edit not by this guy...
3290 # Note: these may not be public values
3291 $user = intval( $current->getRawUser() );
3292 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3293 $s = $dbw->selectRow( 'revision',
3294 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3295 array( 'rev_page' => $current->getPage(),
3296 "rev_user != {$user} OR rev_user_text != {$user_text}"
3298 array( 'USE INDEX' => 'page_timestamp',
3299 'ORDER BY' => 'rev_timestamp DESC' )
3301 if ( $s === false ) {
3302 # No one else ever edited this page
3303 return array( array( 'cantrollback' ) );
3304 } else if ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3305 # Only admins can see this text
3306 return array( array( 'notvisiblerev' ) );
3310 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3311 # Mark all reverted edits as bot
3315 if ( $wgUseRCPatrol ) {
3316 # Mark all reverted edits as patrolled
3317 $set['rc_patrolled'] = 1;
3320 if ( count( $set ) ) {
3321 $dbw->update( 'recentchanges', $set,
3323 'rc_cur_id' => $current->getPage(),
3324 'rc_user_text' => $current->getUserText(),
3325 "rc_timestamp > '{$s->rev_timestamp}'",
3330 # Generate the edit summary if necessary
3331 $target = Revision
::newFromId( $s->rev_id
);
3332 if ( empty( $summary ) ) {
3333 if ( $from == '' ) { // no public user name
3334 $summary = wfMsgForContent( 'revertpage-nouser' );
3336 $summary = wfMsgForContent( 'revertpage' );
3340 # Allow the custom summary to use the same args as the default message
3342 $target->getUserText(), $from, $s->rev_id
,
3343 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3344 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3346 $summary = wfMsgReplaceArgs( $summary, $args );
3349 $flags = EDIT_UPDATE
;
3351 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3352 $flags |
= EDIT_MINOR
;
3355 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3356 $flags |
= EDIT_FORCE_BOT
;
3359 # Actually store the edit
3360 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3361 if ( !empty( $status->value
['revision'] ) ) {
3362 $revId = $status->value
['revision']->getId();
3367 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3369 $resultDetails = array(
3370 'summary' => $summary,
3371 'current' => $current,
3372 'target' => $target,
3380 * User interface for rollback operations
3382 public function rollback() {
3383 global $wgUser, $wgOut, $wgRequest;
3387 $result = $this->doRollback(
3388 $wgRequest->getVal( 'from' ),
3389 $wgRequest->getText( 'summary' ),
3390 $wgRequest->getVal( 'token' ),
3391 $wgRequest->getBool( 'bot' ),
3395 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3396 $wgOut->rateLimited();
3400 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3401 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3402 $errArray = $result[0];
3403 $errMsg = array_shift( $errArray );
3404 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3406 if ( isset( $details['current'] ) ) {
3407 $current = $details['current'];
3409 if ( $current->getComment() != '' ) {
3410 $wgOut->addWikiMsgArray( 'editcomment', array(
3411 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3418 # Display permissions errors before read-only message -- there's no
3419 # point in misleading the user into thinking the inability to rollback
3420 # is only temporary.
3421 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3422 # array_diff is completely broken for arrays of arrays, sigh.
3423 # Remove any 'readonlytext' error manually.
3425 foreach ( $result as $error ) {
3426 if ( $error != array( 'readonlytext' ) ) {
3430 $wgOut->showPermissionsErrorPage( $out );
3435 if ( $result == array( array( 'readonlytext' ) ) ) {
3436 $wgOut->readOnlyPage();
3441 $current = $details['current'];
3442 $target = $details['target'];
3443 $newId = $details['newid'];
3444 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3445 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3447 if ( $current->getUserText() === '' ) {
3448 $old = wfMsg( 'rev-deleted-user' );
3450 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
3451 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
3454 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
3455 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
3456 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3457 $wgOut->returnToMain( false, $this->mTitle
);
3459 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3460 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3461 $de->showDiff( '', '' );
3466 * Do standard deferred updates after page view
3468 public function viewUpdates() {
3469 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3470 if ( wfReadOnly() ) {
3474 # Don't update page view counters on views from bot users (bug 14044)
3475 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3476 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3477 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3480 # Update newtalk / watchlist notification status
3481 $wgUser->clearNotification( $this->mTitle
);
3485 * Prepare text which is about to be saved.
3486 * Returns a stdclass with source, pst and output members
3488 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3489 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3491 return $this->mPreparedEdit
;
3496 if( $user === null ) {
3500 $popts = ParserOptions
::newFromUser( $user );
3501 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3503 $edit = (object)array();
3504 $edit->revid
= $revid;
3505 $edit->newText
= $text;
3506 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3507 $edit->popts
= $this->getParserOptions();
3508 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3509 $edit->oldText
= $this->getRawText();
3511 $this->mPreparedEdit
= $edit;
3517 * Do standard deferred updates after page edit.
3518 * Update links tables, site stats, search index and message cache.
3519 * Purges pages that include this page if the text was changed here.
3520 * Every 100th edit, prune the recent changes table.
3523 * @param $text String: New text of the article
3524 * @param $summary String: Edit summary
3525 * @param $minoredit Boolean: Minor edit
3526 * @param $timestamp_of_pagechange String timestamp associated with the page change
3527 * @param $newid Integer: rev_id value of the new revision
3528 * @param $changed Boolean: Whether or not the content actually changed
3529 * @param $user User object: User doing the edit
3530 * @param $created Boolean: Whether the edit created the page
3532 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
3533 $changed = true, User
$user = null, $created = false )
3535 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3537 wfProfileIn( __METHOD__
);
3540 # Be careful not to double-PST: $text is usually already PST-ed once
3541 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3542 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3543 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3545 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3546 $editInfo = $this->mPreparedEdit
;
3549 # Save it to the parser cache
3550 if ( $wgEnableParserCache ) {
3551 $parserCache = ParserCache
::singleton();
3552 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3555 # Update the links tables
3556 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3559 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3561 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3562 if ( 0 == mt_rand( 0, 99 ) ) {
3563 // Flush old entries from the `recentchanges` table; we do this on
3564 // random requests so as to avoid an increase in writes for no good reason
3567 $dbw = wfGetDB( DB_MASTER
);
3568 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3571 array( "rc_timestamp < '$cutoff'" ),
3577 $id = $this->getID();
3578 $title = $this->mTitle
->getPrefixedDBkey();
3579 $shortTitle = $this->mTitle
->getDBkey();
3582 wfProfileOut( __METHOD__
);
3589 } elseif ( $created ) {
3590 $good = (int)$this->isCountable( $editInfo );
3593 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
3597 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
3598 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
3600 # If this is another user's talk page, update newtalk
3601 # Don't do this if $changed = false otherwise some idiot can null-edit a
3602 # load of user talk pages and piss people off, nor if it's a minor edit
3603 # by a properly-flagged bot.
3604 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3605 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3607 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3608 $other = User
::newFromName( $shortTitle, false );
3610 wfDebug( __METHOD__
. ": invalid username\n" );
3611 } elseif ( User
::isIP( $shortTitle ) ) {
3612 // An anonymous user
3613 $other->setNewtalk( true );
3614 } elseif ( $other->isLoggedIn() ) {
3615 $other->setNewtalk( true );
3617 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3622 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3623 MessageCache
::singleton()->replace( $shortTitle, $text );
3626 wfProfileOut( __METHOD__
);
3630 * Perform article updates on a special page creation.
3632 * @param $rev Revision object
3634 * @todo This is a shitty interface function. Kill it and replace the
3635 * other shitty functions like editUpdates and such so it's not needed
3638 public function createUpdates( $rev ) {
3639 $this->editUpdates( $rev->getText(), $rev->getComment(),
3640 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
3644 * Generate the navigation links when browsing through an article revisions
3645 * It shows the information as:
3646 * Revision as of \<date\>; view current revision
3647 * \<- Previous version | Next Version -\>
3649 * @param $oldid String: revision ID of this article revision
3651 public function setOldSubtitle( $oldid = 0 ) {
3652 global $wgLang, $wgOut, $wgUser, $wgRequest;
3654 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3658 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3660 # Cascade unhide param in links for easy deletion browsing
3661 $extraParams = array();
3662 if ( $wgRequest->getVal( 'unhide' ) ) {
3663 $extraParams['unhide'] = 1;
3666 $revision = Revision
::newFromId( $oldid );
3667 $timestamp = $revision->getTimestamp();
3669 $current = ( $oldid == $this->mLatest
);
3670 $td = $wgLang->timeanddate( $timestamp, true );
3671 $tddate = $wgLang->date( $timestamp, true );
3672 $tdtime = $wgLang->time( $timestamp, true );
3675 ?
wfMsgHtml( 'currentrevisionlink' )
3678 wfMsgHtml( 'currentrevisionlink' ),
3681 array( 'known', 'noclasses' )
3684 ?
wfMsgHtml( 'diff' )
3687 wfMsgHtml( 'diff' ),
3693 array( 'known', 'noclasses' )
3695 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3699 wfMsgHtml( 'previousrevision' ),
3702 'direction' => 'prev',
3705 array( 'known', 'noclasses' )
3707 : wfMsgHtml( 'previousrevision' );
3711 wfMsgHtml( 'diff' ),
3717 array( 'known', 'noclasses' )
3719 : wfMsgHtml( 'diff' );
3720 $nextlink = $current
3721 ?
wfMsgHtml( 'nextrevision' )
3724 wfMsgHtml( 'nextrevision' ),
3727 'direction' => 'next',
3730 array( 'known', 'noclasses' )
3732 $nextdiff = $current
3733 ?
wfMsgHtml( 'diff' )
3736 wfMsgHtml( 'diff' ),
3742 array( 'known', 'noclasses' )
3747 // User can delete revisions or view deleted revisions...
3748 $canHide = $wgUser->isAllowed( 'deleterevision' );
3749 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3750 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3751 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3754 'type' => 'revision',
3755 'target' => $this->mTitle
->getPrefixedDbkey(),
3758 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3763 # Show user links if allowed to see them. If hidden, then show them only if requested...
3764 $userlinks = Linker
::revUserTools( $revision, !$unhide );
3766 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3767 ?
'revision-info-current'
3770 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3773 array( 'parseinline', 'replaceafter' ),
3779 $revision->getUser()
3782 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3783 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3785 $wgOut->addHTML( $r );
3789 * This function is called right before saving the wikitext,
3790 * so we can do things like signatures and links-in-context.
3792 * @param $text String article contents
3793 * @param $user User object: user doing the edit, $wgUser will be used if
3795 * @param $popts ParserOptions object: parser options, default options for
3796 * the user loaded if null given
3797 * @return string article contents with altered wikitext markup (signatures
3798 * converted, {{subst:}}, templates, etc.)
3800 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3803 if ( $user === null ) {
3808 if ( $popts === null ) {
3809 $popts = ParserOptions
::newFromUser( $user );
3812 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3815 /* Caching functions */
3818 * checkLastModified returns true if it has taken care of all
3819 * output to the client that is necessary for this request.
3820 * (that is, it has sent a cached version of the page)
3822 * @return boolean true if cached version send, false otherwise
3824 protected function tryFileCache() {
3825 static $called = false;
3828 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3833 if ( $this->isFileCacheable() ) {
3834 $cache = new HTMLFileCache( $this->mTitle
);
3835 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3836 wfDebug( "Article::tryFileCache(): about to load file\n" );
3837 $cache->loadFromFileCache();
3840 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3841 ob_start( array( &$cache, 'saveToFileCache' ) );
3844 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3851 * Check if the page can be cached
3854 public function isFileCacheable() {
3857 if ( HTMLFileCache
::useFileCache() ) {
3858 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3859 // Extension may have reason to disable file caching on some pages.
3861 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3869 * Loads page_touched and returns a value indicating if it should be used
3870 * @return boolean true if not a redirect
3872 public function checkTouched() {
3873 if ( !$this->mDataLoaded
) {
3874 $this->loadPageData();
3877 return !$this->mIsRedirect
;
3881 * Get the page_touched field
3882 * @return string containing GMT timestamp
3884 public function getTouched() {
3885 if ( !$this->mDataLoaded
) {
3886 $this->loadPageData();
3889 return $this->mTouched
;
3893 * Get the page_latest field
3894 * @return integer rev_id of current revision
3896 public function getLatest() {
3897 if ( !$this->mDataLoaded
) {
3898 $this->loadPageData();
3901 return (int)$this->mLatest
;
3905 * Edit an article without doing all that other stuff
3906 * The article must already exist; link tables etc
3907 * are not updated, caches are not flushed.
3909 * @param $text String: text submitted
3910 * @param $comment String: comment submitted
3911 * @param $minor Boolean: whereas it's a minor modification
3913 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3914 wfProfileIn( __METHOD__
);
3916 $dbw = wfGetDB( DB_MASTER
);
3917 $revision = new Revision( array(
3918 'page' => $this->getId(),
3920 'comment' => $comment,
3921 'minor_edit' => $minor ?
1 : 0,
3923 $revision->insertOn( $dbw );
3924 $this->updateRevisionOn( $dbw, $revision );
3927 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3929 wfProfileOut( __METHOD__
);
3933 * The onArticle*() functions are supposed to be a kind of hooks
3934 * which should be called whenever any of the specified actions
3937 * This is a good place to put code to clear caches, for instance.
3939 * This is called on page move and undelete, as well as edit
3941 * @param $title Title object
3943 public static function onArticleCreate( $title ) {
3944 # Update existence markers on article/talk tabs...
3945 if ( $title->isTalkPage() ) {
3946 $other = $title->getSubjectPage();
3948 $other = $title->getTalkPage();
3951 $other->invalidateCache();
3952 $other->purgeSquid();
3954 $title->touchLinks();
3955 $title->purgeSquid();
3956 $title->deleteTitleProtection();
3960 * Clears caches when article is deleted
3962 * @param $title Title
3964 public static function onArticleDelete( $title ) {
3965 # Update existence markers on article/talk tabs...
3966 if ( $title->isTalkPage() ) {
3967 $other = $title->getSubjectPage();
3969 $other = $title->getTalkPage();
3972 $other->invalidateCache();
3973 $other->purgeSquid();
3975 $title->touchLinks();
3976 $title->purgeSquid();
3979 HTMLFileCache
::clearFileCache( $title );
3982 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3983 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3987 if ( $title->getNamespace() == NS_FILE
) {
3988 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3989 $update->doUpdate();
3993 if ( $title->getNamespace() == NS_USER_TALK
) {
3994 $user = User
::newFromName( $title->getText(), false );
3995 $user->setNewtalk( false );
3999 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4003 * Purge caches on page update etc
4005 * @param $title Title object
4006 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4008 public static function onArticleEdit( $title ) {
4009 global $wgDeferredUpdateList;
4011 // Invalidate caches of articles which include this page
4012 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4014 // Invalidate the caches of all pages which redirect here
4015 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4017 # Purge squid for this page only
4018 $title->purgeSquid();
4020 # Clear file cache for this page only
4021 HTMLFileCache
::clearFileCache( $title );
4027 * Overriden by ImagePage class, only present here to avoid a fatal error
4028 * Called for ?action=revert
4030 public function revert() {
4032 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4036 * Info about this page
4037 * Called for ?action=info when $wgAllowPageInfo is on.
4039 public function info() {
4040 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4042 if ( !$wgAllowPageInfo ) {
4043 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4047 $page = $this->mTitle
->getSubjectPage();
4049 $wgOut->setPagetitle( $page->getPrefixedText() );
4050 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4051 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4053 if ( !$this->mTitle
->exists() ) {
4054 $wgOut->addHTML( '<div class="noarticletext">' );
4055 $msg = $wgUser->isLoggedIn()
4057 : 'noarticletextanon';
4058 $wgOut->addWikiMsg( $msg );
4059 $wgOut->addHTML( '</div>' );
4061 $dbr = wfGetDB( DB_SLAVE
);
4063 'wl_title' => $page->getDBkey(),
4064 'wl_namespace' => $page->getNamespace() );
4065 $numwatchers = $dbr->selectField(
4071 $pageInfo = $this->pageCountInfo( $page );
4072 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4074 // @todo FIXME: unescaped messages
4075 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4076 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4079 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4082 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4085 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4088 $wgOut->addHTML( '</ul>' );
4093 * Return the total number of edits and number of unique editors
4094 * on a given page. If page does not exist, returns false.
4096 * @param $title Title object
4097 * @return mixed array or boolean false
4099 public function pageCountInfo( $title ) {
4100 $id = $title->getArticleId();
4106 $dbr = wfGetDB( DB_SLAVE
);
4107 $rev_clause = array( 'rev_page' => $id );
4108 $edits = $dbr->selectField(
4114 $authors = $dbr->selectField(
4116 'COUNT(DISTINCT rev_user_text)',
4121 return array( 'edits' => $edits, 'authors' => $authors );
4125 * Return a list of templates used by this article.
4126 * Uses the templatelinks table
4128 * @return Array of Title objects
4130 public function getUsedTemplates() {
4132 $id = $this->mTitle
->getArticleID();
4138 $dbr = wfGetDB( DB_SLAVE
);
4139 $res = $dbr->select( array( 'templatelinks' ),
4140 array( 'tl_namespace', 'tl_title' ),
4141 array( 'tl_from' => $id ),
4144 if ( $res !== false ) {
4145 foreach ( $res as $row ) {
4146 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4154 * Returns a list of hidden categories this page is a member of.
4155 * Uses the page_props and categorylinks tables.
4157 * @return Array of Title objects
4159 public function getHiddenCategories() {
4161 $id = $this->mTitle
->getArticleID();
4167 $dbr = wfGetDB( DB_SLAVE
);
4168 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4170 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4171 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4174 if ( $res !== false ) {
4175 foreach ( $res as $row ) {
4176 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4184 * Return an applicable autosummary if one exists for the given edit.
4185 * @param $oldtext String: the previous text of the page.
4186 * @param $newtext String: The submitted text of the page.
4187 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4188 * @return string An appropriate autosummary, or an empty string.
4190 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4193 # Decide what kind of autosummary is needed.
4195 # Redirect autosummaries
4196 $ot = Title
::newFromRedirect( $oldtext );
4197 $rt = Title
::newFromRedirect( $newtext );
4199 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4200 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4203 # New page autosummaries
4204 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4205 # If they're making a new article, give its text, truncated, in the summary.
4207 $truncatedtext = $wgContLang->truncate(
4208 str_replace( "\n", ' ', $newtext ),
4209 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4211 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4214 # Blanking autosummaries
4215 if ( $oldtext != '' && $newtext == '' ) {
4216 return wfMsgForContent( 'autosumm-blank' );
4217 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4218 # Removing more than 90% of the article
4220 $truncatedtext = $wgContLang->truncate(
4222 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4224 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4227 # If we reach this point, there's no applicable autosummary for our case, so our
4228 # autosummary is empty.
4233 * Add the primary page-view wikitext to the output buffer
4234 * Saves the text into the parser cache if possible.
4235 * Updates templatelinks if it is out of date.
4237 * @param $text String
4238 * @param $cache Boolean
4239 * @param $parserOptions mixed ParserOptions object, or boolean false
4241 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4244 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4245 $wgOut->addParserOutput( $this->mParserOutput
);
4249 * This does all the heavy lifting for outputWikitext, except it returns the parser
4250 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4251 * say, embedding thread pages within a discussion system (LiquidThreads)
4253 * @param $text string
4254 * @param $cache boolean
4255 * @param $parserOptions parsing options, defaults to false
4256 * @return string containing parsed output
4258 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4259 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4261 if ( !$parserOptions ) {
4262 $parserOptions = $this->getParserOptions();
4266 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4267 $parserOptions, true, true, $this->getRevIdFetched() );
4272 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4273 $this->mTitle
->getPrefixedDBkey() ) );
4276 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4277 $parserCache = ParserCache
::singleton();
4278 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4281 // Make sure file cache is not used on uncacheable content.
4282 // Output that has magic words in it can still use the parser cache
4283 // (if enabled), though it will generally expire sooner.
4284 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4285 $wgUseFileCache = false;
4288 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4290 return $this->mParserOutput
;
4294 * Get parser options suitable for rendering the primary article wikitext
4295 * @return ParserOptions object
4297 public function getParserOptions() {
4299 if ( !$this->mParserOptions
) {
4300 $this->mParserOptions
= $this->makeParserOptions( $wgUser );
4302 // Clone to allow modifications of the return value without affecting cache
4303 return clone $this->mParserOptions
;
4307 * Get parser options suitable for rendering the primary article wikitext
4309 * @return ParserOptions
4311 public function makeParserOptions( User
$user ) {
4312 $options = ParserOptions
::newFromUser( $user );
4313 $options->enableLimitReport(); // show inclusion/loop reports
4314 $options->setTidy( true ); // fix bad HTML
4319 * Updates cascading protections
4321 * @param $parserOutput ParserOutput object, or boolean false
4323 protected function doCascadeProtectionUpdates( $parserOutput ) {
4324 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4328 // templatelinks table may have become out of sync,
4329 // especially if using variable-based transclusions.
4330 // For paranoia, check if things have changed and if
4331 // so apply updates to the database. This will ensure
4332 // that cascaded protections apply as soon as the changes
4335 # Get templates from templatelinks
4336 $id = $this->mTitle
->getArticleID();
4338 $tlTemplates = array();
4340 $dbr = wfGetDB( DB_SLAVE
);
4341 $res = $dbr->select( array( 'templatelinks' ),
4342 array( 'tl_namespace', 'tl_title' ),
4343 array( 'tl_from' => $id ),
4347 foreach ( $res as $row ) {
4348 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4351 # Get templates from parser output.
4352 $poTemplates = array();
4353 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4354 foreach ( $templates as $dbk => $id ) {
4355 $poTemplates["$ns:$dbk"] = true;
4360 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4362 if ( count( $templates_diff ) > 0 ) {
4363 # Whee, link updates time.
4364 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4370 * Update all the appropriate counts in the category table, given that
4371 * we've added the categories $added and deleted the categories $deleted.
4373 * @param $added array The names of categories that were added
4374 * @param $deleted array The names of categories that were deleted
4376 public function updateCategoryCounts( $added, $deleted ) {
4377 $ns = $this->mTitle
->getNamespace();
4378 $dbw = wfGetDB( DB_MASTER
);
4380 # First make sure the rows exist. If one of the "deleted" ones didn't
4381 # exist, we might legitimately not create it, but it's simpler to just
4382 # create it and then give it a negative value, since the value is bogus
4385 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4386 $insertCats = array_merge( $added, $deleted );
4387 if ( !$insertCats ) {
4388 # Okay, nothing to do
4392 $insertRows = array();
4394 foreach ( $insertCats as $cat ) {
4395 $insertRows[] = array(
4396 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4400 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4402 $addFields = array( 'cat_pages = cat_pages + 1' );
4403 $removeFields = array( 'cat_pages = cat_pages - 1' );
4405 if ( $ns == NS_CATEGORY
) {
4406 $addFields[] = 'cat_subcats = cat_subcats + 1';
4407 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4408 } elseif ( $ns == NS_FILE
) {
4409 $addFields[] = 'cat_files = cat_files + 1';
4410 $removeFields[] = 'cat_files = cat_files - 1';
4417 array( 'cat_title' => $added ),
4426 array( 'cat_title' => $deleted ),
4433 * Lightweight method to get the parser output for a page, checking the parser cache
4434 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4435 * consider, so it's not appropriate to use there.
4437 * @since 1.16 (r52326) for LiquidThreads
4439 * @param $oldid mixed integer Revision ID or null
4440 * @return ParserOutput or false if the given revsion ID is not found
4442 public function getParserOutput( $oldid = null ) {
4443 global $wgEnableParserCache, $wgUser;
4445 // Should the parser cache be used?
4446 $useParserCache = $wgEnableParserCache &&
4447 $wgUser->getStubThreshold() == 0 &&
4451 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4453 if ( $wgUser->getStubThreshold() ) {
4454 wfIncrStats( 'pcache_miss_stub' );
4457 if ( $useParserCache ) {
4458 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4459 if ( $parserOutput !== false ) {
4460 return $parserOutput;
4464 // Cache miss; parse and output it.
4465 if ( $oldid === null ) {
4466 $text = $this->getRawText();
4468 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4469 if ( $rev === null ) {
4472 $text = $rev->getText();
4475 return $this->getOutputFromWikitext( $text, $useParserCache );
4479 * Sets the context this Article is executed in
4481 * @param $context RequestContext
4484 public function setContext( $context ) {
4485 $this->mContext
= $context;
4489 * Gets the context this Article is executed in
4491 * @return RequestContext
4494 public function getContext() {
4495 if ( $this->mContext
instanceof RequestContext
) {
4496 return $this->mContext
;
4498 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4499 return RequestContext
::getMain();
4505 class PoolWorkArticleView
extends PoolCounterWork
{
4512 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4513 parent
::__construct( 'ArticleView', $key );
4514 $this->mArticle
= $article;
4515 $this->cacheable
= $useParserCache;
4516 $this->parserOptions
= $parserOptions;
4520 return $this->mArticle
->doViewParse();
4523 function getCachedWork() {
4526 $parserCache = ParserCache
::singleton();
4527 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4529 if ( $this->mArticle
->mParserOutput
!== false ) {
4530 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4531 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4532 # Ensure that UI elements requiring revision ID have
4533 # the correct version information.
4534 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4540 function fallback() {
4541 return $this->mArticle
->tryDirtyCache();
4545 * @param $status Status
4547 function error( $status ) {
4550 $wgOut->clearHTML(); // for release() errors
4551 $wgOut->enableClientCache( false );
4552 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4554 $errortext = $status->getWikiText( false, 'view-pool-error' );
4555 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );