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 $mForUpdate = false; // !<
31 var $mGoodAdjustment = 0; // !<
32 var $mIsRedirect = false; // !<
33 var $mLatest = false; // !<
35 var $mPreparedEdit = false;
40 var $mRedirectedFrom = null;
45 var $mRedirectTarget = null;
50 var $mRedirectUrl = false; // !<
51 var $mRevIdFetched = 0; // !<
56 var $mLastRevision = null;
61 var $mRevision = null;
63 var $mTimestamp = ''; // !<
64 var $mTitle; // !< Title object
65 var $mTotalAdjustment = 0; // !<
66 var $mTouched = '19700101000000'; // !<
81 * Constructor and clear the article
82 * @param $title Reference to a Title object.
83 * @param $oldId Integer revision ID, null to fetch from request, zero for current
85 public function __construct( Title
$title, $oldId = null ) {
86 // FIXME: does the reference play any role here?
87 $this->mTitle
=& $title;
88 $this->mOldId
= $oldId;
92 * Constructor from an page id
93 * @param $id Int article ID to load
95 public static function newFromID( $id ) {
96 $t = Title
::newFromID( $id );
97 # FIXME: doesn't inherit right
98 return $t == null ?
null : new self( $t );
99 # return $t == null ? null : new static( $t ); // PHP 5.3
103 * Tell the page view functions that this view was redirected
104 * from another page on the wiki.
105 * @param $from Title object.
107 public function setRedirectedFrom( Title
$from ) {
108 $this->mRedirectedFrom
= $from;
112 * If this page is a redirect, get its target
114 * The target will be fetched from the redirect table if possible.
115 * If this page doesn't have an entry there, call insertRedirect()
116 * @return mixed Title object, or null if this page is not a redirect
118 public function getRedirectTarget() {
119 if ( !$this->mTitle
->isRedirect() ) {
123 if ( $this->mRedirectTarget
!== null ) {
124 return $this->mRedirectTarget
;
127 # Query the redirect table
128 $dbr = wfGetDB( DB_SLAVE
);
129 $row = $dbr->selectRow( 'redirect',
130 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
131 array( 'rd_from' => $this->getID() ),
135 // rd_fragment and rd_interwiki were added later, populate them if empty
136 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
137 return $this->mRedirectTarget
= Title
::makeTitle(
138 $row->rd_namespace
, $row->rd_title
,
139 $row->rd_fragment
, $row->rd_interwiki
);
142 # This page doesn't have an entry in the redirect table
143 return $this->mRedirectTarget
= $this->insertRedirect();
147 * Insert an entry for this page into the redirect table.
149 * Don't call this function directly unless you know what you're doing.
150 * @return Title object or null if not a redirect
152 public function insertRedirect() {
153 // recurse through to only get the final target
154 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
158 $this->insertRedirectEntry( $retval );
163 * Insert or update the redirect table entry for this page to indicate
164 * it redirects to $rt .
165 * @param $rt Title redirect target
167 public function insertRedirectEntry( $rt ) {
168 $dbw = wfGetDB( DB_MASTER
);
169 $dbw->replace( 'redirect', array( 'rd_from' ),
171 'rd_from' => $this->getID(),
172 'rd_namespace' => $rt->getNamespace(),
173 'rd_title' => $rt->getDBkey(),
174 'rd_fragment' => $rt->getFragment(),
175 'rd_interwiki' => $rt->getInterwiki(),
182 * Get the Title object or URL this page redirects to
184 * @return mixed false, Title of in-wiki target, or string with URL
186 public function followRedirect() {
187 return $this->getRedirectURL( $this->getRedirectTarget() );
191 * Get the Title object this text redirects to
193 * @param $text string article content containing redirect info
194 * @return mixed false, Title of in-wiki target, or string with URL
195 * @deprecated since 1.17
197 public function followRedirectText( $text ) {
198 // recurse through to only get the final target
199 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
203 * Get the Title object or URL to use for a redirect. We use Title
204 * objects for same-wiki, non-special redirects and URLs for everything
206 * @param $rt Title Redirect target
207 * @return mixed false, Title object of local target, or string with URL
209 public function getRedirectURL( $rt ) {
211 if ( $rt->getInterwiki() != '' ) {
212 if ( $rt->isLocal() ) {
213 // Offsite wikis need an HTTP redirect.
215 // This can be hard to reverse and may produce loops,
216 // so they may be disabled in the site configuration.
217 $source = $this->mTitle
->getFullURL( 'redirect=no' );
218 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
221 if ( $rt->getNamespace() == NS_SPECIAL
) {
222 // Gotta handle redirects to special pages differently:
223 // Fill the HTTP response "Location" header and ignore
224 // the rest of the page we're on.
226 // This can be hard to reverse, so they may be disabled.
227 if ( $rt->isSpecial( 'Userlogout' ) ) {
230 return $rt->getFullURL();
238 // No or invalid redirect
243 * Get the title object of the article
244 * @return Title object of this page
246 public function getTitle() {
247 return $this->mTitle
;
252 * FIXME: shouldn't this be public?
255 public function clear() {
256 $this->mDataLoaded
= false;
257 $this->mContentLoaded
= false;
259 $this->mCounter
= -1; # Not loaded
260 $this->mRedirectedFrom
= null; # Title object if set
261 $this->mRedirectTarget
= null; # Title object if set
262 $this->mLastRevision
= null; # Latest revision
263 $this->mTimestamp
= '';
264 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
265 $this->mTouched
= '19700101000000';
266 $this->mForUpdate
= false;
267 $this->mIsRedirect
= false;
268 $this->mRevIdFetched
= 0;
269 $this->mRedirectUrl
= false;
270 $this->mLatest
= false;
271 $this->mPreparedEdit
= false;
275 * Note that getContent/loadContent do not follow redirects anymore.
276 * If you need to fetch redirectable content easily, try
277 * the shortcut in Article::followRedirect()
279 * This function has side effects! Do not use this function if you
280 * only want the real revision text if any.
282 * @return Return the text of this revision
284 public function getContent() {
287 wfProfileIn( __METHOD__
);
289 if ( $this->getID() === 0 ) {
290 # If this is a MediaWiki:x message, then load the messages
291 # and return the message value for x.
292 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
293 $text = $this->mTitle
->getDefaultMessageText();
294 if ( $text === false ) {
298 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
300 wfProfileOut( __METHOD__
);
304 $this->loadContent();
305 wfProfileOut( __METHOD__
);
307 return $this->mContent
;
312 * Get the text of the current revision. No side-effects...
314 * @return Return the text of the current revision
316 public function getRawText() {
317 // Check process cache for current revision
318 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
319 return $this->mContent
;
322 $rev = Revision
::newFromTitle( $this->mTitle
);
323 $text = $rev ?
$rev->getRawText() : false;
329 * This function returns the text of a section, specified by a number ($section).
330 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
331 * the first section before any such heading (section 0).
333 * If a section contains subsections, these are also returned.
335 * @param $text String: text to look in
336 * @param $section Integer: section number
337 * @return string text of the requested section
340 public function getSection( $text, $section ) {
342 return $wgParser->getSection( $text, $section );
346 * Get the text that needs to be saved in order to undo all revisions
347 * between $undo and $undoafter. Revisions must belong to the same page,
348 * must exist and must not be deleted
349 * @param $undo Revision
350 * @param $undoafter Revision Must be an earlier revision than $undo
351 * @return mixed string on success, false on failure
353 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
354 $currentRev = Revision
::newFromTitle( $this->mTitle
);
355 if ( !$currentRev ) {
356 return false; // no page
358 $undo_text = $undo->getText();
359 $undoafter_text = $undoafter->getText();
360 $cur_text = $currentRev->getText();
362 if ( $cur_text == $undo_text ) {
363 # No use doing a merge if it's just a straight revert.
364 return $undoafter_text;
369 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
377 * @return int The oldid of the article that is to be shown, 0 for the
380 public function getOldID() {
381 if ( is_null( $this->mOldId
) ) {
382 $this->mOldId
= $this->getOldIDFromRequest();
385 return $this->mOldId
;
389 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
391 * @return int The old id for the request
393 public function getOldIDFromRequest() {
396 $this->mRedirectUrl
= false;
398 $oldid = $wgRequest->getVal( 'oldid' );
400 if ( isset( $oldid ) ) {
401 $oldid = intval( $oldid );
402 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
403 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
407 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
409 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
410 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
425 * Load the revision (including text) into this object
427 function loadContent() {
428 if ( $this->mContentLoaded
) {
432 wfProfileIn( __METHOD__
);
434 $this->fetchContent( $this->getOldID() );
436 wfProfileOut( __METHOD__
);
440 * Return the list of revision fields that should be selected to create
443 public static function selectFields() {
460 * Fetch a page record with the given conditions
461 * @param $dbr DatabaseBase object
462 * @param $conditions Array
463 * @return mixed Database result resource, or false on failure
465 protected function pageData( $dbr, $conditions ) {
466 $fields = self
::selectFields();
468 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
470 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
472 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
478 * Fetch a page record matching the Title object's namespace and title
479 * using a sanitized title string
481 * @param $dbr DatabaseBase object
482 * @param $title Title object
483 * @return mixed Database result resource, or false on failure
485 protected function pageDataFromTitle( $dbr, $title ) {
486 return $this->pageData( $dbr, array(
487 'page_namespace' => $title->getNamespace(),
488 'page_title' => $title->getDBkey() ) );
492 * Fetch a page record matching the requested ID
494 * @param $dbr DatabaseBase
496 * @return mixed Database result resource, or false on failure
498 protected function pageDataFromId( $dbr, $id ) {
499 return $this->pageData( $dbr, array( 'page_id' => $id ) );
503 * Set the general counter, title etc data loaded from
506 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
508 public function loadPageData( $data = 'fromdb' ) {
509 if ( $data === 'fromdb' ) {
510 $dbr = wfGetDB( DB_SLAVE
);
511 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
514 $lc = LinkCache
::singleton();
517 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
519 $this->mTitle
->mArticleID
= intval( $data->page_id
);
521 # Old-fashioned restrictions
522 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
524 $this->mCounter
= intval( $data->page_counter
);
525 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
526 $this->mIsRedirect
= intval( $data->page_is_redirect
);
527 $this->mLatest
= intval( $data->page_latest
);
529 $lc->addBadLinkObj( $this->mTitle
);
530 $this->mTitle
->mArticleID
= 0;
533 $this->mDataLoaded
= true;
537 * Get text of an article from database
538 * Does *NOT* follow redirects.
540 * @param $oldid Int: 0 for whatever the latest revision is
541 * @return mixed string containing article contents, or false if null
543 function fetchContent( $oldid = 0 ) {
544 if ( $this->mContentLoaded
) {
545 return $this->mContent
;
548 # Pre-fill content with error message so that if something
549 # fails we'll have something telling us what we intended.
550 $t = $this->mTitle
->getPrefixedText();
551 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
552 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
555 $revision = Revision
::newFromId( $oldid );
556 if ( $revision === null ) {
557 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
561 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
562 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
565 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
569 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
570 $this->loadPageData( $data );
573 if ( !$this->mDataLoaded
) {
574 $this->loadPageData();
577 if ( $this->mLatest
=== false ) {
578 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
582 $revision = Revision
::newFromId( $this->mLatest
);
583 if ( $revision === null ) {
584 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
589 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
590 // We should instead work with the Revision object when we need it...
591 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
593 if ( $revision->getId() == $this->mLatest
) {
594 $this->setLastEdit( $revision );
597 $this->mRevIdFetched
= $revision->getId();
598 $this->mContentLoaded
= true;
599 $this->mRevision
=& $revision;
601 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
603 return $this->mContent
;
607 * Read/write accessor to select FOR UPDATE
608 * @FIXME: remove, does nothing
610 * @param $x Mixed: FIXME
611 * @return mixed value of $x, or value stored in Article::mForUpdate
613 public function forUpdate( $x = null ) {
614 wfDeprecated( __METHOD__
);
615 return wfSetVar( $this->mForUpdate
, $x );
619 * @return int Page ID
621 public function getID() {
622 return $this->mTitle
->getArticleID();
626 * @return bool Whether or not the page exists in the database
628 public function exists() {
629 return $this->getId() > 0;
633 * Check if this page is something we're going to be showing
634 * some sort of sensible content for. If we return false, page
635 * views (plain action=view) will return an HTTP 404 response,
636 * so spiders and robots can know they're following a bad link.
640 public function hasViewableContent() {
641 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
645 * @return int The view count for the page
647 public function getCount() {
648 if ( -1 == $this->mCounter
) {
649 $id = $this->getID();
654 $dbr = wfGetDB( DB_SLAVE
);
655 $this->mCounter
= $dbr->selectField( 'page',
657 array( 'page_id' => $id ),
663 return $this->mCounter
;
667 * Determine whether a page would be suitable for being counted as an
668 * article in the site_stats table based on the title & its content
670 * @param $text String: text to analyze
673 public function isCountable( $text ) {
674 global $wgUseCommaCount;
676 $token = $wgUseCommaCount ?
',' : '[[';
678 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
682 * Tests if the article text represents a redirect
684 * @param $text mixed string containing article contents, or boolean
687 public function isRedirect( $text = false ) {
688 if ( $text === false ) {
689 if ( !$this->mDataLoaded
) {
690 $this->loadPageData();
693 return (bool)$this->mIsRedirect
;
695 return Title
::newFromRedirect( $text ) !== null;
700 * Returns true if the currently-referenced revision is the current edit
701 * to this page (and it exists).
704 public function isCurrent() {
705 # If no oldid, this is the current version.
706 if ( $this->getOldID() == 0 ) {
710 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
714 * Loads everything except the text
715 * This isn't necessary for all uses, so it's only done if needed.
717 protected function loadLastEdit() {
718 if ( $this->mLastRevision
!== null ) {
719 return; // already loaded
722 # New or non-existent articles have no user information
723 $id = $this->getID();
728 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
730 $this->setLastEdit( $revision );
735 * Set the latest revision
737 protected function setLastEdit( Revision
$revision ) {
738 $this->mLastRevision
= $revision;
739 $this->mTimestamp
= $revision->getTimestamp();
743 * @return string GMT timestamp of last article revision
745 public function getTimestamp() {
746 // Check if the field has been filled by ParserCache::get()
747 if ( !$this->mTimestamp
) {
748 $this->loadLastEdit();
750 return wfTimestamp( TS_MW
, $this->mTimestamp
);
754 * @param $audience Integer: one of:
755 * Revision::FOR_PUBLIC to be displayed to all users
756 * Revision::FOR_THIS_USER to be displayed to $wgUser
757 * Revision::RAW get the text regardless of permissions
758 * @return int user ID for the user that made the last article revision
760 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
761 $this->loadLastEdit();
762 if ( $this->mLastRevision
) {
763 return $this->mLastRevision
->getUser( $audience );
770 * @param $audience Integer: one of:
771 * Revision::FOR_PUBLIC to be displayed to all users
772 * Revision::FOR_THIS_USER to be displayed to $wgUser
773 * Revision::RAW get the text regardless of permissions
774 * @return string username of the user that made the last article revision
776 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
777 $this->loadLastEdit();
778 if ( $this->mLastRevision
) {
779 return $this->mLastRevision
->getUserText( $audience );
786 * @param $audience Integer: one of:
787 * Revision::FOR_PUBLIC to be displayed to all users
788 * Revision::FOR_THIS_USER to be displayed to $wgUser
789 * Revision::RAW get the text regardless of permissions
790 * @return string Comment stored for the last article revision
792 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
793 $this->loadLastEdit();
794 if ( $this->mLastRevision
) {
795 return $this->mLastRevision
->getComment( $audience );
802 * Returns true if last revision was marked as "minor edit"
804 * @return boolean Minor edit indicator for the last article revision.
806 public function getMinorEdit() {
807 $this->loadLastEdit();
808 if ( $this->mLastRevision
) {
809 return $this->mLastRevision
->isMinor();
816 * Use this to fetch the rev ID used on page views
818 * @return int revision ID of last article revision
820 public function getRevIdFetched() {
821 if ( $this->mRevIdFetched
) {
822 return $this->mRevIdFetched
;
824 return $this->getLatest();
829 * Get a list of users who have edited this article, not including the user who made
830 * the most recent revision, which you can get from $article->getUser() if you want it
833 public function getContributors() {
834 # FIXME: this is expensive; cache this info somewhere.
836 $dbr = wfGetDB( DB_SLAVE
);
837 $userTable = $dbr->tableName( 'user' );
839 if ( $dbr->implicitGroupby() ) {
840 $realNameField = 'user_real_name';
842 $realNameField = 'FIRST(user_real_name) AS user_real_name';
845 $tables = array( 'revision', 'user' );
848 'rev_user as user_id',
849 'rev_user_text AS user_name',
851 'MAX(rev_timestamp) AS timestamp',
854 $conds = array( 'rev_page' => $this->getId() );
856 // The user who made the top revision gets credited as "this page was last edited by
857 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
858 $user = $this->getUser();
860 $conds[] = "rev_user != $user";
862 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
865 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
868 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
872 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
873 'ORDER BY' => 'timestamp DESC',
876 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
877 return new UserArrayFromResult( $res );
881 * This is the default action of the index.php entry point: just view the
882 * page of the given title.
884 public function view() {
885 global $wgUser, $wgOut, $wgRequest, $wgParser;
886 global $wgUseFileCache, $wgUseETag;
888 wfProfileIn( __METHOD__
);
890 # Get variables from query string
891 $oldid = $this->getOldID();
893 # getOldID may want us to redirect somewhere else
894 if ( $this->mRedirectUrl
) {
895 $wgOut->redirect( $this->mRedirectUrl
);
896 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
897 wfProfileOut( __METHOD__
);
902 $wgOut->setArticleFlag( true );
903 # Set page title (may be overridden by DISPLAYTITLE)
904 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
906 # If we got diff in the query, we want to see a diff page instead of the article.
907 if ( $wgRequest->getCheck( 'diff' ) ) {
908 wfDebug( __METHOD__
. ": showing diff page\n" );
909 $this->showDiffPage();
910 wfProfileOut( __METHOD__
);
915 # Allow frames by default
916 $wgOut->allowClickjacking();
918 $parserCache = ParserCache
::singleton();
920 $parserOptions = $this->getParserOptions();
921 # Render printable version, use printable version cache
922 if ( $wgOut->isPrintable() ) {
923 $parserOptions->setIsPrintable( true );
924 $parserOptions->setEditSection( false );
925 } else if ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
926 $parserOptions->setEditSection( false );
929 # Try client and file cache
930 if ( $oldid === 0 && $this->checkTouched() ) {
932 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
935 # Is it client cached?
936 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
937 wfDebug( __METHOD__
. ": done 304\n" );
938 wfProfileOut( __METHOD__
);
942 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
943 wfDebug( __METHOD__
. ": done file cache\n" );
944 # tell wgOut that output is taken care of
946 $this->viewUpdates();
947 wfProfileOut( __METHOD__
);
953 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
954 $parserOptions->setEditSection( false );
957 # Should the parser cache be used?
958 $useParserCache = $this->useParserCache( $oldid );
959 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
960 if ( $wgUser->getStubThreshold() ) {
961 wfIncrStats( 'pcache_miss_stub' );
964 $wasRedirected = $this->showRedirectedFromHeader();
965 $this->showNamespaceHeader();
967 # Iterate through the possible ways of constructing the output text.
968 # Keep going until $outputDone is set, or we run out of things to do.
971 $this->mParserOutput
= false;
973 while ( !$outputDone && ++
$pass ) {
976 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
979 # Try the parser cache
980 if ( $useParserCache ) {
981 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
983 if ( $this->mParserOutput
!== false ) {
984 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
985 $wgOut->addParserOutput( $this->mParserOutput
);
986 # Ensure that UI elements requiring revision ID have
987 # the correct version information.
988 $wgOut->setRevisionId( $this->mLatest
);
994 $text = $this->getContent();
995 if ( $text === false ||
$this->getID() == 0 ) {
996 wfDebug( __METHOD__
. ": showing missing article\n" );
997 $this->showMissingArticle();
998 wfProfileOut( __METHOD__
);
1002 # Another whitelist check in case oldid is altering the title
1003 if ( !$this->mTitle
->userCanRead() ) {
1004 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
1005 $wgOut->loginToUse();
1008 wfProfileOut( __METHOD__
);
1012 # Are we looking at an old revision
1013 if ( $oldid && !is_null( $this->mRevision
) ) {
1014 $this->setOldSubtitle( $oldid );
1016 if ( !$this->showDeletedRevisionHeader() ) {
1017 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
1018 wfProfileOut( __METHOD__
);
1022 # If this "old" version is the current, then try the parser cache...
1023 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
1024 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1025 if ( $this->mParserOutput
) {
1026 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
1027 $wgOut->addParserOutput( $this->mParserOutput
);
1028 $wgOut->setRevisionId( $this->mLatest
);
1035 # Ensure that UI elements requiring revision ID have
1036 # the correct version information.
1037 $wgOut->setRevisionId( $this->getRevIdFetched() );
1039 # Pages containing custom CSS or JavaScript get special treatment
1040 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1041 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1042 $this->showCssOrJsPage();
1045 $rt = Title
::newFromRedirectArray( $text );
1047 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1048 # Viewing a redirect page (e.g. with parameter redirect=no)
1049 # Don't append the subtitle if this was an old revision
1050 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1051 # Parse just to get categories, displaytitle, etc.
1052 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1053 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1059 # Run the parse, protected by a pool counter
1060 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1062 $key = $parserCache->getKey( $this, $parserOptions );
1063 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1065 if ( !$poolArticleView->execute() ) {
1066 # Connection or timeout error
1067 wfProfileOut( __METHOD__
);
1073 # Should be unreachable, but just in case...
1079 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1080 if ( $this->mParserOutput
) {
1081 $titleText = $this->mParserOutput
->getTitleText();
1083 if ( strval( $titleText ) !== '' ) {
1084 $wgOut->setPageTitle( $titleText );
1088 # For the main page, overwrite the <title> element with the con-
1089 # tents of 'pagetitle-view-mainpage' instead of the default (if
1090 # that's not empty).
1091 # This message always exists because it is in the i18n files
1092 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1093 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1094 if ( !$msg->isDisabled() ) {
1095 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1099 # Now that we've filled $this->mParserOutput, we know whether
1100 # there are any __NOINDEX__ tags on the page
1101 $policy = $this->getRobotPolicy( 'view' );
1102 $wgOut->setIndexPolicy( $policy['index'] );
1103 $wgOut->setFollowPolicy( $policy['follow'] );
1105 $this->showViewFooter();
1106 $this->viewUpdates();
1107 wfProfileOut( __METHOD__
);
1111 * Show a diff page according to current request variables. For use within
1112 * Article::view() only, other callers should use the DifferenceEngine class.
1114 public function showDiffPage() {
1115 global $wgRequest, $wgUser;
1117 $diff = $wgRequest->getVal( 'diff' );
1118 $rcid = $wgRequest->getVal( 'rcid' );
1119 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1120 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1121 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1122 $oldid = $this->getOldID();
1124 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1125 // DifferenceEngine directly fetched the revision:
1126 $this->mRevIdFetched
= $de->mNewid
;
1127 $de->showDiffPage( $diffOnly );
1129 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1130 # Run view updates for current revision only
1131 $this->viewUpdates();
1136 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1137 * Article::view() only.
1139 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1142 protected function showCssOrJsPage() {
1145 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1147 // Give hooks a chance to customise the output
1148 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1149 // Wrap the whole lot in a <pre> and don't parse
1151 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1152 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1153 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1154 $wgOut->addHTML( "\n</pre>\n" );
1159 * Get the robot policy to be used for the current view
1160 * @param $action String the action= GET parameter
1161 * @return Array the policy that should be set
1162 * TODO: actions other than 'view'
1164 public function getRobotPolicy( $action ) {
1165 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1166 global $wgDefaultRobotPolicy, $wgRequest;
1168 $ns = $this->mTitle
->getNamespace();
1170 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1171 # Don't index user and user talk pages for blocked users (bug 11443)
1172 if ( !$this->mTitle
->isSubpage() ) {
1173 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1175 'index' => 'noindex',
1176 'follow' => 'nofollow'
1182 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1183 # Non-articles (special pages etc), and old revisions
1185 'index' => 'noindex',
1186 'follow' => 'nofollow'
1188 } elseif ( $wgOut->isPrintable() ) {
1189 # Discourage indexing of printable versions, but encourage following
1191 'index' => 'noindex',
1192 'follow' => 'follow'
1194 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1195 # For ?curid=x urls, disallow indexing
1197 'index' => 'noindex',
1198 'follow' => 'follow'
1202 # Otherwise, construct the policy based on the various config variables.
1203 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1205 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1206 # Honour customised robot policies for this namespace
1207 $policy = array_merge(
1209 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1212 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1213 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1214 # a final sanity check that we have really got the parser output.
1215 $policy = array_merge(
1217 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1221 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1222 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1223 $policy = array_merge(
1225 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1233 * Converts a String robot policy into an associative array, to allow
1234 * merging of several policies using array_merge().
1235 * @param $policy Mixed, returns empty array on null/false/'', transparent
1236 * to already-converted arrays, converts String.
1237 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1239 public static function formatRobotPolicy( $policy ) {
1240 if ( is_array( $policy ) ) {
1242 } elseif ( !$policy ) {
1246 $policy = explode( ',', $policy );
1247 $policy = array_map( 'trim', $policy );
1250 foreach ( $policy as $var ) {
1251 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1252 $arr['index'] = $var;
1253 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1254 $arr['follow'] = $var;
1262 * If this request is a redirect view, send "redirected from" subtitle to
1263 * $wgOut. Returns true if the header was needed, false if this is not a
1264 * redirect view. Handles both local and remote redirects.
1268 public function showRedirectedFromHeader() {
1269 global $wgOut, $wgRequest, $wgRedirectSources;
1271 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1273 if ( isset( $this->mRedirectedFrom
) ) {
1274 // This is an internally redirected page view.
1275 // We'll need a backlink to the source page for navigation.
1276 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1277 $redir = Linker
::link(
1278 $this->mRedirectedFrom
,
1281 array( 'redirect' => 'no' ),
1282 array( 'known', 'noclasses' )
1285 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1286 $wgOut->setSubtitle( $s );
1288 // Set the fragment if one was specified in the redirect
1289 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1290 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1291 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1294 // Add a <link rel="canonical"> tag
1295 $wgOut->addLink( array( 'rel' => 'canonical',
1296 'href' => $this->mTitle
->getLocalURL() )
1301 } elseif ( $rdfrom ) {
1302 // This is an externally redirected view, from some other wiki.
1303 // If it was reported from a trusted site, supply a backlink.
1304 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1305 $redir = Linker
::makeExternalLink( $rdfrom, $rdfrom );
1306 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1307 $wgOut->setSubtitle( $s );
1317 * Show a header specific to the namespace currently being viewed, like
1318 * [[MediaWiki:Talkpagetext]]. For Article::view().
1320 public function showNamespaceHeader() {
1323 if ( $this->mTitle
->isTalkPage() ) {
1324 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1325 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1331 * Show the footer section of an ordinary page view
1333 public function showViewFooter() {
1334 global $wgOut, $wgUseTrackbacks;
1336 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1337 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1338 $wgOut->addWikiMsg( 'anontalkpagetext' );
1341 # If we have been passed an &rcid= parameter, we want to give the user a
1342 # chance to mark this new article as patrolled.
1343 $this->showPatrolFooter();
1346 if ( $wgUseTrackbacks ) {
1347 $this->addTrackbacks();
1350 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1355 * If patrol is possible, output a patrol UI box. This is called from the
1356 * footer section of ordinary page views. If patrol is not possible or not
1357 * desired, does nothing.
1359 public function showPatrolFooter() {
1360 global $wgOut, $wgRequest, $wgUser;
1362 $rcid = $wgRequest->getVal( 'rcid' );
1364 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1368 $token = $wgUser->editToken( $rcid );
1369 $wgOut->preventClickjacking();
1372 "<div class='patrollink'>" .
1374 'markaspatrolledlink',
1377 wfMsgHtml( 'markaspatrolledtext' ),
1380 'action' => 'markpatrolled',
1384 array( 'known', 'noclasses' )
1392 * Show the error text for a missing article. For articles in the MediaWiki
1393 * namespace, show the default message text. To be called from Article::view().
1395 public function showMissingArticle() {
1396 global $wgOut, $wgRequest, $wgUser;
1398 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1399 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1400 $parts = explode( '/', $this->mTitle
->getText() );
1401 $rootPart = $parts[0];
1402 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1403 $ip = User
::isIP( $rootPart );
1405 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1406 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1407 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1408 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1409 LogEventsList
::showLogExtract(
1412 $user->getUserPage()->getPrefixedText(),
1416 'showIfEmpty' => false,
1418 'blocked-notice-logextract',
1419 $user->getName() # Support GENDER in notice
1426 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1428 # Show delete and move logs
1429 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1431 'conds' => array( "log_action != 'revision'" ),
1432 'showIfEmpty' => false,
1433 'msgKey' => array( 'moveddeleted-notice' ) )
1436 # Show error message
1437 $oldid = $this->getOldID();
1439 $text = wfMsgNoTrans( 'missing-article',
1440 $this->mTitle
->getPrefixedText(),
1441 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1442 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1443 // Use the default message text
1444 $text = $this->mTitle
->getDefaultMessageText();
1446 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1447 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1448 $errors = array_merge( $createErrors, $editErrors );
1450 if ( !count( $errors ) ) {
1451 $text = wfMsgNoTrans( 'noarticletext' );
1453 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1456 $text = "<div class='noarticletext'>\n$text\n</div>";
1458 if ( !$this->hasViewableContent() ) {
1459 // If there's no backing content, send a 404 Not Found
1460 // for better machine handling of broken links.
1461 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1464 $wgOut->addWikiText( $text );
1468 * If the revision requested for view is deleted, check permissions.
1469 * Send either an error message or a warning header to $wgOut.
1471 * @return boolean true if the view is allowed, false if not.
1473 public function showDeletedRevisionHeader() {
1474 global $wgOut, $wgRequest;
1476 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1481 // If the user is not allowed to see it...
1482 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1483 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1484 'rev-deleted-text-permission' );
1487 // If the user needs to confirm that they want to see it...
1488 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1489 # Give explanation and add a link to view the revision...
1490 $oldid = intval( $this->getOldID() );
1491 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1492 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1493 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1494 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1495 array( $msg, $link ) );
1498 // We are allowed to see...
1500 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1501 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1502 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1509 * Should the parser cache be used?
1513 public function useParserCache( $oldid ) {
1514 global $wgUser, $wgEnableParserCache;
1516 return $wgEnableParserCache
1517 && $wgUser->getStubThreshold() == 0
1520 && !$this->mTitle
->isCssOrJsPage()
1521 && !$this->mTitle
->isCssJsSubpage();
1525 * Execute the uncached parse for action=view
1527 public function doViewParse() {
1530 $oldid = $this->getOldID();
1531 $parserOptions = $this->getParserOptions();
1533 # Render printable version, use printable version cache
1534 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1536 # Don't show section-edit links on old revisions... this way lies madness.
1537 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1538 $parserOptions->setEditSection( false );
1541 $useParserCache = $this->useParserCache( $oldid );
1542 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1548 * Try to fetch an expired entry from the parser cache. If it is present,
1549 * output it and return true. If it is not present, output nothing and
1550 * return false. This is used as a callback function for
1551 * PoolCounter::executeProtected().
1555 public function tryDirtyCache() {
1557 $parserCache = ParserCache
::singleton();
1558 $options = $this->getParserOptions();
1560 if ( $wgOut->isPrintable() ) {
1561 $options->setIsPrintable( true );
1562 $options->setEditSection( false );
1565 $output = $parserCache->getDirty( $this, $options );
1568 wfDebug( __METHOD__
. ": sending dirty output\n" );
1569 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1570 $wgOut->setSquidMaxage( 0 );
1571 $this->mParserOutput
= $output;
1572 $wgOut->addParserOutput( $output );
1573 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1577 wfDebugLog( 'dirty', "dirty missing\n" );
1578 wfDebug( __METHOD__
. ": no dirty cache\n" );
1587 * @param $target Title|Array of destination(s) to redirect
1588 * @param $appendSubtitle Boolean [optional]
1589 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1590 * @return string containing HMTL with redirect link
1592 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1593 global $wgOut, $wgContLang, $wgStylePath;
1595 if ( !is_array( $target ) ) {
1596 $target = array( $target );
1599 $imageDir = $wgContLang->getDir();
1601 if ( $appendSubtitle ) {
1602 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1605 // the loop prepends the arrow image before the link, so the first case needs to be outside
1606 $title = array_shift( $target );
1608 if ( $forceKnown ) {
1609 $link = Linker
::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1611 $link = Linker
::link( $title, htmlspecialchars( $title->getFullText() ) );
1614 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1615 $alt = $wgContLang->isRTL() ?
'←' : '→';
1616 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1617 foreach ( $target as $rt ) {
1618 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1619 if ( $forceKnown ) {
1620 $link .= Linker
::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1622 $link .= Linker
::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1626 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1627 return '<div class="redirectMsg">' .
1628 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1629 '<span class="redirectText">' . $link . '</span></div>';
1633 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1635 public function addTrackbacks() {
1638 $dbr = wfGetDB( DB_SLAVE
);
1639 $tbs = $dbr->select( 'trackbacks',
1640 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1641 array( 'tb_page' => $this->getID() )
1644 if ( !$dbr->numRows( $tbs ) ) {
1648 $wgOut->preventClickjacking();
1651 foreach ( $tbs as $o ) {
1654 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1655 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1656 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1657 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1661 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1669 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1673 * Removes trackback record for current article from trackbacks table
1675 public function deletetrackback() {
1676 global $wgRequest, $wgOut;
1678 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1679 $wgOut->addWikiMsg( 'sessionfailure' );
1684 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
1686 if ( count( $permission_errors ) ) {
1687 $wgOut->showPermissionsErrorPage( $permission_errors );
1692 $db = wfGetDB( DB_MASTER
);
1693 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1695 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1696 $this->mTitle
->invalidateCache();
1700 * Handle action=render
1703 public function render() {
1706 $wgOut->setArticleBodyOnly( true );
1711 * Handle action=purge
1713 public function purge() {
1714 return Action
::factory( 'purge', $this )->show();
1718 * Perform the actions of a page purging
1720 public function doPurge() {
1723 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1727 // Invalidate the cache
1728 $this->mTitle
->invalidateCache();
1731 if ( $wgUseSquid ) {
1732 // Commit the transaction before the purge is sent
1733 $dbw = wfGetDB( DB_MASTER
);
1737 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1738 $update->doUpdate();
1741 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1742 if ( $this->getID() == 0 ) {
1745 $text = $this->getRawText();
1748 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1753 * Insert a new empty page record for this article.
1754 * This *must* be followed up by creating a revision
1755 * and running $this->updateRevisionOn( ... );
1756 * or else the record will be left in a funky state.
1757 * Best if all done inside a transaction.
1759 * @param $dbw Database
1760 * @return int The newly created page_id key, or false if the title already existed
1763 public function insertOn( $dbw ) {
1764 wfProfileIn( __METHOD__
);
1766 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1767 $dbw->insert( 'page', array(
1768 'page_id' => $page_id,
1769 'page_namespace' => $this->mTitle
->getNamespace(),
1770 'page_title' => $this->mTitle
->getDBkey(),
1771 'page_counter' => 0,
1772 'page_restrictions' => '',
1773 'page_is_redirect' => 0, # Will set this shortly...
1775 'page_random' => wfRandom(),
1776 'page_touched' => $dbw->timestamp(),
1777 'page_latest' => 0, # Fill this in shortly...
1778 'page_len' => 0, # Fill this in shortly...
1779 ), __METHOD__
, 'IGNORE' );
1781 $affected = $dbw->affectedRows();
1784 $newid = $dbw->insertId();
1785 $this->mTitle
->resetArticleID( $newid );
1787 wfProfileOut( __METHOD__
);
1789 return $affected ?
$newid : false;
1793 * Update the page record to point to a newly saved revision.
1795 * @param $dbw DatabaseBase: object
1796 * @param $revision Revision: For ID number, and text used to set
1797 length and redirect status fields
1798 * @param $lastRevision Integer: if given, will not overwrite the page field
1799 * when different from the currently set value.
1800 * Giving 0 indicates the new page flag should be set
1802 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1803 * removing rows in redirect table.
1804 * @return bool true on success, false on failure
1807 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1808 wfProfileIn( __METHOD__
);
1810 $text = $revision->getText();
1811 $rt = Title
::newFromRedirectRecurse( $text );
1813 $conditions = array( 'page_id' => $this->getId() );
1815 if ( !is_null( $lastRevision ) ) {
1816 # An extra check against threads stepping on each other
1817 $conditions['page_latest'] = $lastRevision;
1820 $dbw->update( 'page',
1822 'page_latest' => $revision->getId(),
1823 'page_touched' => $dbw->timestamp(),
1824 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1825 'page_is_redirect' => $rt !== null ?
1 : 0,
1826 'page_len' => strlen( $text ),
1831 $result = $dbw->affectedRows() != 0;
1833 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1836 wfProfileOut( __METHOD__
);
1841 * Add row to the redirect table if this is a redirect, remove otherwise.
1843 * @param $dbw DatabaseBase
1844 * @param $redirectTitle Title object pointing to the redirect target,
1845 * or NULL if this is not a redirect
1846 * @param $lastRevIsRedirect If given, will optimize adding and
1847 * removing rows in redirect table.
1848 * @return bool true on success, false on failure
1851 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1852 // Always update redirects (target link might have changed)
1853 // Update/Insert if we don't know if the last revision was a redirect or not
1854 // Delete if changing from redirect to non-redirect
1855 $isRedirect = !is_null( $redirectTitle );
1857 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1861 wfProfileIn( __METHOD__
);
1862 if ( $isRedirect ) {
1863 $this->insertRedirectEntry( $redirectTitle );
1865 // This is not a redirect, remove row from redirect table
1866 $where = array( 'rd_from' => $this->getId() );
1867 $dbw->delete( 'redirect', $where, __METHOD__
);
1870 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1871 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1873 wfProfileOut( __METHOD__
);
1875 return ( $dbw->affectedRows() != 0 );
1879 * If the given revision is newer than the currently set page_latest,
1880 * update the page record. Otherwise, do nothing.
1882 * @param $dbw Database object
1883 * @param $revision Revision object
1886 public function updateIfNewerOn( &$dbw, $revision ) {
1887 wfProfileIn( __METHOD__
);
1889 $row = $dbw->selectRow(
1890 array( 'revision', 'page' ),
1891 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1893 'page_id' => $this->getId(),
1894 'page_latest=rev_id' ),
1898 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1899 wfProfileOut( __METHOD__
);
1902 $prev = $row->rev_id
;
1903 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1905 # No or missing previous revision; mark the page as new
1907 $lastRevIsRedirect = null;
1910 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1912 wfProfileOut( __METHOD__
);
1917 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1918 * @param $text String: new text of the section
1919 * @param $summary String: new section's subject, only if $section is 'new'
1920 * @param $edittime String: revision timestamp or null to use the current revision
1921 * @return string Complete article text, or null if error
1923 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1924 wfProfileIn( __METHOD__
);
1926 if ( strval( $section ) == '' ) {
1927 // Whole-page edit; let the whole text through
1929 if ( is_null( $edittime ) ) {
1930 $rev = Revision
::newFromTitle( $this->mTitle
);
1932 $dbw = wfGetDB( DB_MASTER
);
1933 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1937 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1938 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1939 wfProfileOut( __METHOD__
);
1943 $oldtext = $rev->getText();
1945 if ( $section == 'new' ) {
1946 # Inserting a new section
1947 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1948 $text = strlen( trim( $oldtext ) ) > 0
1949 ?
"{$oldtext}\n\n{$subject}{$text}"
1950 : "{$subject}{$text}";
1952 # Replacing an existing section; roll out the big guns
1955 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1959 wfProfileOut( __METHOD__
);
1964 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1966 * @return Int updated $flags
1968 function checkFlags( $flags ) {
1969 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1970 if ( $this->mTitle
->getArticleID() ) {
1971 $flags |
= EDIT_UPDATE
;
1983 * Change an existing article or create a new article. Updates RC and all necessary caches,
1984 * optionally via the deferred update array.
1986 * $wgUser must be set before calling this function.
1988 * @param $text String: new text
1989 * @param $summary String: edit summary
1990 * @param $flags Integer bitfield:
1992 * Article is known or assumed to be non-existent, create a new one
1994 * Article is known or assumed to be pre-existing, update it
1996 * Mark this edit minor, if the user is allowed to do so
1998 * Do not log the change in recentchanges
2000 * Mark the edit a "bot" edit regardless of user rights
2001 * EDIT_DEFER_UPDATES
2002 * Defer some of the updates until the end of index.php
2004 * Fill in blank summaries with generated text where possible
2006 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2007 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2008 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2009 * edit-already-exists error will be returned. These two conditions are also possible with
2010 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2012 * @param $baseRevId the revision ID this edit was based off, if any
2013 * @param $user User (optional), $wgUser will be used if not passed
2015 * @return Status object. Possible errors:
2016 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2017 * edit-gone-missing: In update mode, but the article didn't exist
2018 * edit-conflict: In update mode, the article changed unexpectedly
2019 * edit-no-change: Warning that the text was the same as before
2020 * edit-already-exists: In creation mode, but the article already exists
2022 * Extensions may define additional errors.
2024 * $return->value will contain an associative array with members as follows:
2025 * new: Boolean indicating if the function attempted to create a new article
2026 * revision: The revision object for the inserted revision, or null
2028 * Compatibility note: this function previously returned a boolean value indicating success/failure
2030 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2031 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2033 # Low-level sanity check
2034 if ( $this->mTitle
->getText() === '' ) {
2035 throw new MWException( 'Something is trying to edit an article with an empty title' );
2038 wfProfileIn( __METHOD__
);
2040 $user = is_null( $user ) ?
$wgUser : $user;
2041 $status = Status
::newGood( array() );
2043 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2044 $this->loadPageData();
2046 $flags = $this->checkFlags( $flags );
2048 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2049 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2051 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2053 if ( $status->isOK() ) {
2054 $status->fatal( 'edit-hook-aborted' );
2057 wfProfileOut( __METHOD__
);
2061 # Silently ignore EDIT_MINOR if not allowed
2062 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2063 $bot = $flags & EDIT_FORCE_BOT
;
2065 $oldtext = $this->getRawText(); // current revision
2066 $oldsize = strlen( $oldtext );
2068 # Provide autosummaries if one is not provided and autosummaries are enabled.
2069 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2070 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2073 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2074 $text = $editInfo->pst
;
2075 $newsize = strlen( $text );
2077 $dbw = wfGetDB( DB_MASTER
);
2078 $now = wfTimestampNow();
2079 $this->mTimestamp
= $now;
2081 if ( $flags & EDIT_UPDATE
) {
2082 # Update article, but only if changed.
2083 $status->value
['new'] = false;
2085 # Make sure the revision is either completely inserted or not inserted at all
2086 if ( !$wgDBtransactions ) {
2087 $userAbort = ignore_user_abort( true );
2090 $changed = ( strcmp( $text, $oldtext ) != 0 );
2093 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
2094 - (int)$this->isCountable( $oldtext );
2095 $this->mTotalAdjustment
= 0;
2097 if ( !$this->mLatest
) {
2098 # Article gone missing
2099 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2100 $status->fatal( 'edit-gone-missing' );
2102 wfProfileOut( __METHOD__
);
2106 $revision = new Revision( array(
2107 'page' => $this->getId(),
2108 'comment' => $summary,
2109 'minor_edit' => $isminor,
2111 'parent_id' => $this->mLatest
,
2112 'user' => $user->getId(),
2113 'user_text' => $user->getName(),
2118 $revisionId = $revision->insertOn( $dbw );
2122 # Note that we use $this->mLatest instead of fetching a value from the master DB
2123 # during the course of this function. This makes sure that EditPage can detect
2124 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2125 # before this function is called. A previous function used a separate query, this
2126 # creates a window where concurrent edits can cause an ignored edit conflict.
2127 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2130 /* Belated edit conflict! Run away!! */
2131 $status->fatal( 'edit-conflict' );
2133 # Delete the invalid revision if the DB is not transactional
2134 if ( !$wgDBtransactions ) {
2135 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2141 global $wgUseRCPatrol;
2142 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2143 # Update recentchanges
2144 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2145 # Mark as patrolled if the user can do so
2146 $patrolled = $wgUseRCPatrol && !count(
2147 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2148 # Add RC row to the DB
2149 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2150 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2151 $revisionId, $patrolled
2154 # Log auto-patrolled edits
2156 PatrolLog
::record( $rc, true );
2159 $user->incEditCount();
2163 $status->warning( 'edit-no-change' );
2165 // Keep the same revision ID, but do some updates on it
2166 $revisionId = $this->getLatest();
2167 // Update page_touched, this is usually implicit in the page update
2168 // Other cache updates are done in onArticleEdit()
2169 $this->mTitle
->invalidateCache();
2172 if ( !$wgDBtransactions ) {
2173 ignore_user_abort( $userAbort );
2176 // Now that ignore_user_abort is restored, we can respond to fatal errors
2177 if ( !$status->isOK() ) {
2178 wfProfileOut( __METHOD__
);
2182 # Invalidate cache of this article and all pages using this article
2183 # as a template. Partly deferred.
2184 Article
::onArticleEdit( $this->mTitle
);
2185 # Update links tables, site stats, etc.
2186 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2188 # Create new article
2189 $status->value
['new'] = true;
2191 # Set statistics members
2192 # We work out if it's countable after PST to avoid counter drift
2193 # when articles are created with {{subst:}}
2194 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2195 $this->mTotalAdjustment
= 1;
2199 # Add the page record; stake our claim on this title!
2200 # This will return false if the article already exists
2201 $newid = $this->insertOn( $dbw );
2203 if ( $newid === false ) {
2205 $status->fatal( 'edit-already-exists' );
2207 wfProfileOut( __METHOD__
);
2211 # Save the revision text...
2212 $revision = new Revision( array(
2214 'comment' => $summary,
2215 'minor_edit' => $isminor,
2217 'user' => $user->getId(),
2218 'user_text' => $user->getName(),
2221 $revisionId = $revision->insertOn( $dbw );
2223 $this->mTitle
->resetArticleID( $newid );
2224 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached (FIXME?)
2225 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2227 # Update the page record with revision data
2228 $this->updateRevisionOn( $dbw, $revision, 0 );
2230 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2232 # Update recentchanges
2233 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2234 global $wgUseRCPatrol, $wgUseNPPatrol;
2236 # Mark as patrolled if the user can do so
2237 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2238 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2239 # Add RC row to the DB
2240 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2241 '', strlen( $text ), $revisionId, $patrolled );
2243 # Log auto-patrolled edits
2245 PatrolLog
::record( $rc, true );
2248 $user->incEditCount();
2251 # Update links, etc.
2252 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user );
2255 Article
::onArticleCreate( $this->mTitle
);
2257 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2258 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2261 # Do updates right now unless deferral was requested
2262 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2266 // Return the new revision (or null) to the caller
2267 $status->value
['revision'] = $revision;
2269 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2270 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2272 wfProfileOut( __METHOD__
);
2277 * Output a redirect back to the article.
2278 * This is typically used after an edit.
2280 * @param $noRedir Boolean: add redirect=no
2281 * @param $sectionAnchor String: section to redirect to, including "#"
2282 * @param $extraQuery String: extra query params
2284 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2288 $query = 'redirect=no';
2290 $query .= "&$extraQuery";
2292 $query = $extraQuery;
2295 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2299 * Mark this particular edit/page as patrolled
2301 public function markpatrolled() {
2302 global $wgOut, $wgRequest;
2304 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2306 # If we haven't been given an rc_id value, we can't do anything
2307 $rcid = (int) $wgRequest->getVal( 'rcid' );
2309 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2310 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2314 $rc = RecentChange
::newFromId( $rcid );
2316 if ( is_null( $rc ) ) {
2317 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2321 # It would be nice to see where the user had actually come from, but for now just guess
2322 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2323 $return = SpecialPage
::getTitleFor( $returnto );
2325 $errors = $rc->doMarkPatrolled();
2327 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2328 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2333 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2334 // The hook itself has handled any output
2338 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2339 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2340 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2341 $wgOut->returnToMain( null, $return );
2346 if ( !empty( $errors ) ) {
2347 $wgOut->showPermissionsErrorPage( $errors );
2353 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2354 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2355 $wgOut->returnToMain( null, $return );
2359 * User-interface handler for the "watch" action
2360 * @deprecated since 1.18
2362 public function watch() {
2363 Action
::factory( 'watch', $this )->show();
2367 * Add this page to $wgUser's watchlist
2369 * This is safe to be called multiple times
2371 * @return bool true on successful watch operation
2372 * @deprecated since 1.18
2374 public function doWatch() {
2375 return Action
::factory( 'watch', $this )->execute();
2379 * User interface handler for the "unwatch" action.
2380 * @deprecated since 1.18
2382 public function unwatch() {
2383 Action
::factory( 'unwatch', $this )->show();
2387 * Stop watching a page
2388 * @return bool true on successful unwatch
2389 * @deprecated since 1.18
2391 public function doUnwatch() {
2392 return Action
::factory( 'unwatch', $this )->execute();
2396 * action=protect handler
2398 public function protect() {
2399 $form = new ProtectionForm( $this );
2404 * action=unprotect handler (alias)
2406 public function unprotect() {
2411 * Update the article's restriction field, and leave a log entry.
2413 * @param $limit Array: set of restriction keys
2414 * @param $reason String
2415 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2416 * @param $expiry Array: per restriction type expiration
2417 * @return bool true on success
2419 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2420 global $wgUser, $wgContLang;
2422 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2424 $id = $this->mTitle
->getArticleID();
2427 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2431 if ( wfReadOnly() ) {
2432 wfDebug( "updateRestrictions failed: read-only\n" );
2436 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2437 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2445 // Take this opportunity to purge out expired restrictions
2446 Title
::purgeExpiredRestrictions();
2448 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2449 # we expect a single selection, but the schema allows otherwise.
2451 $updated = Article
::flattenRestrictions( $limit );
2454 foreach ( $restrictionTypes as $action ) {
2455 if ( isset( $expiry[$action] ) ) {
2456 # Get current restrictions on $action
2457 $aLimits = $this->mTitle
->getRestrictions( $action );
2458 $current[$action] = implode( '', $aLimits );
2459 # Are any actual restrictions being dealt with here?
2460 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2462 # If something changed, we need to log it. Checking $aRChanged
2463 # assures that "unprotecting" a page that is not protected does
2464 # not log just because the expiry was "changed".
2465 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2471 $current = Article
::flattenRestrictions( $current );
2473 $changed = ( $changed ||
$current != $updated );
2474 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2475 $protect = ( $updated != '' );
2477 # If nothing's changed, do nothing
2479 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2480 $dbw = wfGetDB( DB_MASTER
);
2482 # Prepare a null revision to be added to the history
2483 $modified = $current != '' && $protect;
2486 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2488 $comment_type = 'unprotectedarticle';
2491 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2493 # Only restrictions with the 'protect' right can cascade...
2494 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2495 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2497 # The schema allows multiple restrictions
2498 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2502 $cascade_description = '';
2505 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2509 $comment .= ": $reason";
2512 $editComment = $comment;
2513 $encodedExpiry = array();
2514 $protect_description = '';
2515 foreach ( $limit as $action => $restrictions ) {
2516 if ( !isset( $expiry[$action] ) )
2517 $expiry[$action] = $dbw->getInfinity();
2519 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2520 if ( $restrictions != '' ) {
2521 $protect_description .= "[$action=$restrictions] (";
2522 if ( $encodedExpiry[$action] != 'infinity' ) {
2523 $protect_description .= wfMsgForContent( 'protect-expiring',
2524 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2525 $wgContLang->date( $expiry[$action], false, false ) ,
2526 $wgContLang->time( $expiry[$action], false, false ) );
2528 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2531 $protect_description .= ') ';
2534 $protect_description = trim( $protect_description );
2536 if ( $protect_description && $protect ) {
2537 $editComment .= " ($protect_description)";
2541 $editComment .= "$cascade_description";
2544 # Update restrictions table
2545 foreach ( $limit as $action => $restrictions ) {
2546 if ( $restrictions != '' ) {
2547 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2548 array( 'pr_page' => $id,
2549 'pr_type' => $action,
2550 'pr_level' => $restrictions,
2551 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2552 'pr_expiry' => $encodedExpiry[$action]
2557 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2558 'pr_type' => $action ), __METHOD__
);
2562 # Insert a null revision
2563 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2564 $nullRevId = $nullRevision->insertOn( $dbw );
2566 $latest = $this->getLatest();
2567 # Update page record
2568 $dbw->update( 'page',
2570 'page_touched' => $dbw->timestamp(),
2571 'page_restrictions' => '',
2572 'page_latest' => $nullRevId
2573 ), array( /* WHERE */
2575 ), 'Article::protect'
2578 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2579 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2581 # Update the protection log
2582 $log = new LogPage( 'protect' );
2584 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2585 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2587 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2590 } # End "changed" check
2596 * Take an array of page restrictions and flatten it to a string
2597 * suitable for insertion into the page_restrictions field.
2598 * @param $limit Array
2601 protected static function flattenRestrictions( $limit ) {
2602 if ( !is_array( $limit ) ) {
2603 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2609 foreach ( $limit as $action => $restrictions ) {
2610 if ( $restrictions != '' ) {
2611 $bits[] = "$action=$restrictions";
2615 return implode( ':', $bits );
2619 * Auto-generates a deletion reason
2621 * @param &$hasHistory Boolean: whether the page has a history
2622 * @return mixed String containing deletion reason or empty string, or boolean false
2623 * if no revision occurred
2625 public function generateReason( &$hasHistory ) {
2628 $dbw = wfGetDB( DB_MASTER
);
2629 // Get the last revision
2630 $rev = Revision
::newFromTitle( $this->mTitle
);
2632 if ( is_null( $rev ) ) {
2636 // Get the article's contents
2637 $contents = $rev->getText();
2640 // If the page is blank, use the text from the previous revision,
2641 // which can only be blank if there's a move/import/protect dummy revision involved
2642 if ( $contents == '' ) {
2643 $prev = $rev->getPrevious();
2646 $contents = $prev->getText();
2651 // Find out if there was only one contributor
2652 // Only scan the last 20 revisions
2653 $res = $dbw->select( 'revision', 'rev_user_text',
2654 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2656 array( 'LIMIT' => 20 )
2659 if ( $res === false ) {
2660 // This page has no revisions, which is very weird
2664 $hasHistory = ( $res->numRows() > 1 );
2665 $row = $dbw->fetchObject( $res );
2667 if ( $row ) { // $row is false if the only contributor is hidden
2668 $onlyAuthor = $row->rev_user_text
;
2669 // Try to find a second contributor
2670 foreach ( $res as $row ) {
2671 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2672 $onlyAuthor = false;
2677 $onlyAuthor = false;
2680 // Generate the summary with a '$1' placeholder
2682 // The current revision is blank and the one before is also
2683 // blank. It's just not our lucky day
2684 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2686 if ( $onlyAuthor ) {
2687 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2689 $reason = wfMsgForContent( 'excontent', '$1' );
2693 if ( $reason == '-' ) {
2694 // Allow these UI messages to be blanked out cleanly
2698 // Replace newlines with spaces to prevent uglyness
2699 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2700 // Calculate the maximum amount of chars to get
2701 // Max content length = max comment length - length of the comment (excl. $1)
2702 $maxLength = 255 - ( strlen( $reason ) - 2 );
2703 $contents = $wgContLang->truncate( $contents, $maxLength );
2704 // Remove possible unfinished links
2705 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2706 // Now replace the '$1' placeholder
2707 $reason = str_replace( '$1', $contents, $reason );
2714 * UI entry point for page deletion
2716 public function delete() {
2717 global $wgOut, $wgRequest;
2719 $confirm = $wgRequest->wasPosted() &&
2720 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2722 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2723 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2725 $reason = $this->DeleteReasonList
;
2727 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2728 // Entry from drop down menu + additional comment
2729 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2730 } elseif ( $reason == 'other' ) {
2731 $reason = $this->DeleteReason
;
2734 # Flag to hide all contents of the archived revisions
2735 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2737 # This code desperately needs to be totally rewritten
2739 # Read-only check...
2740 if ( wfReadOnly() ) {
2741 $wgOut->readOnlyPage();
2747 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2749 if ( count( $permission_errors ) > 0 ) {
2750 $wgOut->showPermissionsErrorPage( $permission_errors );
2755 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2757 # Better double-check that it hasn't been deleted yet!
2758 $dbw = wfGetDB( DB_MASTER
);
2759 $conds = $this->mTitle
->pageCond();
2760 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2761 if ( $latest === false ) {
2762 $wgOut->showFatalError(
2765 array( 'class' => 'error mw-error-cannotdelete' ),
2766 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2769 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2770 LogEventsList
::showLogExtract(
2773 $this->mTitle
->getPrefixedText()
2779 # Hack for big sites
2780 $bigHistory = $this->isBigDeletion();
2781 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2782 global $wgLang, $wgDeleteRevisionsLimit;
2784 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2785 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2791 $this->doDelete( $reason, $suppress );
2793 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2795 } elseif ( $this->mTitle
->userIsWatching() ) {
2802 // Generate deletion reason
2803 $hasHistory = false;
2805 $reason = $this->generateReason( $hasHistory );
2808 // If the page has a history, insert a warning
2809 if ( $hasHistory && !$confirm ) {
2812 $revisions = $this->estimateRevisionCount();
2814 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2815 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2816 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->mTitle
,
2817 wfMsgHtml( 'history' ),
2818 array( 'rel' => 'archives' ),
2819 array( 'action' => 'history' ) ) .
2823 if ( $bigHistory ) {
2824 global $wgDeleteRevisionsLimit;
2825 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2826 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2830 return $this->confirmDelete( $reason );
2834 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2836 public function isBigDeletion() {
2837 global $wgDeleteRevisionsLimit;
2839 if ( $wgDeleteRevisionsLimit ) {
2840 $revCount = $this->estimateRevisionCount();
2842 return $revCount > $wgDeleteRevisionsLimit;
2849 * @return int approximate revision count
2851 public function estimateRevisionCount() {
2852 $dbr = wfGetDB( DB_SLAVE
);
2854 // For an exact count...
2855 // return $dbr->selectField( 'revision', 'COUNT(*)',
2856 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2857 return $dbr->estimateRowCount( 'revision', '*',
2858 array( 'rev_page' => $this->getId() ), __METHOD__
);
2862 * Get the last N authors
2863 * @param $num Integer: number of revisions to get
2864 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2865 * @return array Array of authors, duplicates not removed
2867 public function getLastNAuthors( $num, $revLatest = 0 ) {
2868 wfProfileIn( __METHOD__
);
2869 // First try the slave
2870 // If that doesn't have the latest revision, try the master
2872 $db = wfGetDB( DB_SLAVE
);
2875 $res = $db->select( array( 'page', 'revision' ),
2876 array( 'rev_id', 'rev_user_text' ),
2878 'page_namespace' => $this->mTitle
->getNamespace(),
2879 'page_title' => $this->mTitle
->getDBkey(),
2880 'rev_page = page_id'
2883 'ORDER BY' => 'rev_timestamp DESC',
2889 wfProfileOut( __METHOD__
);
2893 $row = $db->fetchObject( $res );
2895 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2896 $db = wfGetDB( DB_MASTER
);
2901 } while ( $continue );
2903 $authors = array( $row->rev_user_text
);
2905 foreach ( $res as $row ) {
2906 $authors[] = $row->rev_user_text
;
2909 wfProfileOut( __METHOD__
);
2914 * Output deletion confirmation dialog
2915 * FIXME: Move to another file?
2916 * @param $reason String: prefilled reason
2918 public function confirmDelete( $reason ) {
2921 wfDebug( "Article::confirmDelete\n" );
2923 $deleteBackLink = Linker
::linkKnown( $this->mTitle
);
2924 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2925 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2926 $wgOut->addWikiMsg( 'confirmdeletetext' );
2928 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2930 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2931 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2933 <td class='mw-input'><strong>" .
2934 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2935 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2941 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2943 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2944 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2945 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2946 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2947 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2948 "<tr id=\"wpDeleteReasonListRow\">
2949 <td class='mw-label'>" .
2950 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2952 <td class='mw-input'>" .
2953 Xml
::listDropDown( 'wpDeleteReasonList',
2954 wfMsgForContent( 'deletereason-dropdown' ),
2955 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2958 <tr id=\"wpDeleteReasonRow\">
2959 <td class='mw-label'>" .
2960 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2962 <td class='mw-input'>" .
2963 Html
::input( 'wpReason', $reason, 'text', array(
2965 'maxlength' => '255',
2973 # Disallow watching if user is not logged in
2974 if ( $wgOut->getUser()->isLoggedIn() ) {
2978 <td class='mw-input'>" .
2979 Xml
::checkLabel( wfMsg( 'watchthis' ),
2980 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2989 <td class='mw-submit'>" .
2990 Xml
::submitButton( wfMsg( 'deletepage' ),
2991 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2994 Xml
::closeElement( 'table' ) .
2995 Xml
::closeElement( 'fieldset' ) .
2996 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2997 Xml
::closeElement( 'form' );
2999 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
3000 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
3001 $link = Linker
::link(
3003 wfMsgHtml( 'delete-edit-reasonlist' ),
3005 array( 'action' => 'edit' )
3007 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3010 $wgOut->addHTML( $form );
3011 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3012 LogEventsList
::showLogExtract( $wgOut, 'delete',
3013 $this->mTitle
->getPrefixedText()
3018 * Perform a deletion and output success or failure messages
3020 public function doDelete( $reason, $suppress = false ) {
3023 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3026 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
3027 $deleted = $this->mTitle
->getPrefixedText();
3029 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3030 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3032 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3034 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3035 $wgOut->returnToMain( false );
3037 if ( $error == '' ) {
3038 $wgOut->showFatalError(
3041 array( 'class' => 'error mw-error-cannotdelete' ),
3042 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3046 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3048 LogEventsList
::showLogExtract(
3051 $this->mTitle
->getPrefixedText()
3054 $wgOut->showFatalError( $error );
3060 * Back-end article deletion
3061 * Deletes the article with database consistency, writes logs, purges caches
3063 * @param $reason string delete reason for deletion log
3064 * @param suppress bitfield
3065 * Revision::DELETED_TEXT
3066 * Revision::DELETED_COMMENT
3067 * Revision::DELETED_USER
3068 * Revision::DELETED_RESTRICTED
3069 * @param $id int article ID
3070 * @param $commit boolean defaults to true, triggers transaction end
3071 * @return boolean true if successful
3073 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3074 global $wgDeferredUpdateList, $wgUseTrackbacks;
3077 wfDebug( __METHOD__
. "\n" );
3079 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3082 $dbw = wfGetDB( DB_MASTER
);
3083 $t = $this->mTitle
->getDBkey();
3084 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3086 if ( $t === '' ||
$id == 0 ) {
3090 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3091 array_push( $wgDeferredUpdateList, $u );
3093 // Bitfields to further suppress the content
3096 // This should be 15...
3097 $bitfield |
= Revision
::DELETED_TEXT
;
3098 $bitfield |
= Revision
::DELETED_COMMENT
;
3099 $bitfield |
= Revision
::DELETED_USER
;
3100 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3102 $bitfield = 'rev_deleted';
3106 // For now, shunt the revision data into the archive table.
3107 // Text is *not* removed from the text table; bulk storage
3108 // is left intact to avoid breaking block-compression or
3109 // immutable storage schemes.
3111 // For backwards compatibility, note that some older archive
3112 // table entries will have ar_text and ar_flags fields still.
3114 // In the future, we may keep revisions and mark them with
3115 // the rev_deleted field, which is reserved for this purpose.
3116 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3118 'ar_namespace' => 'page_namespace',
3119 'ar_title' => 'page_title',
3120 'ar_comment' => 'rev_comment',
3121 'ar_user' => 'rev_user',
3122 'ar_user_text' => 'rev_user_text',
3123 'ar_timestamp' => 'rev_timestamp',
3124 'ar_minor_edit' => 'rev_minor_edit',
3125 'ar_rev_id' => 'rev_id',
3126 'ar_text_id' => 'rev_text_id',
3127 'ar_text' => '\'\'', // Be explicit to appease
3128 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3129 'ar_len' => 'rev_len',
3130 'ar_page_id' => 'page_id',
3131 'ar_deleted' => $bitfield
3134 'page_id = rev_page'
3138 # Delete restrictions for it
3139 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3141 # Now that it's safely backed up, delete it
3142 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3143 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3150 # Fix category table counts
3152 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3154 foreach ( $res as $row ) {
3155 $cats [] = $row->cl_to
;
3158 $this->updateCategoryCounts( array(), $cats );
3160 # If using cascading deletes, we can skip some explicit deletes
3161 if ( !$dbw->cascadingDeletes() ) {
3162 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3164 if ( $wgUseTrackbacks )
3165 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3167 # Delete outgoing links
3168 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3169 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3170 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3171 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3172 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3173 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3174 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3175 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3178 # If using cleanup triggers, we can skip some manual deletes
3179 if ( !$dbw->cleanupTriggers() ) {
3180 # Clean up recentchanges entries...
3181 $dbw->delete( 'recentchanges',
3182 array( 'rc_type != ' . RC_LOG
,
3183 'rc_namespace' => $this->mTitle
->getNamespace(),
3184 'rc_title' => $this->mTitle
->getDBkey() ),
3186 $dbw->delete( 'recentchanges',
3187 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3192 Article
::onArticleDelete( $this->mTitle
);
3194 # Clear the cached article id so the interface doesn't act like we exist
3195 $this->mTitle
->resetArticleID( 0 );
3197 # Log the deletion, if the page was suppressed, log it at Oversight instead
3198 $logtype = $suppress ?
'suppress' : 'delete';
3199 $log = new LogPage( $logtype );
3201 # Make sure logging got through
3202 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3208 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3213 * Roll back the most recent consecutive set of edits to a page
3214 * from the same user; fails if there are no eligible edits to
3215 * roll back to, e.g. user is the sole contributor. This function
3216 * performs permissions checks on $wgUser, then calls commitRollback()
3217 * to do the dirty work
3219 * @param $fromP String: Name of the user whose edits to rollback.
3220 * @param $summary String: Custom summary. Set to default summary if empty.
3221 * @param $token String: Rollback token.
3222 * @param $bot Boolean: If true, mark all reverted edits as bot.
3224 * @param $resultDetails Array: contains result-specific array of additional values
3225 * 'alreadyrolled' : 'current' (rev)
3226 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3228 * @return array of errors, each error formatted as
3229 * array(messagekey, param1, param2, ...).
3230 * On success, the array is empty. This array can also be passed to
3231 * OutputPage::showPermissionsErrorPage().
3233 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3236 $resultDetails = null;
3239 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3240 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3241 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3243 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3244 $errors[] = array( 'sessionfailure' );
3247 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3248 $errors[] = array( 'actionthrottledtext' );
3251 # If there were errors, bail out now
3252 if ( !empty( $errors ) ) {
3256 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3260 * Backend implementation of doRollback(), please refer there for parameter
3261 * and return value documentation
3263 * NOTE: This function does NOT check ANY permissions, it just commits the
3264 * rollback to the DB Therefore, you should only call this function direct-
3265 * ly if you want to use custom permissions checks. If you don't, use
3266 * doRollback() instead.
3268 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3269 global $wgUseRCPatrol, $wgUser, $wgLang;
3271 $dbw = wfGetDB( DB_MASTER
);
3273 if ( wfReadOnly() ) {
3274 return array( array( 'readonlytext' ) );
3277 # Get the last editor
3278 $current = Revision
::newFromTitle( $this->mTitle
);
3279 if ( is_null( $current ) ) {
3280 # Something wrong... no page?
3281 return array( array( 'notanarticle' ) );
3284 $from = str_replace( '_', ' ', $fromP );
3285 # User name given should match up with the top revision.
3286 # If the user was deleted then $from should be empty.
3287 if ( $from != $current->getUserText() ) {
3288 $resultDetails = array( 'current' => $current );
3289 return array( array( 'alreadyrolled',
3290 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3291 htmlspecialchars( $fromP ),
3292 htmlspecialchars( $current->getUserText() )
3296 # Get the last edit not by this guy...
3297 # Note: these may not be public values
3298 $user = intval( $current->getRawUser() );
3299 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3300 $s = $dbw->selectRow( 'revision',
3301 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3302 array( 'rev_page' => $current->getPage(),
3303 "rev_user != {$user} OR rev_user_text != {$user_text}"
3305 array( 'USE INDEX' => 'page_timestamp',
3306 'ORDER BY' => 'rev_timestamp DESC' )
3308 if ( $s === false ) {
3309 # No one else ever edited this page
3310 return array( array( 'cantrollback' ) );
3311 } else if ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3312 # Only admins can see this text
3313 return array( array( 'notvisiblerev' ) );
3317 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3318 # Mark all reverted edits as bot
3322 if ( $wgUseRCPatrol ) {
3323 # Mark all reverted edits as patrolled
3324 $set['rc_patrolled'] = 1;
3327 if ( count( $set ) ) {
3328 $dbw->update( 'recentchanges', $set,
3330 'rc_cur_id' => $current->getPage(),
3331 'rc_user_text' => $current->getUserText(),
3332 "rc_timestamp > '{$s->rev_timestamp}'",
3337 # Generate the edit summary if necessary
3338 $target = Revision
::newFromId( $s->rev_id
);
3339 if ( empty( $summary ) ) {
3340 if ( $from == '' ) { // no public user name
3341 $summary = wfMsgForContent( 'revertpage-nouser' );
3343 $summary = wfMsgForContent( 'revertpage' );
3347 # Allow the custom summary to use the same args as the default message
3349 $target->getUserText(), $from, $s->rev_id
,
3350 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3351 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3353 $summary = wfMsgReplaceArgs( $summary, $args );
3356 $flags = EDIT_UPDATE
;
3358 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3359 $flags |
= EDIT_MINOR
;
3362 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3363 $flags |
= EDIT_FORCE_BOT
;
3366 # Actually store the edit
3367 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3368 if ( !empty( $status->value
['revision'] ) ) {
3369 $revId = $status->value
['revision']->getId();
3374 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3376 $resultDetails = array(
3377 'summary' => $summary,
3378 'current' => $current,
3379 'target' => $target,
3387 * User interface for rollback operations
3389 public function rollback() {
3390 global $wgUser, $wgOut, $wgRequest;
3394 $result = $this->doRollback(
3395 $wgRequest->getVal( 'from' ),
3396 $wgRequest->getText( 'summary' ),
3397 $wgRequest->getVal( 'token' ),
3398 $wgRequest->getBool( 'bot' ),
3402 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3403 $wgOut->rateLimited();
3407 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3408 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3409 $errArray = $result[0];
3410 $errMsg = array_shift( $errArray );
3411 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3413 if ( isset( $details['current'] ) ) {
3414 $current = $details['current'];
3416 if ( $current->getComment() != '' ) {
3417 $wgOut->addWikiMsgArray( 'editcomment', array(
3418 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3425 # Display permissions errors before read-only message -- there's no
3426 # point in misleading the user into thinking the inability to rollback
3427 # is only temporary.
3428 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3429 # array_diff is completely broken for arrays of arrays, sigh.
3430 # Remove any 'readonlytext' error manually.
3432 foreach ( $result as $error ) {
3433 if ( $error != array( 'readonlytext' ) ) {
3437 $wgOut->showPermissionsErrorPage( $out );
3442 if ( $result == array( array( 'readonlytext' ) ) ) {
3443 $wgOut->readOnlyPage();
3448 $current = $details['current'];
3449 $target = $details['target'];
3450 $newId = $details['newid'];
3451 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3452 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3454 if ( $current->getUserText() === '' ) {
3455 $old = wfMsg( 'rev-deleted-user' );
3457 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
3458 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
3461 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
3462 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
3463 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3464 $wgOut->returnToMain( false, $this->mTitle
);
3466 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3467 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3468 $de->showDiff( '', '' );
3473 * Do standard deferred updates after page view
3475 public function viewUpdates() {
3476 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3477 if ( wfReadOnly() ) {
3481 # Don't update page view counters on views from bot users (bug 14044)
3482 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3483 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3484 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3487 # Update newtalk / watchlist notification status
3488 $wgUser->clearNotification( $this->mTitle
);
3492 * Prepare text which is about to be saved.
3493 * Returns a stdclass with source, pst and output members
3495 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3496 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3498 return $this->mPreparedEdit
;
3503 if( $user === null ) {
3507 $popts = ParserOptions
::newFromUser( $user );
3508 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3510 $edit = (object)array();
3511 $edit->revid
= $revid;
3512 $edit->newText
= $text;
3513 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3514 $edit->popts
= $this->getParserOptions();
3515 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3516 $edit->oldText
= $this->getRawText();
3518 $this->mPreparedEdit
= $edit;
3524 * Do standard deferred updates after page edit.
3525 * Update links tables, site stats, search index and message cache.
3526 * Purges pages that include this page if the text was changed here.
3527 * Every 100th edit, prune the recent changes table.
3530 * @param $text String: New text of the article
3531 * @param $summary String: Edit summary
3532 * @param $minoredit Boolean: Minor edit
3533 * @param $timestamp_of_pagechange String timestamp associated with the page change
3534 * @param $newid Integer: rev_id value of the new revision
3535 * @param $changed Boolean: Whether or not the content actually changed
3536 * @param $user User object: User doing the edit
3538 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User
$user = null ) {
3539 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3541 wfProfileIn( __METHOD__
);
3544 # Be careful not to double-PST: $text is usually already PST-ed once
3545 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3546 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3547 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3549 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3550 $editInfo = $this->mPreparedEdit
;
3553 # Save it to the parser cache
3554 if ( $wgEnableParserCache ) {
3555 $parserCache = ParserCache
::singleton();
3556 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3559 # Update the links tables
3560 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3563 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3565 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3566 if ( 0 == mt_rand( 0, 99 ) ) {
3567 // Flush old entries from the `recentchanges` table; we do this on
3568 // random requests so as to avoid an increase in writes for no good reason
3571 $dbw = wfGetDB( DB_MASTER
);
3572 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3575 array( "rc_timestamp < '$cutoff'" ),
3581 $id = $this->getID();
3582 $title = $this->mTitle
->getPrefixedDBkey();
3583 $shortTitle = $this->mTitle
->getDBkey();
3586 wfProfileOut( __METHOD__
);
3590 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3591 array_push( $wgDeferredUpdateList, $u );
3592 $u = new SearchUpdate( $id, $title, $text );
3593 array_push( $wgDeferredUpdateList, $u );
3595 # If this is another user's talk page, update newtalk
3596 # Don't do this if $changed = false otherwise some idiot can null-edit a
3597 # load of user talk pages and piss people off, nor if it's a minor edit
3598 # by a properly-flagged bot.
3599 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3600 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3602 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3603 $other = User
::newFromName( $shortTitle, false );
3605 wfDebug( __METHOD__
. ": invalid username\n" );
3606 } elseif ( User
::isIP( $shortTitle ) ) {
3607 // An anonymous user
3608 $other->setNewtalk( true );
3609 } elseif ( $other->isLoggedIn() ) {
3610 $other->setNewtalk( true );
3612 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3617 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3618 MessageCache
::singleton()->replace( $shortTitle, $text );
3621 wfProfileOut( __METHOD__
);
3625 * Perform article updates on a special page creation.
3627 * @param $rev Revision object
3629 * @todo This is a shitty interface function. Kill it and replace the
3630 * other shitty functions like editUpdates and such so it's not needed
3633 public function createUpdates( $rev ) {
3634 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3635 $this->mTotalAdjustment
= 1;
3636 $this->editUpdates( $rev->getText(), $rev->getComment(),
3637 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3641 * Generate the navigation links when browsing through an article revisions
3642 * It shows the information as:
3643 * Revision as of \<date\>; view current revision
3644 * \<- Previous version | Next Version -\>
3646 * @param $oldid String: revision ID of this article revision
3648 public function setOldSubtitle( $oldid = 0 ) {
3649 global $wgLang, $wgOut, $wgUser, $wgRequest;
3651 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3655 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3657 # Cascade unhide param in links for easy deletion browsing
3658 $extraParams = array();
3659 if ( $wgRequest->getVal( 'unhide' ) ) {
3660 $extraParams['unhide'] = 1;
3663 $revision = Revision
::newFromId( $oldid );
3664 $timestamp = $revision->getTimestamp();
3666 $current = ( $oldid == $this->mLatest
);
3667 $td = $wgLang->timeanddate( $timestamp, true );
3668 $tddate = $wgLang->date( $timestamp, true );
3669 $tdtime = $wgLang->time( $timestamp, true );
3672 ?
wfMsgHtml( 'currentrevisionlink' )
3675 wfMsgHtml( 'currentrevisionlink' ),
3678 array( 'known', 'noclasses' )
3681 ?
wfMsgHtml( 'diff' )
3684 wfMsgHtml( 'diff' ),
3690 array( 'known', 'noclasses' )
3692 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3696 wfMsgHtml( 'previousrevision' ),
3699 'direction' => 'prev',
3702 array( 'known', 'noclasses' )
3704 : wfMsgHtml( 'previousrevision' );
3708 wfMsgHtml( 'diff' ),
3714 array( 'known', 'noclasses' )
3716 : wfMsgHtml( 'diff' );
3717 $nextlink = $current
3718 ?
wfMsgHtml( 'nextrevision' )
3721 wfMsgHtml( 'nextrevision' ),
3724 'direction' => 'next',
3727 array( 'known', 'noclasses' )
3729 $nextdiff = $current
3730 ?
wfMsgHtml( 'diff' )
3733 wfMsgHtml( 'diff' ),
3739 array( 'known', 'noclasses' )
3744 // User can delete revisions or view deleted revisions...
3745 $canHide = $wgUser->isAllowed( 'deleterevision' );
3746 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3747 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3748 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3751 'type' => 'revision',
3752 'target' => $this->mTitle
->getPrefixedDbkey(),
3755 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3760 # Show user links if allowed to see them. If hidden, then show them only if requested...
3761 $userlinks = Linker
::revUserTools( $revision, !$unhide );
3763 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3764 ?
'revision-info-current'
3767 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3770 array( 'parseinline', 'replaceafter' ),
3776 $revision->getUser()
3779 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3780 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3782 $wgOut->addHTML( $r );
3786 * This function is called right before saving the wikitext,
3787 * so we can do things like signatures and links-in-context.
3789 * @param $text String article contents
3790 * @param $user User object: user doing the edit, $wgUser will be used if
3792 * @param $popts ParserOptions object: parser options, default options for
3793 * the user loaded if null given
3794 * @return string article contents with altered wikitext markup (signatures
3795 * converted, {{subst:}}, templates, etc.)
3797 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3800 if ( $user === null ) {
3805 if ( $popts === null ) {
3806 $popts = ParserOptions
::newFromUser( $user );
3809 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3812 /* Caching functions */
3815 * checkLastModified returns true if it has taken care of all
3816 * output to the client that is necessary for this request.
3817 * (that is, it has sent a cached version of the page)
3819 * @return boolean true if cached version send, false otherwise
3821 protected function tryFileCache() {
3822 static $called = false;
3825 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3830 if ( $this->isFileCacheable() ) {
3831 $cache = new HTMLFileCache( $this->mTitle
);
3832 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3833 wfDebug( "Article::tryFileCache(): about to load file\n" );
3834 $cache->loadFromFileCache();
3837 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3838 ob_start( array( &$cache, 'saveToFileCache' ) );
3841 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3848 * Check if the page can be cached
3851 public function isFileCacheable() {
3854 if ( HTMLFileCache
::useFileCache() ) {
3855 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3856 // Extension may have reason to disable file caching on some pages.
3858 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3866 * Loads page_touched and returns a value indicating if it should be used
3867 * @return boolean true if not a redirect
3869 public function checkTouched() {
3870 if ( !$this->mDataLoaded
) {
3871 $this->loadPageData();
3874 return !$this->mIsRedirect
;
3878 * Get the page_touched field
3879 * @return string containing GMT timestamp
3881 public function getTouched() {
3882 if ( !$this->mDataLoaded
) {
3883 $this->loadPageData();
3886 return $this->mTouched
;
3890 * Get the page_latest field
3891 * @return integer rev_id of current revision
3893 public function getLatest() {
3894 if ( !$this->mDataLoaded
) {
3895 $this->loadPageData();
3898 return (int)$this->mLatest
;
3902 * Edit an article without doing all that other stuff
3903 * The article must already exist; link tables etc
3904 * are not updated, caches are not flushed.
3906 * @param $text String: text submitted
3907 * @param $comment String: comment submitted
3908 * @param $minor Boolean: whereas it's a minor modification
3910 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3911 wfProfileIn( __METHOD__
);
3913 $dbw = wfGetDB( DB_MASTER
);
3914 $revision = new Revision( array(
3915 'page' => $this->getId(),
3917 'comment' => $comment,
3918 'minor_edit' => $minor ?
1 : 0,
3920 $revision->insertOn( $dbw );
3921 $this->updateRevisionOn( $dbw, $revision );
3924 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3926 wfProfileOut( __METHOD__
);
3930 * The onArticle*() functions are supposed to be a kind of hooks
3931 * which should be called whenever any of the specified actions
3934 * This is a good place to put code to clear caches, for instance.
3936 * This is called on page move and undelete, as well as edit
3938 * @param $title Title object
3940 public static function onArticleCreate( $title ) {
3941 # Update existence markers on article/talk tabs...
3942 if ( $title->isTalkPage() ) {
3943 $other = $title->getSubjectPage();
3945 $other = $title->getTalkPage();
3948 $other->invalidateCache();
3949 $other->purgeSquid();
3951 $title->touchLinks();
3952 $title->purgeSquid();
3953 $title->deleteTitleProtection();
3957 * Clears caches when article is deleted
3959 * @param $title Title
3961 public static function onArticleDelete( $title ) {
3962 # Update existence markers on article/talk tabs...
3963 if ( $title->isTalkPage() ) {
3964 $other = $title->getSubjectPage();
3966 $other = $title->getTalkPage();
3969 $other->invalidateCache();
3970 $other->purgeSquid();
3972 $title->touchLinks();
3973 $title->purgeSquid();
3976 HTMLFileCache
::clearFileCache( $title );
3979 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3980 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3984 if ( $title->getNamespace() == NS_FILE
) {
3985 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3986 $update->doUpdate();
3990 if ( $title->getNamespace() == NS_USER_TALK
) {
3991 $user = User
::newFromName( $title->getText(), false );
3992 $user->setNewtalk( false );
3996 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4000 * Purge caches on page update etc
4002 * @param $title Title object
4003 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4005 public static function onArticleEdit( $title ) {
4006 global $wgDeferredUpdateList;
4008 // Invalidate caches of articles which include this page
4009 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4011 // Invalidate the caches of all pages which redirect here
4012 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4014 # Purge squid for this page only
4015 $title->purgeSquid();
4017 # Clear file cache for this page only
4018 HTMLFileCache
::clearFileCache( $title );
4024 * Overriden by ImagePage class, only present here to avoid a fatal error
4025 * Called for ?action=revert
4027 public function revert() {
4029 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4033 * Info about this page
4034 * Called for ?action=info when $wgAllowPageInfo is on.
4036 public function info() {
4037 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4039 if ( !$wgAllowPageInfo ) {
4040 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4044 $page = $this->mTitle
->getSubjectPage();
4046 $wgOut->setPagetitle( $page->getPrefixedText() );
4047 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4048 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4050 if ( !$this->mTitle
->exists() ) {
4051 $wgOut->addHTML( '<div class="noarticletext">' );
4052 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
4053 // This doesn't quite make sense; the user is asking for
4054 // information about the _page_, not the message... -- RC
4055 $wgOut->addHTML( htmlspecialchars( $this->mTitle
->getDefaultMessageText() ) );
4057 $msg = $wgUser->isLoggedIn()
4059 : 'noarticletextanon';
4060 $wgOut->addWikiMsg( $msg );
4063 $wgOut->addHTML( '</div>' );
4065 $dbr = wfGetDB( DB_SLAVE
);
4067 'wl_title' => $page->getDBkey(),
4068 'wl_namespace' => $page->getNamespace() );
4069 $numwatchers = $dbr->selectField(
4075 $pageInfo = $this->pageCountInfo( $page );
4076 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4079 //FIXME: unescaped messages
4080 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4081 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4084 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4087 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4090 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4093 $wgOut->addHTML( '</ul>' );
4098 * Return the total number of edits and number of unique editors
4099 * on a given page. If page does not exist, returns false.
4101 * @param $title Title object
4102 * @return mixed array or boolean false
4104 public function pageCountInfo( $title ) {
4105 $id = $title->getArticleId();
4111 $dbr = wfGetDB( DB_SLAVE
);
4112 $rev_clause = array( 'rev_page' => $id );
4113 $edits = $dbr->selectField(
4119 $authors = $dbr->selectField(
4121 'COUNT(DISTINCT rev_user_text)',
4126 return array( 'edits' => $edits, 'authors' => $authors );
4130 * Return a list of templates used by this article.
4131 * Uses the templatelinks table
4133 * @return Array of Title objects
4135 public function getUsedTemplates() {
4137 $id = $this->mTitle
->getArticleID();
4143 $dbr = wfGetDB( DB_SLAVE
);
4144 $res = $dbr->select( array( 'templatelinks' ),
4145 array( 'tl_namespace', 'tl_title' ),
4146 array( 'tl_from' => $id ),
4149 if ( $res !== false ) {
4150 foreach ( $res as $row ) {
4151 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4159 * Returns a list of hidden categories this page is a member of.
4160 * Uses the page_props and categorylinks tables.
4162 * @return Array of Title objects
4164 public function getHiddenCategories() {
4166 $id = $this->mTitle
->getArticleID();
4172 $dbr = wfGetDB( DB_SLAVE
);
4173 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4175 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4176 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4179 if ( $res !== false ) {
4180 foreach ( $res as $row ) {
4181 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4189 * Return an applicable autosummary if one exists for the given edit.
4190 * @param $oldtext String: the previous text of the page.
4191 * @param $newtext String: The submitted text of the page.
4192 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4193 * @return string An appropriate autosummary, or an empty string.
4195 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4198 # Decide what kind of autosummary is needed.
4200 # Redirect autosummaries
4201 $ot = Title
::newFromRedirect( $oldtext );
4202 $rt = Title
::newFromRedirect( $newtext );
4204 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4205 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4208 # New page autosummaries
4209 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4210 # If they're making a new article, give its text, truncated, in the summary.
4212 $truncatedtext = $wgContLang->truncate(
4213 str_replace( "\n", ' ', $newtext ),
4214 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4216 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4219 # Blanking autosummaries
4220 if ( $oldtext != '' && $newtext == '' ) {
4221 return wfMsgForContent( 'autosumm-blank' );
4222 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4223 # Removing more than 90% of the article
4225 $truncatedtext = $wgContLang->truncate(
4227 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4229 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4232 # If we reach this point, there's no applicable autosummary for our case, so our
4233 # autosummary is empty.
4238 * Add the primary page-view wikitext to the output buffer
4239 * Saves the text into the parser cache if possible.
4240 * Updates templatelinks if it is out of date.
4242 * @param $text String
4243 * @param $cache Boolean
4244 * @param $parserOptions mixed ParserOptions object, or boolean false
4246 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4249 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4250 $wgOut->addParserOutput( $this->mParserOutput
);
4254 * This does all the heavy lifting for outputWikitext, except it returns the parser
4255 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4256 * say, embedding thread pages within a discussion system (LiquidThreads)
4258 * @param $text string
4259 * @param $cache boolean
4260 * @param $parserOptions parsing options, defaults to false
4261 * @return string containing parsed output
4263 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4264 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4266 if ( !$parserOptions ) {
4267 $parserOptions = $this->getParserOptions();
4271 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4272 $parserOptions, true, true, $this->getRevIdFetched() );
4277 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4278 $this->mTitle
->getPrefixedDBkey() ) );
4281 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4282 $parserCache = ParserCache
::singleton();
4283 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4286 // Make sure file cache is not used on uncacheable content.
4287 // Output that has magic words in it can still use the parser cache
4288 // (if enabled), though it will generally expire sooner.
4289 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4290 $wgUseFileCache = false;
4293 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4295 return $this->mParserOutput
;
4299 * Get parser options suitable for rendering the primary article wikitext
4300 * @return ParserOptions object
4302 public function getParserOptions() {
4304 if ( !$this->mParserOptions
) {
4305 $this->mParserOptions
= $this->makeParserOptions( $wgUser );
4307 // Clone to allow modifications of the return value without affecting cache
4308 return clone $this->mParserOptions
;
4312 * Get parser options suitable for rendering the primary article wikitext
4314 * @return ParserOptions
4316 public function makeParserOptions( User
$user ) {
4317 $options = ParserOptions
::newFromUser( $user );
4318 $options->enableLimitReport(); // show inclusion/loop reports
4319 $options->setTidy( true ); // fix bad HTML
4324 * Updates cascading protections
4326 * @param $parserOutput ParserOutput object, or boolean false
4328 protected function doCascadeProtectionUpdates( $parserOutput ) {
4329 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4333 // templatelinks table may have become out of sync,
4334 // especially if using variable-based transclusions.
4335 // For paranoia, check if things have changed and if
4336 // so apply updates to the database. This will ensure
4337 // that cascaded protections apply as soon as the changes
4340 # Get templates from templatelinks
4341 $id = $this->mTitle
->getArticleID();
4343 $tlTemplates = array();
4345 $dbr = wfGetDB( DB_SLAVE
);
4346 $res = $dbr->select( array( 'templatelinks' ),
4347 array( 'tl_namespace', 'tl_title' ),
4348 array( 'tl_from' => $id ),
4352 foreach ( $res as $row ) {
4353 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4356 # Get templates from parser output.
4357 $poTemplates = array();
4358 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4359 foreach ( $templates as $dbk => $id ) {
4360 $poTemplates["$ns:$dbk"] = true;
4365 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4367 if ( count( $templates_diff ) > 0 ) {
4368 # Whee, link updates time.
4369 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4375 * Update all the appropriate counts in the category table, given that
4376 * we've added the categories $added and deleted the categories $deleted.
4378 * @param $added array The names of categories that were added
4379 * @param $deleted array The names of categories that were deleted
4381 public function updateCategoryCounts( $added, $deleted ) {
4382 $ns = $this->mTitle
->getNamespace();
4383 $dbw = wfGetDB( DB_MASTER
);
4385 # First make sure the rows exist. If one of the "deleted" ones didn't
4386 # exist, we might legitimately not create it, but it's simpler to just
4387 # create it and then give it a negative value, since the value is bogus
4390 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4391 $insertCats = array_merge( $added, $deleted );
4392 if ( !$insertCats ) {
4393 # Okay, nothing to do
4397 $insertRows = array();
4399 foreach ( $insertCats as $cat ) {
4400 $insertRows[] = array(
4401 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4405 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4407 $addFields = array( 'cat_pages = cat_pages + 1' );
4408 $removeFields = array( 'cat_pages = cat_pages - 1' );
4410 if ( $ns == NS_CATEGORY
) {
4411 $addFields[] = 'cat_subcats = cat_subcats + 1';
4412 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4413 } elseif ( $ns == NS_FILE
) {
4414 $addFields[] = 'cat_files = cat_files + 1';
4415 $removeFields[] = 'cat_files = cat_files - 1';
4422 array( 'cat_title' => $added ),
4431 array( 'cat_title' => $deleted ),
4438 * Lightweight method to get the parser output for a page, checking the parser cache
4439 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4440 * consider, so it's not appropriate to use there.
4442 * @since 1.16 (r52326) for LiquidThreads
4444 * @param $oldid mixed integer Revision ID or null
4445 * @return ParserOutput or false if the given revsion ID is not found
4447 public function getParserOutput( $oldid = null ) {
4448 global $wgEnableParserCache, $wgUser;
4450 // Should the parser cache be used?
4451 $useParserCache = $wgEnableParserCache &&
4452 $wgUser->getStubThreshold() == 0 &&
4456 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4458 if ( $wgUser->getStubThreshold() ) {
4459 wfIncrStats( 'pcache_miss_stub' );
4462 if ( $useParserCache ) {
4463 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4464 if ( $parserOutput !== false ) {
4465 return $parserOutput;
4469 // Cache miss; parse and output it.
4470 if ( $oldid === null ) {
4471 $text = $this->getRawText();
4473 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4474 if ( $rev === null ) {
4477 $text = $rev->getText();
4480 return $this->getOutputFromWikitext( $text, $useParserCache );
4484 * Sets the context this Article is executed in
4486 * @param $context RequestContext
4489 public function setContext( $context ) {
4490 $this->mContext
= $context;
4494 * Gets the context this Article is executed in
4496 * @return RequestContext
4499 public function getContext() {
4500 if ( $this->mContext
instanceof RequestContext
) {
4501 return $this->mContext
;
4503 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4504 return RequestContext
::getMain();
4510 class PoolWorkArticleView
extends PoolCounterWork
{
4517 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4518 parent
::__construct( 'ArticleView', $key );
4519 $this->mArticle
= $article;
4520 $this->cacheable
= $useParserCache;
4521 $this->parserOptions
= $parserOptions;
4525 return $this->mArticle
->doViewParse();
4528 function getCachedWork() {
4531 $parserCache = ParserCache
::singleton();
4532 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4534 if ( $this->mArticle
->mParserOutput
!== false ) {
4535 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4536 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4537 # Ensure that UI elements requiring revision ID have
4538 # the correct version information.
4539 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4545 function fallback() {
4546 return $this->mArticle
->tryDirtyCache();
4550 * @param $status Status
4552 function error( $status ) {
4555 $wgOut->clearHTML(); // for release() errors
4556 $wgOut->enableClientCache( false );
4557 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4559 $errortext = $status->getWikiText( false, 'view-pool-error' );
4560 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );