8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
14 * @internal documentation reviewed 15 Mar 2010
27 var $mContentLoaded = false; // !<
28 var $mCounter = -1; // !< Not loaded
29 var $mDataLoaded = false; // !<
30 var $mIsRedirect = false; // !<
31 var $mLatest = false; // !<
33 var $mPreparedEdit = false;
38 var $mRedirectedFrom = null;
43 var $mRedirectTarget = null;
48 var $mRedirectUrl = false; // !<
49 var $mRevIdFetched = 0; // !<
54 var $mLastRevision = null;
59 var $mRevision = null;
61 var $mTimestamp = ''; // !<
62 var $mTitle; // !< Title object
63 var $mTouched = '19700101000000'; // !<
78 * Constructor and clear the article
79 * @param $title Reference to a Title object.
80 * @param $oldId Integer revision ID, null to fetch from request, zero for current
82 public function __construct( Title
$title, $oldId = null ) {
83 // @todo FIXME: Does the reference play any role here?
84 $this->mTitle
=& $title;
85 $this->mOldId
= $oldId;
89 * Create an Article object of the appropriate class for the given page.
92 * @param $context RequestContext
93 * @return Article object
95 public static function newFromTitle( $title, RequestContext
$context ) {
96 if ( NS_MEDIA
== $title->getNamespace() ) {
97 // FIXME: where should this go?
98 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
102 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
104 $article->setContext( $context );
108 switch( $title->getNamespace() ) {
110 $page = new ImagePage( $title );
113 $page = new CategoryPage( $title );
116 $page = new Article( $title );
118 $page->setContext( $context );
123 * Constructor from an page id
124 * @param $id Int article ID to load
126 public static function newFromID( $id ) {
127 $t = Title
::newFromID( $id );
128 # @todo FIXME: Doesn't inherit right
129 return $t == null ?
null : new self( $t );
130 # return $t == null ? null : new static( $t ); // PHP 5.3
134 * Tell the page view functions that this view was redirected
135 * from another page on the wiki.
136 * @param $from Title object.
138 public function setRedirectedFrom( Title
$from ) {
139 $this->mRedirectedFrom
= $from;
143 * If this page is a redirect, get its target
145 * The target will be fetched from the redirect table if possible.
146 * If this page doesn't have an entry there, call insertRedirect()
147 * @return Title|mixed object, or null if this page is not a redirect
149 public function getRedirectTarget() {
150 if ( !$this->mTitle
->isRedirect() ) {
154 if ( $this->mRedirectTarget
!== null ) {
155 return $this->mRedirectTarget
;
158 # Query the redirect table
159 $dbr = wfGetDB( DB_SLAVE
);
160 $row = $dbr->selectRow( 'redirect',
161 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
162 array( 'rd_from' => $this->getID() ),
166 // rd_fragment and rd_interwiki were added later, populate them if empty
167 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
168 return $this->mRedirectTarget
= Title
::makeTitle(
169 $row->rd_namespace
, $row->rd_title
,
170 $row->rd_fragment
, $row->rd_interwiki
);
173 # This page doesn't have an entry in the redirect table
174 return $this->mRedirectTarget
= $this->insertRedirect();
178 * Insert an entry for this page into the redirect table.
180 * Don't call this function directly unless you know what you're doing.
181 * @return Title object or null if not a redirect
183 public function insertRedirect() {
184 // recurse through to only get the final target
185 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
189 $this->insertRedirectEntry( $retval );
194 * Insert or update the redirect table entry for this page to indicate
195 * it redirects to $rt .
196 * @param $rt Title redirect target
198 public function insertRedirectEntry( $rt ) {
199 $dbw = wfGetDB( DB_MASTER
);
200 $dbw->replace( 'redirect', array( 'rd_from' ),
202 'rd_from' => $this->getID(),
203 'rd_namespace' => $rt->getNamespace(),
204 'rd_title' => $rt->getDBkey(),
205 'rd_fragment' => $rt->getFragment(),
206 'rd_interwiki' => $rt->getInterwiki(),
213 * Get the Title object or URL this page redirects to
215 * @return mixed false, Title of in-wiki target, or string with URL
217 public function followRedirect() {
218 return $this->getRedirectURL( $this->getRedirectTarget() );
222 * Get the Title object this text redirects to
224 * @param $text string article content containing redirect info
225 * @return mixed false, Title of in-wiki target, or string with URL
226 * @deprecated since 1.17
228 public function followRedirectText( $text ) {
229 // recurse through to only get the final target
230 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
234 * Get the Title object or URL to use for a redirect. We use Title
235 * objects for same-wiki, non-special redirects and URLs for everything
237 * @param $rt Title Redirect target
238 * @return mixed false, Title object of local target, or string with URL
240 public function getRedirectURL( $rt ) {
242 if ( $rt->getInterwiki() != '' ) {
243 if ( $rt->isLocal() ) {
244 // Offsite wikis need an HTTP redirect.
246 // This can be hard to reverse and may produce loops,
247 // so they may be disabled in the site configuration.
248 $source = $this->mTitle
->getFullURL( 'redirect=no' );
249 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
252 if ( $rt->getNamespace() == NS_SPECIAL
) {
253 // Gotta handle redirects to special pages differently:
254 // Fill the HTTP response "Location" header and ignore
255 // the rest of the page we're on.
257 // This can be hard to reverse, so they may be disabled.
258 if ( $rt->isSpecial( 'Userlogout' ) ) {
261 return $rt->getFullURL();
269 // No or invalid redirect
274 * Get the title object of the article
275 * @return Title object of this page
277 public function getTitle() {
278 return $this->mTitle
;
283 * @todo FIXME: Shouldn't this be public?
286 public function clear() {
287 $this->mDataLoaded
= false;
288 $this->mContentLoaded
= false;
290 $this->mCounter
= -1; # Not loaded
291 $this->mRedirectedFrom
= null; # Title object if set
292 $this->mRedirectTarget
= null; # Title object if set
293 $this->mLastRevision
= null; # Latest revision
294 $this->mTimestamp
= '';
295 $this->mTouched
= '19700101000000';
296 $this->mIsRedirect
= false;
297 $this->mRevIdFetched
= 0;
298 $this->mRedirectUrl
= false;
299 $this->mLatest
= false;
300 $this->mPreparedEdit
= false;
304 * Note that getContent/loadContent do not follow redirects anymore.
305 * If you need to fetch redirectable content easily, try
306 * the shortcut in Article::followRedirect()
308 * This function has side effects! Do not use this function if you
309 * only want the real revision text if any.
311 * @return Return the text of this revision
313 public function getContent() {
316 wfProfileIn( __METHOD__
);
318 if ( $this->getID() === 0 ) {
319 # If this is a MediaWiki:x message, then load the messages
320 # and return the message value for x.
321 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
322 $text = $this->mTitle
->getDefaultMessageText();
323 if ( $text === false ) {
327 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
329 wfProfileOut( __METHOD__
);
333 $this->loadContent();
334 wfProfileOut( __METHOD__
);
336 return $this->mContent
;
341 * Get the text of the current revision. No side-effects...
343 * @return Return the text of the current revision
345 public function getRawText() {
346 // Check process cache for current revision
347 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
348 return $this->mContent
;
351 $rev = Revision
::newFromTitle( $this->mTitle
);
352 $text = $rev ?
$rev->getRawText() : false;
358 * Get the text that needs to be saved in order to undo all revisions
359 * between $undo and $undoafter. Revisions must belong to the same page,
360 * must exist and must not be deleted
361 * @param $undo Revision
362 * @param $undoafter Revision Must be an earlier revision than $undo
363 * @return mixed string on success, false on failure
365 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
366 $currentRev = Revision
::newFromTitle( $this->mTitle
);
367 if ( !$currentRev ) {
368 return false; // no page
370 $undo_text = $undo->getText();
371 $undoafter_text = $undoafter->getText();
372 $cur_text = $currentRev->getText();
374 if ( $cur_text == $undo_text ) {
375 # No use doing a merge if it's just a straight revert.
376 return $undoafter_text;
381 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
389 * @return int The oldid of the article that is to be shown, 0 for the
392 public function getOldID() {
393 if ( is_null( $this->mOldId
) ) {
394 $this->mOldId
= $this->getOldIDFromRequest();
397 return $this->mOldId
;
401 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
403 * @return int The old id for the request
405 public function getOldIDFromRequest() {
408 $this->mRedirectUrl
= false;
410 $oldid = $wgRequest->getVal( 'oldid' );
412 if ( isset( $oldid ) ) {
413 $oldid = intval( $oldid );
414 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
415 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
419 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
421 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
422 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
437 * Load the revision (including text) into this object
439 function loadContent() {
440 if ( $this->mContentLoaded
) {
444 wfProfileIn( __METHOD__
);
446 $this->fetchContent( $this->getOldID() );
448 wfProfileOut( __METHOD__
);
452 * Return the list of revision fields that should be selected to create
455 public static function selectFields() {
472 * Fetch a page record with the given conditions
473 * @param $dbr DatabaseBase object
474 * @param $conditions Array
475 * @return mixed Database result resource, or false on failure
477 protected function pageData( $dbr, $conditions ) {
478 $fields = self
::selectFields();
480 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
482 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
484 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
490 * Fetch a page record matching the Title object's namespace and title
491 * using a sanitized title string
493 * @param $dbr DatabaseBase object
494 * @param $title Title object
495 * @return mixed Database result resource, or false on failure
497 protected function pageDataFromTitle( $dbr, $title ) {
498 return $this->pageData( $dbr, array(
499 'page_namespace' => $title->getNamespace(),
500 'page_title' => $title->getDBkey() ) );
504 * Fetch a page record matching the requested ID
506 * @param $dbr DatabaseBase
508 * @return mixed Database result resource, or false on failure
510 protected function pageDataFromId( $dbr, $id ) {
511 return $this->pageData( $dbr, array( 'page_id' => $id ) );
515 * Set the general counter, title etc data loaded from
518 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
520 public function loadPageData( $data = 'fromdb' ) {
521 if ( $data === 'fromdb' ) {
522 $dbr = wfGetDB( DB_SLAVE
);
523 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
526 $lc = LinkCache
::singleton();
529 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
531 $this->mTitle
->mArticleID
= intval( $data->page_id
);
533 # Old-fashioned restrictions
534 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
536 $this->mCounter
= intval( $data->page_counter
);
537 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
538 $this->mIsRedirect
= intval( $data->page_is_redirect
);
539 $this->mLatest
= intval( $data->page_latest
);
541 $lc->addBadLinkObj( $this->mTitle
);
542 $this->mTitle
->mArticleID
= 0;
545 $this->mDataLoaded
= true;
549 * Get text of an article from database
550 * Does *NOT* follow redirects.
552 * @param $oldid Int: 0 for whatever the latest revision is
553 * @return mixed string containing article contents, or false if null
555 function fetchContent( $oldid = 0 ) {
556 if ( $this->mContentLoaded
) {
557 return $this->mContent
;
560 # Pre-fill content with error message so that if something
561 # fails we'll have something telling us what we intended.
562 $t = $this->mTitle
->getPrefixedText();
563 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
564 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
567 $revision = Revision
::newFromId( $oldid );
568 if ( $revision === null ) {
569 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
573 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
574 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
577 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
581 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
582 $this->loadPageData( $data );
585 if ( !$this->mDataLoaded
) {
586 $this->loadPageData();
589 if ( $this->mLatest
=== false ) {
590 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
594 $revision = Revision
::newFromId( $this->mLatest
);
595 if ( $revision === null ) {
596 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
601 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
602 // We should instead work with the Revision object when we need it...
603 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
605 if ( $revision->getId() == $this->mLatest
) {
606 $this->setLastEdit( $revision );
609 $this->mRevIdFetched
= $revision->getId();
610 $this->mContentLoaded
= true;
611 $this->mRevision
=& $revision;
613 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
615 return $this->mContent
;
620 * @deprecated since 1.18
622 public function forUpdate() {
623 wfDeprecated( __METHOD__
);
627 * @return int Page ID
629 public function getID() {
630 return $this->mTitle
->getArticleID();
634 * @return bool Whether or not the page exists in the database
636 public function exists() {
637 return $this->getId() > 0;
641 * Check if this page is something we're going to be showing
642 * some sort of sensible content for. If we return false, page
643 * views (plain action=view) will return an HTTP 404 response,
644 * so spiders and robots can know they're following a bad link.
648 public function hasViewableContent() {
649 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
653 * @return int The view count for the page
655 public function getCount() {
656 if ( -1 == $this->mCounter
) {
657 $id = $this->getID();
662 $dbr = wfGetDB( DB_SLAVE
);
663 $this->mCounter
= $dbr->selectField( 'page',
665 array( 'page_id' => $id ),
671 return $this->mCounter
;
675 * Determine whether a page would be suitable for being counted as an
676 * article in the site_stats table based on the title & its content
678 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
679 * if false, the current database state will be used
682 public function isCountable( $editInfo = false ) {
683 global $wgArticleCountMethod;
685 if ( !$this->mTitle
->isContentPage() ) {
689 $text = $editInfo ?
$editInfo->pst
: false;
691 if ( $this->isRedirect( $text ) ) {
695 switch ( $wgArticleCountMethod ) {
699 if ( $text === false ) {
700 $text = $this->getRawText();
702 return in_string( ',', $text );
705 // ParserOutput::getLinks() is a 2D array of page links, so
706 // to be really correct we would need to recurse in the array
707 // but the main array should only have items in it if there are
709 return (bool)count( $editInfo->output
->getLinks() );
711 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
712 array( 'pl_from' => $this->getId() ), __METHOD__
);
718 * Tests if the article text represents a redirect
720 * @param $text mixed string containing article contents, or boolean
723 public function isRedirect( $text = false ) {
724 if ( $text === false ) {
725 if ( !$this->mDataLoaded
) {
726 $this->loadPageData();
729 return (bool)$this->mIsRedirect
;
731 return Title
::newFromRedirect( $text ) !== null;
736 * Returns true if the currently-referenced revision is the current edit
737 * to this page (and it exists).
740 public function isCurrent() {
741 # If no oldid, this is the current version.
742 if ( $this->getOldID() == 0 ) {
746 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
750 * Loads everything except the text
751 * This isn't necessary for all uses, so it's only done if needed.
753 protected function loadLastEdit() {
754 if ( $this->mLastRevision
!== null ) {
755 return; // already loaded
758 # New or non-existent articles have no user information
759 $id = $this->getID();
764 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
766 $this->setLastEdit( $revision );
771 * Set the latest revision
773 protected function setLastEdit( Revision
$revision ) {
774 $this->mLastRevision
= $revision;
775 $this->mTimestamp
= $revision->getTimestamp();
779 * @return string GMT timestamp of last article revision
781 public function getTimestamp() {
782 // Check if the field has been filled by ParserCache::get()
783 if ( !$this->mTimestamp
) {
784 $this->loadLastEdit();
786 return wfTimestamp( TS_MW
, $this->mTimestamp
);
790 * @param $audience Integer: one of:
791 * Revision::FOR_PUBLIC to be displayed to all users
792 * Revision::FOR_THIS_USER to be displayed to $wgUser
793 * Revision::RAW get the text regardless of permissions
794 * @return int user ID for the user that made the last article revision
796 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
797 $this->loadLastEdit();
798 if ( $this->mLastRevision
) {
799 return $this->mLastRevision
->getUser( $audience );
806 * @param $audience Integer: one of:
807 * Revision::FOR_PUBLIC to be displayed to all users
808 * Revision::FOR_THIS_USER to be displayed to $wgUser
809 * Revision::RAW get the text regardless of permissions
810 * @return string username of the user that made the last article revision
812 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
813 $this->loadLastEdit();
814 if ( $this->mLastRevision
) {
815 return $this->mLastRevision
->getUserText( $audience );
822 * @param $audience Integer: one of:
823 * Revision::FOR_PUBLIC to be displayed to all users
824 * Revision::FOR_THIS_USER to be displayed to $wgUser
825 * Revision::RAW get the text regardless of permissions
826 * @return string Comment stored for the last article revision
828 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
829 $this->loadLastEdit();
830 if ( $this->mLastRevision
) {
831 return $this->mLastRevision
->getComment( $audience );
838 * Returns true if last revision was marked as "minor edit"
840 * @return boolean Minor edit indicator for the last article revision.
842 public function getMinorEdit() {
843 $this->loadLastEdit();
844 if ( $this->mLastRevision
) {
845 return $this->mLastRevision
->isMinor();
852 * Use this to fetch the rev ID used on page views
854 * @return int revision ID of last article revision
856 public function getRevIdFetched() {
857 if ( $this->mRevIdFetched
) {
858 return $this->mRevIdFetched
;
860 return $this->getLatest();
865 * Get a list of users who have edited this article, not including the user who made
866 * the most recent revision, which you can get from $article->getUser() if you want it
869 public function getContributors() {
870 # @todo FIXME: This is expensive; cache this info somewhere.
872 $dbr = wfGetDB( DB_SLAVE
);
873 $userTable = $dbr->tableName( 'user' );
875 if ( $dbr->implicitGroupby() ) {
876 $realNameField = 'user_real_name';
878 $realNameField = 'FIRST(user_real_name) AS user_real_name';
881 $tables = array( 'revision', 'user' );
884 'rev_user as user_id',
885 'rev_user_text AS user_name',
887 'MAX(rev_timestamp) AS timestamp',
890 $conds = array( 'rev_page' => $this->getId() );
892 // The user who made the top revision gets credited as "this page was last edited by
893 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
894 $user = $this->getUser();
896 $conds[] = "rev_user != $user";
898 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
901 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
904 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
908 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
909 'ORDER BY' => 'timestamp DESC',
912 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
913 return new UserArrayFromResult( $res );
917 * This is the default action of the index.php entry point: just view the
918 * page of the given title.
920 public function view() {
921 global $wgUser, $wgOut, $wgRequest, $wgParser;
922 global $wgUseFileCache, $wgUseETag;
924 wfProfileIn( __METHOD__
);
926 # Get variables from query string
927 $oldid = $this->getOldID();
929 # getOldID may want us to redirect somewhere else
930 if ( $this->mRedirectUrl
) {
931 $wgOut->redirect( $this->mRedirectUrl
);
932 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
933 wfProfileOut( __METHOD__
);
938 $wgOut->setArticleFlag( true );
939 # Set page title (may be overridden by DISPLAYTITLE)
940 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
942 # If we got diff in the query, we want to see a diff page instead of the article.
943 if ( $wgRequest->getCheck( 'diff' ) ) {
944 wfDebug( __METHOD__
. ": showing diff page\n" );
945 $this->showDiffPage();
946 wfProfileOut( __METHOD__
);
951 # Allow frames by default
952 $wgOut->allowClickjacking();
954 $parserCache = ParserCache
::singleton();
956 $parserOptions = $this->getParserOptions();
957 # Render printable version, use printable version cache
958 if ( $wgOut->isPrintable() ) {
959 $parserOptions->setIsPrintable( true );
960 $parserOptions->setEditSection( false );
961 } else if ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
962 $parserOptions->setEditSection( false );
965 # Try client and file cache
966 if ( $oldid === 0 && $this->checkTouched() ) {
968 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
971 # Is it client cached?
972 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
973 wfDebug( __METHOD__
. ": done 304\n" );
974 wfProfileOut( __METHOD__
);
978 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
979 wfDebug( __METHOD__
. ": done file cache\n" );
980 # tell wgOut that output is taken care of
982 $this->viewUpdates();
983 wfProfileOut( __METHOD__
);
989 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
990 $parserOptions->setEditSection( false );
993 # Should the parser cache be used?
994 $useParserCache = $this->useParserCache( $oldid );
995 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
996 if ( $wgUser->getStubThreshold() ) {
997 wfIncrStats( 'pcache_miss_stub' );
1000 $wasRedirected = $this->showRedirectedFromHeader();
1001 $this->showNamespaceHeader();
1003 # Iterate through the possible ways of constructing the output text.
1004 # Keep going until $outputDone is set, or we run out of things to do.
1006 $outputDone = false;
1007 $this->mParserOutput
= false;
1009 while ( !$outputDone && ++
$pass ) {
1012 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
1015 # Try the parser cache
1016 if ( $useParserCache ) {
1017 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1019 if ( $this->mParserOutput
!== false ) {
1020 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
1021 $wgOut->addParserOutput( $this->mParserOutput
);
1022 # Ensure that UI elements requiring revision ID have
1023 # the correct version information.
1024 $wgOut->setRevisionId( $this->mLatest
);
1030 $text = $this->getContent();
1031 if ( $text === false ||
$this->getID() == 0 ) {
1032 wfDebug( __METHOD__
. ": showing missing article\n" );
1033 $this->showMissingArticle();
1034 wfProfileOut( __METHOD__
);
1038 # Another whitelist check in case oldid is altering the title
1039 if ( !$this->mTitle
->userCanRead() ) {
1040 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
1041 $wgOut->loginToUse();
1044 wfProfileOut( __METHOD__
);
1048 # Are we looking at an old revision
1049 if ( $oldid && !is_null( $this->mRevision
) ) {
1050 $this->setOldSubtitle( $oldid );
1052 if ( !$this->showDeletedRevisionHeader() ) {
1053 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
1054 wfProfileOut( __METHOD__
);
1058 # If this "old" version is the current, then try the parser cache...
1059 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
1060 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1061 if ( $this->mParserOutput
) {
1062 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
1063 $wgOut->addParserOutput( $this->mParserOutput
);
1064 $wgOut->setRevisionId( $this->mLatest
);
1071 # Ensure that UI elements requiring revision ID have
1072 # the correct version information.
1073 $wgOut->setRevisionId( $this->getRevIdFetched() );
1075 # Pages containing custom CSS or JavaScript get special treatment
1076 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1077 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1078 $this->showCssOrJsPage();
1081 $rt = Title
::newFromRedirectArray( $text );
1083 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1084 # Viewing a redirect page (e.g. with parameter redirect=no)
1085 # Don't append the subtitle if this was an old revision
1086 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1087 # Parse just to get categories, displaytitle, etc.
1088 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1089 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1095 # Run the parse, protected by a pool counter
1096 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1098 $key = $parserCache->getKey( $this, $parserOptions );
1099 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1101 if ( !$poolArticleView->execute() ) {
1102 # Connection or timeout error
1103 wfProfileOut( __METHOD__
);
1109 # Should be unreachable, but just in case...
1115 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1116 if ( $this->mParserOutput
) {
1117 $titleText = $this->mParserOutput
->getTitleText();
1119 if ( strval( $titleText ) !== '' ) {
1120 $wgOut->setPageTitle( $titleText );
1124 # For the main page, overwrite the <title> element with the con-
1125 # tents of 'pagetitle-view-mainpage' instead of the default (if
1126 # that's not empty).
1127 # This message always exists because it is in the i18n files
1128 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1129 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1130 if ( !$msg->isDisabled() ) {
1131 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1135 # Now that we've filled $this->mParserOutput, we know whether
1136 # there are any __NOINDEX__ tags on the page
1137 $policy = $this->getRobotPolicy( 'view' );
1138 $wgOut->setIndexPolicy( $policy['index'] );
1139 $wgOut->setFollowPolicy( $policy['follow'] );
1141 $this->showViewFooter();
1142 $this->viewUpdates();
1143 wfProfileOut( __METHOD__
);
1147 * Show a diff page according to current request variables. For use within
1148 * Article::view() only, other callers should use the DifferenceEngine class.
1150 public function showDiffPage() {
1151 global $wgRequest, $wgUser;
1153 $diff = $wgRequest->getVal( 'diff' );
1154 $rcid = $wgRequest->getVal( 'rcid' );
1155 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1156 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1157 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1158 $oldid = $this->getOldID();
1160 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1161 // DifferenceEngine directly fetched the revision:
1162 $this->mRevIdFetched
= $de->mNewid
;
1163 $de->showDiffPage( $diffOnly );
1165 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1166 # Run view updates for current revision only
1167 $this->viewUpdates();
1172 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1173 * Article::view() only.
1175 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1178 protected function showCssOrJsPage() {
1181 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1183 // Give hooks a chance to customise the output
1184 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1185 // Wrap the whole lot in a <pre> and don't parse
1187 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1188 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1189 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1190 $wgOut->addHTML( "\n</pre>\n" );
1195 * Get the robot policy to be used for the current view
1196 * @param $action String the action= GET parameter
1197 * @return Array the policy that should be set
1198 * TODO: actions other than 'view'
1200 public function getRobotPolicy( $action ) {
1201 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1202 global $wgDefaultRobotPolicy, $wgRequest;
1204 $ns = $this->mTitle
->getNamespace();
1206 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1207 # Don't index user and user talk pages for blocked users (bug 11443)
1208 if ( !$this->mTitle
->isSubpage() ) {
1209 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1211 'index' => 'noindex',
1212 'follow' => 'nofollow'
1218 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1219 # Non-articles (special pages etc), and old revisions
1221 'index' => 'noindex',
1222 'follow' => 'nofollow'
1224 } elseif ( $wgOut->isPrintable() ) {
1225 # Discourage indexing of printable versions, but encourage following
1227 'index' => 'noindex',
1228 'follow' => 'follow'
1230 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1231 # For ?curid=x urls, disallow indexing
1233 'index' => 'noindex',
1234 'follow' => 'follow'
1238 # Otherwise, construct the policy based on the various config variables.
1239 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1241 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1242 # Honour customised robot policies for this namespace
1243 $policy = array_merge(
1245 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1248 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1249 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1250 # a final sanity check that we have really got the parser output.
1251 $policy = array_merge(
1253 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1257 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1258 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1259 $policy = array_merge(
1261 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1269 * Converts a String robot policy into an associative array, to allow
1270 * merging of several policies using array_merge().
1271 * @param $policy Mixed, returns empty array on null/false/'', transparent
1272 * to already-converted arrays, converts String.
1273 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1275 public static function formatRobotPolicy( $policy ) {
1276 if ( is_array( $policy ) ) {
1278 } elseif ( !$policy ) {
1282 $policy = explode( ',', $policy );
1283 $policy = array_map( 'trim', $policy );
1286 foreach ( $policy as $var ) {
1287 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1288 $arr['index'] = $var;
1289 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1290 $arr['follow'] = $var;
1298 * If this request is a redirect view, send "redirected from" subtitle to
1299 * $wgOut. Returns true if the header was needed, false if this is not a
1300 * redirect view. Handles both local and remote redirects.
1304 public function showRedirectedFromHeader() {
1305 global $wgOut, $wgRequest, $wgRedirectSources;
1307 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1309 if ( isset( $this->mRedirectedFrom
) ) {
1310 // This is an internally redirected page view.
1311 // We'll need a backlink to the source page for navigation.
1312 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1313 $redir = Linker
::link(
1314 $this->mRedirectedFrom
,
1317 array( 'redirect' => 'no' ),
1318 array( 'known', 'noclasses' )
1321 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1322 $wgOut->setSubtitle( $s );
1324 // Set the fragment if one was specified in the redirect
1325 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1326 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1327 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1330 // Add a <link rel="canonical"> tag
1331 $wgOut->addLink( array( 'rel' => 'canonical',
1332 'href' => $this->mTitle
->getLocalURL() )
1337 } elseif ( $rdfrom ) {
1338 // This is an externally redirected view, from some other wiki.
1339 // If it was reported from a trusted site, supply a backlink.
1340 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1341 $redir = Linker
::makeExternalLink( $rdfrom, $rdfrom );
1342 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1343 $wgOut->setSubtitle( $s );
1353 * Show a header specific to the namespace currently being viewed, like
1354 * [[MediaWiki:Talkpagetext]]. For Article::view().
1356 public function showNamespaceHeader() {
1359 if ( $this->mTitle
->isTalkPage() ) {
1360 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1361 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1367 * Show the footer section of an ordinary page view
1369 public function showViewFooter() {
1370 global $wgOut, $wgUseTrackbacks;
1372 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1373 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1374 $wgOut->addWikiMsg( 'anontalkpagetext' );
1377 # If we have been passed an &rcid= parameter, we want to give the user a
1378 # chance to mark this new article as patrolled.
1379 $this->showPatrolFooter();
1382 if ( $wgUseTrackbacks ) {
1383 $this->addTrackbacks();
1386 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1391 * If patrol is possible, output a patrol UI box. This is called from the
1392 * footer section of ordinary page views. If patrol is not possible or not
1393 * desired, does nothing.
1395 public function showPatrolFooter() {
1396 global $wgOut, $wgRequest, $wgUser;
1398 $rcid = $wgRequest->getVal( 'rcid' );
1400 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1404 $token = $wgUser->editToken( $rcid );
1405 $wgOut->preventClickjacking();
1408 "<div class='patrollink'>" .
1410 'markaspatrolledlink',
1413 wfMsgHtml( 'markaspatrolledtext' ),
1416 'action' => 'markpatrolled',
1420 array( 'known', 'noclasses' )
1428 * Show the error text for a missing article. For articles in the MediaWiki
1429 * namespace, show the default message text. To be called from Article::view().
1431 public function showMissingArticle() {
1432 global $wgOut, $wgRequest, $wgUser;
1434 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1435 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1436 $parts = explode( '/', $this->mTitle
->getText() );
1437 $rootPart = $parts[0];
1438 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1439 $ip = User
::isIP( $rootPart );
1441 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1442 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1443 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1444 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1445 LogEventsList
::showLogExtract(
1448 $user->getUserPage()->getPrefixedText(),
1452 'showIfEmpty' => false,
1454 'blocked-notice-logextract',
1455 $user->getName() # Support GENDER in notice
1462 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1464 # Show delete and move logs
1465 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1467 'conds' => array( "log_action != 'revision'" ),
1468 'showIfEmpty' => false,
1469 'msgKey' => array( 'moveddeleted-notice' ) )
1472 # Show error message
1473 $oldid = $this->getOldID();
1475 $text = wfMsgNoTrans( 'missing-article',
1476 $this->mTitle
->getPrefixedText(),
1477 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1478 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1479 // Use the default message text
1480 $text = $this->mTitle
->getDefaultMessageText();
1482 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1483 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1484 $errors = array_merge( $createErrors, $editErrors );
1486 if ( !count( $errors ) ) {
1487 $text = wfMsgNoTrans( 'noarticletext' );
1489 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1492 $text = "<div class='noarticletext'>\n$text\n</div>";
1494 if ( !$this->hasViewableContent() ) {
1495 // If there's no backing content, send a 404 Not Found
1496 // for better machine handling of broken links.
1497 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1500 $wgOut->addWikiText( $text );
1504 * If the revision requested for view is deleted, check permissions.
1505 * Send either an error message or a warning header to $wgOut.
1507 * @return boolean true if the view is allowed, false if not.
1509 public function showDeletedRevisionHeader() {
1510 global $wgOut, $wgRequest;
1512 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1517 // If the user is not allowed to see it...
1518 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1519 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1520 'rev-deleted-text-permission' );
1523 // If the user needs to confirm that they want to see it...
1524 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1525 # Give explanation and add a link to view the revision...
1526 $oldid = intval( $this->getOldID() );
1527 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1528 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1529 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1530 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1531 array( $msg, $link ) );
1534 // We are allowed to see...
1536 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1537 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1538 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1545 * Should the parser cache be used?
1549 public function useParserCache( $oldid ) {
1550 global $wgUser, $wgEnableParserCache;
1552 return $wgEnableParserCache
1553 && $wgUser->getStubThreshold() == 0
1556 && !$this->mTitle
->isCssOrJsPage()
1557 && !$this->mTitle
->isCssJsSubpage();
1561 * Execute the uncached parse for action=view
1563 public function doViewParse() {
1566 $oldid = $this->getOldID();
1567 $parserOptions = $this->getParserOptions();
1569 # Render printable version, use printable version cache
1570 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1572 # Don't show section-edit links on old revisions... this way lies madness.
1573 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1574 $parserOptions->setEditSection( false );
1577 $useParserCache = $this->useParserCache( $oldid );
1578 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1584 * Try to fetch an expired entry from the parser cache. If it is present,
1585 * output it and return true. If it is not present, output nothing and
1586 * return false. This is used as a callback function for
1587 * PoolCounter::executeProtected().
1591 public function tryDirtyCache() {
1593 $parserCache = ParserCache
::singleton();
1594 $options = $this->getParserOptions();
1596 if ( $wgOut->isPrintable() ) {
1597 $options->setIsPrintable( true );
1598 $options->setEditSection( false );
1601 $output = $parserCache->getDirty( $this, $options );
1604 wfDebug( __METHOD__
. ": sending dirty output\n" );
1605 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1606 $wgOut->setSquidMaxage( 0 );
1607 $this->mParserOutput
= $output;
1608 $wgOut->addParserOutput( $output );
1609 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1613 wfDebugLog( 'dirty', "dirty missing\n" );
1614 wfDebug( __METHOD__
. ": no dirty cache\n" );
1623 * @param $target Title|Array of destination(s) to redirect
1624 * @param $appendSubtitle Boolean [optional]
1625 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1626 * @return string containing HMTL with redirect link
1628 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1629 global $wgOut, $wgContLang, $wgStylePath;
1631 if ( !is_array( $target ) ) {
1632 $target = array( $target );
1635 $imageDir = $wgContLang->getDir();
1637 if ( $appendSubtitle ) {
1638 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1641 // the loop prepends the arrow image before the link, so the first case needs to be outside
1642 $title = array_shift( $target );
1644 if ( $forceKnown ) {
1645 $link = Linker
::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1647 $link = Linker
::link( $title, htmlspecialchars( $title->getFullText() ) );
1650 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1651 $alt = $wgContLang->isRTL() ?
'←' : '→';
1652 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1653 foreach ( $target as $rt ) {
1654 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1655 if ( $forceKnown ) {
1656 $link .= Linker
::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1658 $link .= Linker
::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1662 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1663 return '<div class="redirectMsg">' .
1664 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1665 '<span class="redirectText">' . $link . '</span></div>';
1669 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1671 public function addTrackbacks() {
1674 $dbr = wfGetDB( DB_SLAVE
);
1675 $tbs = $dbr->select( 'trackbacks',
1676 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1677 array( 'tb_page' => $this->getID() )
1680 if ( !$dbr->numRows( $tbs ) ) {
1684 $wgOut->preventClickjacking();
1687 foreach ( $tbs as $o ) {
1690 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1691 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1692 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1693 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1697 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1705 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1709 * Removes trackback record for current article from trackbacks table
1711 public function deletetrackback() {
1712 global $wgRequest, $wgOut;
1714 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1715 $wgOut->addWikiMsg( 'sessionfailure' );
1720 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
1722 if ( count( $permission_errors ) ) {
1723 $wgOut->showPermissionsErrorPage( $permission_errors );
1728 $db = wfGetDB( DB_MASTER
);
1729 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1731 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1732 $this->mTitle
->invalidateCache();
1736 * Handle action=render
1739 public function render() {
1742 $wgOut->setArticleBodyOnly( true );
1747 * Handle action=purge
1749 public function purge() {
1750 return Action
::factory( 'purge', $this )->show();
1754 * Perform the actions of a page purging
1756 public function doPurge() {
1759 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1763 // Invalidate the cache
1764 $this->mTitle
->invalidateCache();
1767 if ( $wgUseSquid ) {
1768 // Commit the transaction before the purge is sent
1769 $dbw = wfGetDB( DB_MASTER
);
1773 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1774 $update->doUpdate();
1777 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1778 if ( $this->getID() == 0 ) {
1781 $text = $this->getRawText();
1784 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1789 * Insert a new empty page record for this article.
1790 * This *must* be followed up by creating a revision
1791 * and running $this->updateRevisionOn( ... );
1792 * or else the record will be left in a funky state.
1793 * Best if all done inside a transaction.
1795 * @param $dbw DatabaseBase
1796 * @return int The newly created page_id key, or false if the title already existed
1799 public function insertOn( $dbw ) {
1800 wfProfileIn( __METHOD__
);
1802 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1803 $dbw->insert( 'page', array(
1804 'page_id' => $page_id,
1805 'page_namespace' => $this->mTitle
->getNamespace(),
1806 'page_title' => $this->mTitle
->getDBkey(),
1807 'page_counter' => 0,
1808 'page_restrictions' => '',
1809 'page_is_redirect' => 0, # Will set this shortly...
1811 'page_random' => wfRandom(),
1812 'page_touched' => $dbw->timestamp(),
1813 'page_latest' => 0, # Fill this in shortly...
1814 'page_len' => 0, # Fill this in shortly...
1815 ), __METHOD__
, 'IGNORE' );
1817 $affected = $dbw->affectedRows();
1820 $newid = $dbw->insertId();
1821 $this->mTitle
->resetArticleID( $newid );
1823 wfProfileOut( __METHOD__
);
1825 return $affected ?
$newid : false;
1829 * Update the page record to point to a newly saved revision.
1831 * @param $dbw DatabaseBase: object
1832 * @param $revision Revision: For ID number, and text used to set
1833 length and redirect status fields
1834 * @param $lastRevision Integer: if given, will not overwrite the page field
1835 * when different from the currently set value.
1836 * Giving 0 indicates the new page flag should be set
1838 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1839 * removing rows in redirect table.
1840 * @return bool true on success, false on failure
1843 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1844 wfProfileIn( __METHOD__
);
1846 $text = $revision->getText();
1847 $rt = Title
::newFromRedirectRecurse( $text );
1849 $conditions = array( 'page_id' => $this->getId() );
1851 if ( !is_null( $lastRevision ) ) {
1852 # An extra check against threads stepping on each other
1853 $conditions['page_latest'] = $lastRevision;
1856 $dbw->update( 'page',
1858 'page_latest' => $revision->getId(),
1859 'page_touched' => $dbw->timestamp(),
1860 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1861 'page_is_redirect' => $rt !== null ?
1 : 0,
1862 'page_len' => strlen( $text ),
1867 $result = $dbw->affectedRows() != 0;
1869 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1872 wfProfileOut( __METHOD__
);
1877 * Add row to the redirect table if this is a redirect, remove otherwise.
1879 * @param $dbw DatabaseBase
1880 * @param $redirectTitle Title object pointing to the redirect target,
1881 * or NULL if this is not a redirect
1882 * @param $lastRevIsRedirect If given, will optimize adding and
1883 * removing rows in redirect table.
1884 * @return bool true on success, false on failure
1887 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1888 // Always update redirects (target link might have changed)
1889 // Update/Insert if we don't know if the last revision was a redirect or not
1890 // Delete if changing from redirect to non-redirect
1891 $isRedirect = !is_null( $redirectTitle );
1893 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1897 wfProfileIn( __METHOD__
);
1898 if ( $isRedirect ) {
1899 $this->insertRedirectEntry( $redirectTitle );
1901 // This is not a redirect, remove row from redirect table
1902 $where = array( 'rd_from' => $this->getId() );
1903 $dbw->delete( 'redirect', $where, __METHOD__
);
1906 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1907 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1909 wfProfileOut( __METHOD__
);
1911 return ( $dbw->affectedRows() != 0 );
1915 * If the given revision is newer than the currently set page_latest,
1916 * update the page record. Otherwise, do nothing.
1918 * @param $dbw Database object
1919 * @param $revision Revision object
1922 public function updateIfNewerOn( &$dbw, $revision ) {
1923 wfProfileIn( __METHOD__
);
1925 $row = $dbw->selectRow(
1926 array( 'revision', 'page' ),
1927 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1929 'page_id' => $this->getId(),
1930 'page_latest=rev_id' ),
1934 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1935 wfProfileOut( __METHOD__
);
1938 $prev = $row->rev_id
;
1939 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1941 # No or missing previous revision; mark the page as new
1943 $lastRevIsRedirect = null;
1946 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1948 wfProfileOut( __METHOD__
);
1953 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1954 * @param $text String: new text of the section
1955 * @param $summary String: new section's subject, only if $section is 'new'
1956 * @param $edittime String: revision timestamp or null to use the current revision
1957 * @return string Complete article text, or null if error
1959 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1960 wfProfileIn( __METHOD__
);
1962 if ( strval( $section ) == '' ) {
1963 // Whole-page edit; let the whole text through
1965 if ( is_null( $edittime ) ) {
1966 $rev = Revision
::newFromTitle( $this->mTitle
);
1968 $dbw = wfGetDB( DB_MASTER
);
1969 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1973 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1974 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1975 wfProfileOut( __METHOD__
);
1979 $oldtext = $rev->getText();
1981 if ( $section == 'new' ) {
1982 # Inserting a new section
1983 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1984 $text = strlen( trim( $oldtext ) ) > 0
1985 ?
"{$oldtext}\n\n{$subject}{$text}"
1986 : "{$subject}{$text}";
1988 # Replacing an existing section; roll out the big guns
1991 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1995 wfProfileOut( __METHOD__
);
2000 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
2002 * @return Int updated $flags
2004 function checkFlags( $flags ) {
2005 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
2006 if ( $this->mTitle
->getArticleID() ) {
2007 $flags |
= EDIT_UPDATE
;
2019 * Change an existing article or create a new article. Updates RC and all necessary caches,
2020 * optionally via the deferred update array.
2022 * $wgUser must be set before calling this function.
2024 * @param $text String: new text
2025 * @param $summary String: edit summary
2026 * @param $flags Integer bitfield:
2028 * Article is known or assumed to be non-existent, create a new one
2030 * Article is known or assumed to be pre-existing, update it
2032 * Mark this edit minor, if the user is allowed to do so
2034 * Do not log the change in recentchanges
2036 * Mark the edit a "bot" edit regardless of user rights
2037 * EDIT_DEFER_UPDATES
2038 * Defer some of the updates until the end of index.php
2040 * Fill in blank summaries with generated text where possible
2042 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2043 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2044 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2045 * edit-already-exists error will be returned. These two conditions are also possible with
2046 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2048 * @param $baseRevId the revision ID this edit was based off, if any
2049 * @param $user User (optional), $wgUser will be used if not passed
2051 * @return Status object. Possible errors:
2052 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2053 * edit-gone-missing: In update mode, but the article didn't exist
2054 * edit-conflict: In update mode, the article changed unexpectedly
2055 * edit-no-change: Warning that the text was the same as before
2056 * edit-already-exists: In creation mode, but the article already exists
2058 * Extensions may define additional errors.
2060 * $return->value will contain an associative array with members as follows:
2061 * new: Boolean indicating if the function attempted to create a new article
2062 * revision: The revision object for the inserted revision, or null
2064 * Compatibility note: this function previously returned a boolean value indicating success/failure
2066 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2067 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2069 # Low-level sanity check
2070 if ( $this->mTitle
->getText() === '' ) {
2071 throw new MWException( 'Something is trying to edit an article with an empty title' );
2074 wfProfileIn( __METHOD__
);
2076 $user = is_null( $user ) ?
$wgUser : $user;
2077 $status = Status
::newGood( array() );
2079 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2080 $this->loadPageData();
2082 $flags = $this->checkFlags( $flags );
2084 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2085 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2087 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2089 if ( $status->isOK() ) {
2090 $status->fatal( 'edit-hook-aborted' );
2093 wfProfileOut( __METHOD__
);
2097 # Silently ignore EDIT_MINOR if not allowed
2098 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2099 $bot = $flags & EDIT_FORCE_BOT
;
2101 $oldtext = $this->getRawText(); // current revision
2102 $oldsize = strlen( $oldtext );
2104 # Provide autosummaries if one is not provided and autosummaries are enabled.
2105 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2106 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2109 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2110 $text = $editInfo->pst
;
2111 $newsize = strlen( $text );
2113 $dbw = wfGetDB( DB_MASTER
);
2114 $now = wfTimestampNow();
2115 $this->mTimestamp
= $now;
2117 if ( $flags & EDIT_UPDATE
) {
2118 # Update article, but only if changed.
2119 $status->value
['new'] = false;
2121 # Make sure the revision is either completely inserted or not inserted at all
2122 if ( !$wgDBtransactions ) {
2123 $userAbort = ignore_user_abort( true );
2126 $changed = ( strcmp( $text, $oldtext ) != 0 );
2129 if ( !$this->mLatest
) {
2130 # Article gone missing
2131 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2132 $status->fatal( 'edit-gone-missing' );
2134 wfProfileOut( __METHOD__
);
2138 $revision = new Revision( array(
2139 'page' => $this->getId(),
2140 'comment' => $summary,
2141 'minor_edit' => $isminor,
2143 'parent_id' => $this->mLatest
,
2144 'user' => $user->getId(),
2145 'user_text' => $user->getName(),
2150 $revisionId = $revision->insertOn( $dbw );
2154 # Note that we use $this->mLatest instead of fetching a value from the master DB
2155 # during the course of this function. This makes sure that EditPage can detect
2156 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2157 # before this function is called. A previous function used a separate query, this
2158 # creates a window where concurrent edits can cause an ignored edit conflict.
2159 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2162 /* Belated edit conflict! Run away!! */
2163 $status->fatal( 'edit-conflict' );
2165 # Delete the invalid revision if the DB is not transactional
2166 if ( !$wgDBtransactions ) {
2167 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2173 global $wgUseRCPatrol;
2174 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2175 # Update recentchanges
2176 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2177 # Mark as patrolled if the user can do so
2178 $patrolled = $wgUseRCPatrol && !count(
2179 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2180 # Add RC row to the DB
2181 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2182 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2183 $revisionId, $patrolled
2186 # Log auto-patrolled edits
2188 PatrolLog
::record( $rc, true );
2191 $user->incEditCount();
2195 $status->warning( 'edit-no-change' );
2197 // Keep the same revision ID, but do some updates on it
2198 $revisionId = $this->getLatest();
2199 // Update page_touched, this is usually implicit in the page update
2200 // Other cache updates are done in onArticleEdit()
2201 $this->mTitle
->invalidateCache();
2204 if ( !$wgDBtransactions ) {
2205 ignore_user_abort( $userAbort );
2208 // Now that ignore_user_abort is restored, we can respond to fatal errors
2209 if ( !$status->isOK() ) {
2210 wfProfileOut( __METHOD__
);
2214 # Invalidate cache of this article and all pages using this article
2215 # as a template. Partly deferred.
2216 Article
::onArticleEdit( $this->mTitle
);
2217 # Update links tables, site stats, etc.
2218 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2220 # Create new article
2221 $status->value
['new'] = true;
2225 # Add the page record; stake our claim on this title!
2226 # This will return false if the article already exists
2227 $newid = $this->insertOn( $dbw );
2229 if ( $newid === false ) {
2231 $status->fatal( 'edit-already-exists' );
2233 wfProfileOut( __METHOD__
);
2237 # Save the revision text...
2238 $revision = new Revision( array(
2240 'comment' => $summary,
2241 'minor_edit' => $isminor,
2243 'user' => $user->getId(),
2244 'user_text' => $user->getName(),
2247 $revisionId = $revision->insertOn( $dbw );
2249 $this->mTitle
->resetArticleID( $newid );
2250 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
2252 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2254 # Update the page record with revision data
2255 $this->updateRevisionOn( $dbw, $revision, 0 );
2257 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2259 # Update recentchanges
2260 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2261 global $wgUseRCPatrol, $wgUseNPPatrol;
2263 # Mark as patrolled if the user can do so
2264 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2265 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2266 # Add RC row to the DB
2267 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2268 '', strlen( $text ), $revisionId, $patrolled );
2270 # Log auto-patrolled edits
2272 PatrolLog
::record( $rc, true );
2275 $user->incEditCount();
2278 # Update links, etc.
2279 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user, true );
2282 Article
::onArticleCreate( $this->mTitle
);
2284 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2285 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2288 # Do updates right now unless deferral was requested
2289 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2293 // Return the new revision (or null) to the caller
2294 $status->value
['revision'] = $revision;
2296 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2297 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2299 wfProfileOut( __METHOD__
);
2304 * Output a redirect back to the article.
2305 * This is typically used after an edit.
2307 * @param $noRedir Boolean: add redirect=no
2308 * @param $sectionAnchor String: section to redirect to, including "#"
2309 * @param $extraQuery String: extra query params
2311 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2315 $query = 'redirect=no';
2317 $query .= "&$extraQuery";
2319 $query = $extraQuery;
2322 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2326 * Mark this particular edit/page as patrolled
2328 public function markpatrolled() {
2329 global $wgOut, $wgRequest;
2331 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2333 # If we haven't been given an rc_id value, we can't do anything
2334 $rcid = (int) $wgRequest->getVal( 'rcid' );
2336 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2337 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2341 $rc = RecentChange
::newFromId( $rcid );
2343 if ( is_null( $rc ) ) {
2344 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2348 # It would be nice to see where the user had actually come from, but for now just guess
2349 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2350 $return = SpecialPage
::getTitleFor( $returnto );
2352 $errors = $rc->doMarkPatrolled();
2354 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2355 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2360 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2361 // The hook itself has handled any output
2365 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2366 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2367 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2368 $wgOut->returnToMain( null, $return );
2373 if ( !empty( $errors ) ) {
2374 $wgOut->showPermissionsErrorPage( $errors );
2380 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2381 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2382 $wgOut->returnToMain( null, $return );
2386 * User-interface handler for the "watch" action
2387 * @deprecated since 1.18
2389 public function watch() {
2390 Action
::factory( 'watch', $this )->show();
2394 * Add this page to $wgUser's watchlist
2396 * This is safe to be called multiple times
2398 * @return bool true on successful watch operation
2399 * @deprecated since 1.18
2401 public function doWatch() {
2402 return Action
::factory( 'watch', $this )->execute();
2406 * User interface handler for the "unwatch" action.
2407 * @deprecated since 1.18
2409 public function unwatch() {
2410 Action
::factory( 'unwatch', $this )->show();
2414 * Stop watching a page
2415 * @return bool true on successful unwatch
2416 * @deprecated since 1.18
2418 public function doUnwatch() {
2419 return Action
::factory( 'unwatch', $this )->execute();
2423 * action=protect handler
2425 public function protect() {
2426 $form = new ProtectionForm( $this );
2431 * action=unprotect handler (alias)
2433 public function unprotect() {
2438 * Update the article's restriction field, and leave a log entry.
2440 * @param $limit Array: set of restriction keys
2441 * @param $reason String
2442 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2443 * @param $expiry Array: per restriction type expiration
2444 * @return bool true on success
2446 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2447 global $wgUser, $wgContLang;
2449 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2451 $id = $this->mTitle
->getArticleID();
2454 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2458 if ( wfReadOnly() ) {
2459 wfDebug( "updateRestrictions failed: read-only\n" );
2463 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2464 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2472 // Take this opportunity to purge out expired restrictions
2473 Title
::purgeExpiredRestrictions();
2475 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2476 # we expect a single selection, but the schema allows otherwise.
2478 $updated = Article
::flattenRestrictions( $limit );
2481 foreach ( $restrictionTypes as $action ) {
2482 if ( isset( $expiry[$action] ) ) {
2483 # Get current restrictions on $action
2484 $aLimits = $this->mTitle
->getRestrictions( $action );
2485 $current[$action] = implode( '', $aLimits );
2486 # Are any actual restrictions being dealt with here?
2487 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2489 # If something changed, we need to log it. Checking $aRChanged
2490 # assures that "unprotecting" a page that is not protected does
2491 # not log just because the expiry was "changed".
2492 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2498 $current = Article
::flattenRestrictions( $current );
2500 $changed = ( $changed ||
$current != $updated );
2501 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2502 $protect = ( $updated != '' );
2504 # If nothing's changed, do nothing
2506 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2507 $dbw = wfGetDB( DB_MASTER
);
2509 # Prepare a null revision to be added to the history
2510 $modified = $current != '' && $protect;
2513 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2515 $comment_type = 'unprotectedarticle';
2518 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2520 # Only restrictions with the 'protect' right can cascade...
2521 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2522 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2524 # The schema allows multiple restrictions
2525 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2529 $cascade_description = '';
2532 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2536 $comment .= ": $reason";
2539 $editComment = $comment;
2540 $encodedExpiry = array();
2541 $protect_description = '';
2542 foreach ( $limit as $action => $restrictions ) {
2543 if ( !isset( $expiry[$action] ) )
2544 $expiry[$action] = $dbw->getInfinity();
2546 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2547 if ( $restrictions != '' ) {
2548 $protect_description .= "[$action=$restrictions] (";
2549 if ( $encodedExpiry[$action] != 'infinity' ) {
2550 $protect_description .= wfMsgForContent( 'protect-expiring',
2551 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2552 $wgContLang->date( $expiry[$action], false, false ) ,
2553 $wgContLang->time( $expiry[$action], false, false ) );
2555 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2558 $protect_description .= ') ';
2561 $protect_description = trim( $protect_description );
2563 if ( $protect_description && $protect ) {
2564 $editComment .= " ($protect_description)";
2568 $editComment .= "$cascade_description";
2571 # Update restrictions table
2572 foreach ( $limit as $action => $restrictions ) {
2573 if ( $restrictions != '' ) {
2574 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2575 array( 'pr_page' => $id,
2576 'pr_type' => $action,
2577 'pr_level' => $restrictions,
2578 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2579 'pr_expiry' => $encodedExpiry[$action]
2584 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2585 'pr_type' => $action ), __METHOD__
);
2589 # Insert a null revision
2590 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2591 $nullRevId = $nullRevision->insertOn( $dbw );
2593 $latest = $this->getLatest();
2594 # Update page record
2595 $dbw->update( 'page',
2597 'page_touched' => $dbw->timestamp(),
2598 'page_restrictions' => '',
2599 'page_latest' => $nullRevId
2600 ), array( /* WHERE */
2602 ), 'Article::protect'
2605 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2606 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2608 # Update the protection log
2609 $log = new LogPage( 'protect' );
2611 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2612 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2614 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2617 } # End "changed" check
2623 * Take an array of page restrictions and flatten it to a string
2624 * suitable for insertion into the page_restrictions field.
2625 * @param $limit Array
2628 protected static function flattenRestrictions( $limit ) {
2629 if ( !is_array( $limit ) ) {
2630 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2636 foreach ( $limit as $action => $restrictions ) {
2637 if ( $restrictions != '' ) {
2638 $bits[] = "$action=$restrictions";
2642 return implode( ':', $bits );
2646 * Auto-generates a deletion reason
2648 * @param &$hasHistory Boolean: whether the page has a history
2649 * @return mixed String containing deletion reason or empty string, or boolean false
2650 * if no revision occurred
2652 public function generateReason( &$hasHistory ) {
2655 $dbw = wfGetDB( DB_MASTER
);
2656 // Get the last revision
2657 $rev = Revision
::newFromTitle( $this->mTitle
);
2659 if ( is_null( $rev ) ) {
2663 // Get the article's contents
2664 $contents = $rev->getText();
2667 // If the page is blank, use the text from the previous revision,
2668 // which can only be blank if there's a move/import/protect dummy revision involved
2669 if ( $contents == '' ) {
2670 $prev = $rev->getPrevious();
2673 $contents = $prev->getText();
2678 // Find out if there was only one contributor
2679 // Only scan the last 20 revisions
2680 $res = $dbw->select( 'revision', 'rev_user_text',
2681 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2683 array( 'LIMIT' => 20 )
2686 if ( $res === false ) {
2687 // This page has no revisions, which is very weird
2691 $hasHistory = ( $res->numRows() > 1 );
2692 $row = $dbw->fetchObject( $res );
2694 if ( $row ) { // $row is false if the only contributor is hidden
2695 $onlyAuthor = $row->rev_user_text
;
2696 // Try to find a second contributor
2697 foreach ( $res as $row ) {
2698 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2699 $onlyAuthor = false;
2704 $onlyAuthor = false;
2707 // Generate the summary with a '$1' placeholder
2709 // The current revision is blank and the one before is also
2710 // blank. It's just not our lucky day
2711 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2713 if ( $onlyAuthor ) {
2714 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2716 $reason = wfMsgForContent( 'excontent', '$1' );
2720 if ( $reason == '-' ) {
2721 // Allow these UI messages to be blanked out cleanly
2725 // Replace newlines with spaces to prevent uglyness
2726 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2727 // Calculate the maximum amount of chars to get
2728 // Max content length = max comment length - length of the comment (excl. $1)
2729 $maxLength = 255 - ( strlen( $reason ) - 2 );
2730 $contents = $wgContLang->truncate( $contents, $maxLength );
2731 // Remove possible unfinished links
2732 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2733 // Now replace the '$1' placeholder
2734 $reason = str_replace( '$1', $contents, $reason );
2741 * UI entry point for page deletion
2743 public function delete() {
2744 global $wgOut, $wgRequest;
2746 $confirm = $wgRequest->wasPosted() &&
2747 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2749 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2750 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2752 $reason = $this->DeleteReasonList
;
2754 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2755 // Entry from drop down menu + additional comment
2756 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2757 } elseif ( $reason == 'other' ) {
2758 $reason = $this->DeleteReason
;
2761 # Flag to hide all contents of the archived revisions
2762 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2764 # This code desperately needs to be totally rewritten
2766 # Read-only check...
2767 if ( wfReadOnly() ) {
2768 $wgOut->readOnlyPage();
2774 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2776 if ( count( $permission_errors ) > 0 ) {
2777 $wgOut->showPermissionsErrorPage( $permission_errors );
2782 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2784 # Better double-check that it hasn't been deleted yet!
2785 $dbw = wfGetDB( DB_MASTER
);
2786 $conds = $this->mTitle
->pageCond();
2787 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2788 if ( $latest === false ) {
2789 $wgOut->showFatalError(
2792 array( 'class' => 'error mw-error-cannotdelete' ),
2793 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2796 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2797 LogEventsList
::showLogExtract(
2800 $this->mTitle
->getPrefixedText()
2806 # Hack for big sites
2807 $bigHistory = $this->isBigDeletion();
2808 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2809 global $wgLang, $wgDeleteRevisionsLimit;
2811 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2812 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2818 $this->doDelete( $reason, $suppress );
2820 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2822 } elseif ( $this->mTitle
->userIsWatching() ) {
2829 // Generate deletion reason
2830 $hasHistory = false;
2832 $reason = $this->generateReason( $hasHistory );
2835 // If the page has a history, insert a warning
2836 if ( $hasHistory && !$confirm ) {
2839 $revisions = $this->estimateRevisionCount();
2840 // @todo FIXME: i18n issue/patchwork message
2841 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2842 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2843 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->mTitle
,
2844 wfMsgHtml( 'history' ),
2845 array( 'rel' => 'archives' ),
2846 array( 'action' => 'history' ) ) .
2850 if ( $bigHistory ) {
2851 global $wgDeleteRevisionsLimit;
2852 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2853 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2857 return $this->confirmDelete( $reason );
2861 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2863 public function isBigDeletion() {
2864 global $wgDeleteRevisionsLimit;
2866 if ( $wgDeleteRevisionsLimit ) {
2867 $revCount = $this->estimateRevisionCount();
2869 return $revCount > $wgDeleteRevisionsLimit;
2876 * @return int approximate revision count
2878 public function estimateRevisionCount() {
2879 $dbr = wfGetDB( DB_SLAVE
);
2881 // For an exact count...
2882 // return $dbr->selectField( 'revision', 'COUNT(*)',
2883 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2884 return $dbr->estimateRowCount( 'revision', '*',
2885 array( 'rev_page' => $this->getId() ), __METHOD__
);
2889 * Get the last N authors
2890 * @param $num Integer: number of revisions to get
2891 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2892 * @return array Array of authors, duplicates not removed
2894 public function getLastNAuthors( $num, $revLatest = 0 ) {
2895 wfProfileIn( __METHOD__
);
2896 // First try the slave
2897 // If that doesn't have the latest revision, try the master
2899 $db = wfGetDB( DB_SLAVE
);
2902 $res = $db->select( array( 'page', 'revision' ),
2903 array( 'rev_id', 'rev_user_text' ),
2905 'page_namespace' => $this->mTitle
->getNamespace(),
2906 'page_title' => $this->mTitle
->getDBkey(),
2907 'rev_page = page_id'
2910 'ORDER BY' => 'rev_timestamp DESC',
2916 wfProfileOut( __METHOD__
);
2920 $row = $db->fetchObject( $res );
2922 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2923 $db = wfGetDB( DB_MASTER
);
2928 } while ( $continue );
2930 $authors = array( $row->rev_user_text
);
2932 foreach ( $res as $row ) {
2933 $authors[] = $row->rev_user_text
;
2936 wfProfileOut( __METHOD__
);
2941 * Output deletion confirmation dialog
2942 * @todo FIXME: Move to another file?
2943 * @param $reason String: prefilled reason
2945 public function confirmDelete( $reason ) {
2948 wfDebug( "Article::confirmDelete\n" );
2950 $deleteBackLink = Linker
::linkKnown( $this->mTitle
);
2951 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2952 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2953 $wgOut->addWikiMsg( 'confirmdeletetext' );
2955 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2957 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2958 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2960 <td class='mw-input'><strong>" .
2961 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2962 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2968 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2970 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2971 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2972 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2973 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2974 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2975 "<tr id=\"wpDeleteReasonListRow\">
2976 <td class='mw-label'>" .
2977 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2979 <td class='mw-input'>" .
2980 Xml
::listDropDown( 'wpDeleteReasonList',
2981 wfMsgForContent( 'deletereason-dropdown' ),
2982 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2985 <tr id=\"wpDeleteReasonRow\">
2986 <td class='mw-label'>" .
2987 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2989 <td class='mw-input'>" .
2990 Html
::input( 'wpReason', $reason, 'text', array(
2992 'maxlength' => '255',
3000 # Disallow watching if user is not logged in
3001 if ( $wgOut->getUser()->isLoggedIn() ) {
3005 <td class='mw-input'>" .
3006 Xml
::checkLabel( wfMsg( 'watchthis' ),
3007 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3016 <td class='mw-submit'>" .
3017 Xml
::submitButton( wfMsg( 'deletepage' ),
3018 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3021 Xml
::closeElement( 'table' ) .
3022 Xml
::closeElement( 'fieldset' ) .
3023 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
3024 Xml
::closeElement( 'form' );
3026 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
3027 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
3028 $link = Linker
::link(
3030 wfMsgHtml( 'delete-edit-reasonlist' ),
3032 array( 'action' => 'edit' )
3034 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3037 $wgOut->addHTML( $form );
3038 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3039 LogEventsList
::showLogExtract( $wgOut, 'delete',
3040 $this->mTitle
->getPrefixedText()
3045 * Perform a deletion and output success or failure messages
3047 public function doDelete( $reason, $suppress = false ) {
3050 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3053 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
3054 $deleted = $this->mTitle
->getPrefixedText();
3056 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3057 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3059 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3061 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3062 $wgOut->returnToMain( false );
3064 if ( $error == '' ) {
3065 $wgOut->showFatalError(
3068 array( 'class' => 'error mw-error-cannotdelete' ),
3069 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3073 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3075 LogEventsList
::showLogExtract(
3078 $this->mTitle
->getPrefixedText()
3081 $wgOut->showFatalError( $error );
3087 * Back-end article deletion
3088 * Deletes the article with database consistency, writes logs, purges caches
3090 * @param $reason string delete reason for deletion log
3091 * @param suppress bitfield
3092 * Revision::DELETED_TEXT
3093 * Revision::DELETED_COMMENT
3094 * Revision::DELETED_USER
3095 * Revision::DELETED_RESTRICTED
3096 * @param $id int article ID
3097 * @param $commit boolean defaults to true, triggers transaction end
3098 * @return boolean true if successful
3100 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3101 global $wgDeferredUpdateList, $wgUseTrackbacks;
3104 wfDebug( __METHOD__
. "\n" );
3106 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3109 $dbw = wfGetDB( DB_MASTER
);
3110 $t = $this->mTitle
->getDBkey();
3111 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3113 if ( $t === '' ||
$id == 0 ) {
3117 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
3118 array_push( $wgDeferredUpdateList, $u );
3120 // Bitfields to further suppress the content
3123 // This should be 15...
3124 $bitfield |
= Revision
::DELETED_TEXT
;
3125 $bitfield |
= Revision
::DELETED_COMMENT
;
3126 $bitfield |
= Revision
::DELETED_USER
;
3127 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3129 $bitfield = 'rev_deleted';
3133 // For now, shunt the revision data into the archive table.
3134 // Text is *not* removed from the text table; bulk storage
3135 // is left intact to avoid breaking block-compression or
3136 // immutable storage schemes.
3138 // For backwards compatibility, note that some older archive
3139 // table entries will have ar_text and ar_flags fields still.
3141 // In the future, we may keep revisions and mark them with
3142 // the rev_deleted field, which is reserved for this purpose.
3143 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3145 'ar_namespace' => 'page_namespace',
3146 'ar_title' => 'page_title',
3147 'ar_comment' => 'rev_comment',
3148 'ar_user' => 'rev_user',
3149 'ar_user_text' => 'rev_user_text',
3150 'ar_timestamp' => 'rev_timestamp',
3151 'ar_minor_edit' => 'rev_minor_edit',
3152 'ar_rev_id' => 'rev_id',
3153 'ar_text_id' => 'rev_text_id',
3154 'ar_text' => '\'\'', // Be explicit to appease
3155 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3156 'ar_len' => 'rev_len',
3157 'ar_page_id' => 'page_id',
3158 'ar_deleted' => $bitfield
3161 'page_id = rev_page'
3165 # Delete restrictions for it
3166 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3168 # Now that it's safely backed up, delete it
3169 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3170 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3177 # Fix category table counts
3179 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3181 foreach ( $res as $row ) {
3182 $cats [] = $row->cl_to
;
3185 $this->updateCategoryCounts( array(), $cats );
3187 # If using cascading deletes, we can skip some explicit deletes
3188 if ( !$dbw->cascadingDeletes() ) {
3189 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3191 if ( $wgUseTrackbacks )
3192 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3194 # Delete outgoing links
3195 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3196 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3197 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3198 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3199 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3200 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3201 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3202 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3205 # If using cleanup triggers, we can skip some manual deletes
3206 if ( !$dbw->cleanupTriggers() ) {
3207 # Clean up recentchanges entries...
3208 $dbw->delete( 'recentchanges',
3209 array( 'rc_type != ' . RC_LOG
,
3210 'rc_namespace' => $this->mTitle
->getNamespace(),
3211 'rc_title' => $this->mTitle
->getDBkey() ),
3213 $dbw->delete( 'recentchanges',
3214 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3219 Article
::onArticleDelete( $this->mTitle
);
3221 # Clear the cached article id so the interface doesn't act like we exist
3222 $this->mTitle
->resetArticleID( 0 );
3224 # Log the deletion, if the page was suppressed, log it at Oversight instead
3225 $logtype = $suppress ?
'suppress' : 'delete';
3226 $log = new LogPage( $logtype );
3228 # Make sure logging got through
3229 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3235 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3240 * Roll back the most recent consecutive set of edits to a page
3241 * from the same user; fails if there are no eligible edits to
3242 * roll back to, e.g. user is the sole contributor. This function
3243 * performs permissions checks on $wgUser, then calls commitRollback()
3244 * to do the dirty work
3246 * @param $fromP String: Name of the user whose edits to rollback.
3247 * @param $summary String: Custom summary. Set to default summary if empty.
3248 * @param $token String: Rollback token.
3249 * @param $bot Boolean: If true, mark all reverted edits as bot.
3251 * @param $resultDetails Array: contains result-specific array of additional values
3252 * 'alreadyrolled' : 'current' (rev)
3253 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3255 * @return array of errors, each error formatted as
3256 * array(messagekey, param1, param2, ...).
3257 * On success, the array is empty. This array can also be passed to
3258 * OutputPage::showPermissionsErrorPage().
3260 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3263 $resultDetails = null;
3266 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3267 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3268 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3270 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3271 $errors[] = array( 'sessionfailure' );
3274 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3275 $errors[] = array( 'actionthrottledtext' );
3278 # If there were errors, bail out now
3279 if ( !empty( $errors ) ) {
3283 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3287 * Backend implementation of doRollback(), please refer there for parameter
3288 * and return value documentation
3290 * NOTE: This function does NOT check ANY permissions, it just commits the
3291 * rollback to the DB Therefore, you should only call this function direct-
3292 * ly if you want to use custom permissions checks. If you don't, use
3293 * doRollback() instead.
3295 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3296 global $wgUseRCPatrol, $wgUser, $wgLang;
3298 $dbw = wfGetDB( DB_MASTER
);
3300 if ( wfReadOnly() ) {
3301 return array( array( 'readonlytext' ) );
3304 # Get the last editor
3305 $current = Revision
::newFromTitle( $this->mTitle
);
3306 if ( is_null( $current ) ) {
3307 # Something wrong... no page?
3308 return array( array( 'notanarticle' ) );
3311 $from = str_replace( '_', ' ', $fromP );
3312 # User name given should match up with the top revision.
3313 # If the user was deleted then $from should be empty.
3314 if ( $from != $current->getUserText() ) {
3315 $resultDetails = array( 'current' => $current );
3316 return array( array( 'alreadyrolled',
3317 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3318 htmlspecialchars( $fromP ),
3319 htmlspecialchars( $current->getUserText() )
3323 # Get the last edit not by this guy...
3324 # Note: these may not be public values
3325 $user = intval( $current->getRawUser() );
3326 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3327 $s = $dbw->selectRow( 'revision',
3328 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3329 array( 'rev_page' => $current->getPage(),
3330 "rev_user != {$user} OR rev_user_text != {$user_text}"
3332 array( 'USE INDEX' => 'page_timestamp',
3333 'ORDER BY' => 'rev_timestamp DESC' )
3335 if ( $s === false ) {
3336 # No one else ever edited this page
3337 return array( array( 'cantrollback' ) );
3338 } else if ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3339 # Only admins can see this text
3340 return array( array( 'notvisiblerev' ) );
3344 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3345 # Mark all reverted edits as bot
3349 if ( $wgUseRCPatrol ) {
3350 # Mark all reverted edits as patrolled
3351 $set['rc_patrolled'] = 1;
3354 if ( count( $set ) ) {
3355 $dbw->update( 'recentchanges', $set,
3357 'rc_cur_id' => $current->getPage(),
3358 'rc_user_text' => $current->getUserText(),
3359 "rc_timestamp > '{$s->rev_timestamp}'",
3364 # Generate the edit summary if necessary
3365 $target = Revision
::newFromId( $s->rev_id
);
3366 if ( empty( $summary ) ) {
3367 if ( $from == '' ) { // no public user name
3368 $summary = wfMsgForContent( 'revertpage-nouser' );
3370 $summary = wfMsgForContent( 'revertpage' );
3374 # Allow the custom summary to use the same args as the default message
3376 $target->getUserText(), $from, $s->rev_id
,
3377 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3378 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3380 $summary = wfMsgReplaceArgs( $summary, $args );
3383 $flags = EDIT_UPDATE
;
3385 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3386 $flags |
= EDIT_MINOR
;
3389 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3390 $flags |
= EDIT_FORCE_BOT
;
3393 # Actually store the edit
3394 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3395 if ( !empty( $status->value
['revision'] ) ) {
3396 $revId = $status->value
['revision']->getId();
3401 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3403 $resultDetails = array(
3404 'summary' => $summary,
3405 'current' => $current,
3406 'target' => $target,
3414 * User interface for rollback operations
3416 public function rollback() {
3417 global $wgUser, $wgOut, $wgRequest;
3421 $result = $this->doRollback(
3422 $wgRequest->getVal( 'from' ),
3423 $wgRequest->getText( 'summary' ),
3424 $wgRequest->getVal( 'token' ),
3425 $wgRequest->getBool( 'bot' ),
3429 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3430 $wgOut->rateLimited();
3434 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3435 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3436 $errArray = $result[0];
3437 $errMsg = array_shift( $errArray );
3438 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3440 if ( isset( $details['current'] ) ) {
3441 $current = $details['current'];
3443 if ( $current->getComment() != '' ) {
3444 $wgOut->addWikiMsgArray( 'editcomment', array(
3445 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3452 # Display permissions errors before read-only message -- there's no
3453 # point in misleading the user into thinking the inability to rollback
3454 # is only temporary.
3455 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3456 # array_diff is completely broken for arrays of arrays, sigh.
3457 # Remove any 'readonlytext' error manually.
3459 foreach ( $result as $error ) {
3460 if ( $error != array( 'readonlytext' ) ) {
3464 $wgOut->showPermissionsErrorPage( $out );
3469 if ( $result == array( array( 'readonlytext' ) ) ) {
3470 $wgOut->readOnlyPage();
3475 $current = $details['current'];
3476 $target = $details['target'];
3477 $newId = $details['newid'];
3478 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3479 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3481 if ( $current->getUserText() === '' ) {
3482 $old = wfMsg( 'rev-deleted-user' );
3484 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
3485 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
3488 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
3489 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
3490 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3491 $wgOut->returnToMain( false, $this->mTitle
);
3493 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3494 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3495 $de->showDiff( '', '' );
3500 * Do standard deferred updates after page view
3502 public function viewUpdates() {
3503 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3504 if ( wfReadOnly() ) {
3508 # Don't update page view counters on views from bot users (bug 14044)
3509 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3510 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3511 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3514 # Update newtalk / watchlist notification status
3515 $wgUser->clearNotification( $this->mTitle
);
3519 * Prepare text which is about to be saved.
3520 * Returns a stdclass with source, pst and output members
3522 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3523 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3525 return $this->mPreparedEdit
;
3530 if( $user === null ) {
3534 $popts = ParserOptions
::newFromUser( $user );
3535 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3537 $edit = (object)array();
3538 $edit->revid
= $revid;
3539 $edit->newText
= $text;
3540 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3541 $edit->popts
= $this->getParserOptions();
3542 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3543 $edit->oldText
= $this->getRawText();
3545 $this->mPreparedEdit
= $edit;
3551 * Do standard deferred updates after page edit.
3552 * Update links tables, site stats, search index and message cache.
3553 * Purges pages that include this page if the text was changed here.
3554 * Every 100th edit, prune the recent changes table.
3557 * @param $text String: New text of the article
3558 * @param $summary String: Edit summary
3559 * @param $minoredit Boolean: Minor edit
3560 * @param $timestamp_of_pagechange String timestamp associated with the page change
3561 * @param $newid Integer: rev_id value of the new revision
3562 * @param $changed Boolean: Whether or not the content actually changed
3563 * @param $user User object: User doing the edit
3564 * @param $created Boolean: Whether the edit created the page
3566 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
3567 $changed = true, User
$user = null, $created = false )
3569 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3571 wfProfileIn( __METHOD__
);
3574 # Be careful not to double-PST: $text is usually already PST-ed once
3575 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3576 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3577 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3579 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3580 $editInfo = $this->mPreparedEdit
;
3583 # Save it to the parser cache
3584 if ( $wgEnableParserCache ) {
3585 $parserCache = ParserCache
::singleton();
3586 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3589 # Update the links tables
3590 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3593 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3595 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3596 if ( 0 == mt_rand( 0, 99 ) ) {
3597 // Flush old entries from the `recentchanges` table; we do this on
3598 // random requests so as to avoid an increase in writes for no good reason
3601 $dbw = wfGetDB( DB_MASTER
);
3602 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3605 array( "rc_timestamp < '$cutoff'" ),
3611 $id = $this->getID();
3612 $title = $this->mTitle
->getPrefixedDBkey();
3613 $shortTitle = $this->mTitle
->getDBkey();
3616 wfProfileOut( __METHOD__
);
3623 } elseif ( $created ) {
3624 $good = (int)$this->isCountable( $editInfo );
3627 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
3631 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
3632 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
3634 # If this is another user's talk page, update newtalk
3635 # Don't do this if $changed = false otherwise some idiot can null-edit a
3636 # load of user talk pages and piss people off, nor if it's a minor edit
3637 # by a properly-flagged bot.
3638 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3639 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3641 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3642 $other = User
::newFromName( $shortTitle, false );
3644 wfDebug( __METHOD__
. ": invalid username\n" );
3645 } elseif ( User
::isIP( $shortTitle ) ) {
3646 // An anonymous user
3647 $other->setNewtalk( true );
3648 } elseif ( $other->isLoggedIn() ) {
3649 $other->setNewtalk( true );
3651 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3656 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3657 MessageCache
::singleton()->replace( $shortTitle, $text );
3660 wfProfileOut( __METHOD__
);
3664 * Perform article updates on a special page creation.
3666 * @param $rev Revision object
3668 * @todo This is a shitty interface function. Kill it and replace the
3669 * other shitty functions like editUpdates and such so it's not needed
3672 public function createUpdates( $rev ) {
3673 $this->editUpdates( $rev->getText(), $rev->getComment(),
3674 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
3678 * Generate the navigation links when browsing through an article revisions
3679 * It shows the information as:
3680 * Revision as of \<date\>; view current revision
3681 * \<- Previous version | Next Version -\>
3683 * @param $oldid String: revision ID of this article revision
3685 public function setOldSubtitle( $oldid = 0 ) {
3686 global $wgLang, $wgOut, $wgUser, $wgRequest;
3688 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3692 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3694 # Cascade unhide param in links for easy deletion browsing
3695 $extraParams = array();
3696 if ( $wgRequest->getVal( 'unhide' ) ) {
3697 $extraParams['unhide'] = 1;
3700 $revision = Revision
::newFromId( $oldid );
3701 $timestamp = $revision->getTimestamp();
3703 $current = ( $oldid == $this->mLatest
);
3704 $td = $wgLang->timeanddate( $timestamp, true );
3705 $tddate = $wgLang->date( $timestamp, true );
3706 $tdtime = $wgLang->time( $timestamp, true );
3709 ?
wfMsgHtml( 'currentrevisionlink' )
3712 wfMsgHtml( 'currentrevisionlink' ),
3715 array( 'known', 'noclasses' )
3718 ?
wfMsgHtml( 'diff' )
3721 wfMsgHtml( 'diff' ),
3727 array( 'known', 'noclasses' )
3729 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3733 wfMsgHtml( 'previousrevision' ),
3736 'direction' => 'prev',
3739 array( 'known', 'noclasses' )
3741 : wfMsgHtml( 'previousrevision' );
3745 wfMsgHtml( 'diff' ),
3751 array( 'known', 'noclasses' )
3753 : wfMsgHtml( 'diff' );
3754 $nextlink = $current
3755 ?
wfMsgHtml( 'nextrevision' )
3758 wfMsgHtml( 'nextrevision' ),
3761 'direction' => 'next',
3764 array( 'known', 'noclasses' )
3766 $nextdiff = $current
3767 ?
wfMsgHtml( 'diff' )
3770 wfMsgHtml( 'diff' ),
3776 array( 'known', 'noclasses' )
3781 // User can delete revisions or view deleted revisions...
3782 $canHide = $wgUser->isAllowed( 'deleterevision' );
3783 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3784 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3785 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3788 'type' => 'revision',
3789 'target' => $this->mTitle
->getPrefixedDbkey(),
3792 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3797 # Show user links if allowed to see them. If hidden, then show them only if requested...
3798 $userlinks = Linker
::revUserTools( $revision, !$unhide );
3800 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3801 ?
'revision-info-current'
3804 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3807 array( 'parseinline', 'replaceafter' ),
3813 $revision->getUser()
3816 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3817 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3819 $wgOut->addHTML( $r );
3823 * This function is called right before saving the wikitext,
3824 * so we can do things like signatures and links-in-context.
3826 * @param $text String article contents
3827 * @param $user User object: user doing the edit, $wgUser will be used if
3829 * @param $popts ParserOptions object: parser options, default options for
3830 * the user loaded if null given
3831 * @return string article contents with altered wikitext markup (signatures
3832 * converted, {{subst:}}, templates, etc.)
3834 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3837 if ( $user === null ) {
3842 if ( $popts === null ) {
3843 $popts = ParserOptions
::newFromUser( $user );
3846 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3849 /* Caching functions */
3852 * checkLastModified returns true if it has taken care of all
3853 * output to the client that is necessary for this request.
3854 * (that is, it has sent a cached version of the page)
3856 * @return boolean true if cached version send, false otherwise
3858 protected function tryFileCache() {
3859 static $called = false;
3862 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3867 if ( $this->isFileCacheable() ) {
3868 $cache = new HTMLFileCache( $this->mTitle
);
3869 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3870 wfDebug( "Article::tryFileCache(): about to load file\n" );
3871 $cache->loadFromFileCache();
3874 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3875 ob_start( array( &$cache, 'saveToFileCache' ) );
3878 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3885 * Check if the page can be cached
3888 public function isFileCacheable() {
3891 if ( HTMLFileCache
::useFileCache() ) {
3892 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3893 // Extension may have reason to disable file caching on some pages.
3895 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3903 * Loads page_touched and returns a value indicating if it should be used
3904 * @return boolean true if not a redirect
3906 public function checkTouched() {
3907 if ( !$this->mDataLoaded
) {
3908 $this->loadPageData();
3911 return !$this->mIsRedirect
;
3915 * Get the page_touched field
3916 * @return string containing GMT timestamp
3918 public function getTouched() {
3919 if ( !$this->mDataLoaded
) {
3920 $this->loadPageData();
3923 return $this->mTouched
;
3927 * Get the page_latest field
3928 * @return integer rev_id of current revision
3930 public function getLatest() {
3931 if ( !$this->mDataLoaded
) {
3932 $this->loadPageData();
3935 return (int)$this->mLatest
;
3939 * Edit an article without doing all that other stuff
3940 * The article must already exist; link tables etc
3941 * are not updated, caches are not flushed.
3943 * @param $text String: text submitted
3944 * @param $comment String: comment submitted
3945 * @param $minor Boolean: whereas it's a minor modification
3947 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3948 wfProfileIn( __METHOD__
);
3950 $dbw = wfGetDB( DB_MASTER
);
3951 $revision = new Revision( array(
3952 'page' => $this->getId(),
3954 'comment' => $comment,
3955 'minor_edit' => $minor ?
1 : 0,
3957 $revision->insertOn( $dbw );
3958 $this->updateRevisionOn( $dbw, $revision );
3961 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3963 wfProfileOut( __METHOD__
);
3967 * The onArticle*() functions are supposed to be a kind of hooks
3968 * which should be called whenever any of the specified actions
3971 * This is a good place to put code to clear caches, for instance.
3973 * This is called on page move and undelete, as well as edit
3975 * @param $title Title object
3977 public static function onArticleCreate( $title ) {
3978 # Update existence markers on article/talk tabs...
3979 if ( $title->isTalkPage() ) {
3980 $other = $title->getSubjectPage();
3982 $other = $title->getTalkPage();
3985 $other->invalidateCache();
3986 $other->purgeSquid();
3988 $title->touchLinks();
3989 $title->purgeSquid();
3990 $title->deleteTitleProtection();
3994 * Clears caches when article is deleted
3996 * @param $title Title
3998 public static function onArticleDelete( $title ) {
3999 # Update existence markers on article/talk tabs...
4000 if ( $title->isTalkPage() ) {
4001 $other = $title->getSubjectPage();
4003 $other = $title->getTalkPage();
4006 $other->invalidateCache();
4007 $other->purgeSquid();
4009 $title->touchLinks();
4010 $title->purgeSquid();
4013 HTMLFileCache
::clearFileCache( $title );
4016 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
4017 MessageCache
::singleton()->replace( $title->getDBkey(), false );
4021 if ( $title->getNamespace() == NS_FILE
) {
4022 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4023 $update->doUpdate();
4027 if ( $title->getNamespace() == NS_USER_TALK
) {
4028 $user = User
::newFromName( $title->getText(), false );
4029 $user->setNewtalk( false );
4033 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4037 * Purge caches on page update etc
4039 * @param $title Title object
4040 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4042 public static function onArticleEdit( $title ) {
4043 global $wgDeferredUpdateList;
4045 // Invalidate caches of articles which include this page
4046 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4048 // Invalidate the caches of all pages which redirect here
4049 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4051 # Purge squid for this page only
4052 $title->purgeSquid();
4054 # Clear file cache for this page only
4055 HTMLFileCache
::clearFileCache( $title );
4061 * Overriden by ImagePage class, only present here to avoid a fatal error
4062 * Called for ?action=revert
4064 public function revert() {
4066 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4070 * Info about this page
4071 * Called for ?action=info when $wgAllowPageInfo is on.
4073 public function info() {
4074 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4076 if ( !$wgAllowPageInfo ) {
4077 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4081 $page = $this->mTitle
->getSubjectPage();
4083 $wgOut->setPagetitle( $page->getPrefixedText() );
4084 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4085 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4087 if ( !$this->mTitle
->exists() ) {
4088 $wgOut->addHTML( '<div class="noarticletext">' );
4089 $msg = $wgUser->isLoggedIn()
4091 : 'noarticletextanon';
4092 $wgOut->addWikiMsg( $msg );
4093 $wgOut->addHTML( '</div>' );
4095 $dbr = wfGetDB( DB_SLAVE
);
4097 'wl_title' => $page->getDBkey(),
4098 'wl_namespace' => $page->getNamespace() );
4099 $numwatchers = $dbr->selectField(
4105 $pageInfo = $this->pageCountInfo( $page );
4106 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4108 // @todo FIXME: unescaped messages
4109 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4110 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4113 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4116 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4119 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4122 $wgOut->addHTML( '</ul>' );
4127 * Return the total number of edits and number of unique editors
4128 * on a given page. If page does not exist, returns false.
4130 * @param $title Title object
4131 * @return mixed array or boolean false
4133 public function pageCountInfo( $title ) {
4134 $id = $title->getArticleId();
4140 $dbr = wfGetDB( DB_SLAVE
);
4141 $rev_clause = array( 'rev_page' => $id );
4142 $edits = $dbr->selectField(
4148 $authors = $dbr->selectField(
4150 'COUNT(DISTINCT rev_user_text)',
4155 return array( 'edits' => $edits, 'authors' => $authors );
4159 * Return a list of templates used by this article.
4160 * Uses the templatelinks table
4162 * @return Array of Title objects
4164 public function getUsedTemplates() {
4166 $id = $this->mTitle
->getArticleID();
4172 $dbr = wfGetDB( DB_SLAVE
);
4173 $res = $dbr->select( array( 'templatelinks' ),
4174 array( 'tl_namespace', 'tl_title' ),
4175 array( 'tl_from' => $id ),
4178 if ( $res !== false ) {
4179 foreach ( $res as $row ) {
4180 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4188 * Returns a list of hidden categories this page is a member of.
4189 * Uses the page_props and categorylinks tables.
4191 * @return Array of Title objects
4193 public function getHiddenCategories() {
4195 $id = $this->mTitle
->getArticleID();
4201 $dbr = wfGetDB( DB_SLAVE
);
4202 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4204 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4205 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4208 if ( $res !== false ) {
4209 foreach ( $res as $row ) {
4210 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4218 * Return an applicable autosummary if one exists for the given edit.
4219 * @param $oldtext String: the previous text of the page.
4220 * @param $newtext String: The submitted text of the page.
4221 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4222 * @return string An appropriate autosummary, or an empty string.
4224 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4227 # Decide what kind of autosummary is needed.
4229 # Redirect autosummaries
4230 $ot = Title
::newFromRedirect( $oldtext );
4231 $rt = Title
::newFromRedirect( $newtext );
4233 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4234 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4237 # New page autosummaries
4238 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4239 # If they're making a new article, give its text, truncated, in the summary.
4241 $truncatedtext = $wgContLang->truncate(
4242 str_replace( "\n", ' ', $newtext ),
4243 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4245 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4248 # Blanking autosummaries
4249 if ( $oldtext != '' && $newtext == '' ) {
4250 return wfMsgForContent( 'autosumm-blank' );
4251 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4252 # Removing more than 90% of the article
4254 $truncatedtext = $wgContLang->truncate(
4256 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4258 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4261 # If we reach this point, there's no applicable autosummary for our case, so our
4262 # autosummary is empty.
4267 * Add the primary page-view wikitext to the output buffer
4268 * Saves the text into the parser cache if possible.
4269 * Updates templatelinks if it is out of date.
4271 * @param $text String
4272 * @param $cache Boolean
4273 * @param $parserOptions mixed ParserOptions object, or boolean false
4275 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4278 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4279 $wgOut->addParserOutput( $this->mParserOutput
);
4283 * This does all the heavy lifting for outputWikitext, except it returns the parser
4284 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4285 * say, embedding thread pages within a discussion system (LiquidThreads)
4287 * @param $text string
4288 * @param $cache boolean
4289 * @param $parserOptions parsing options, defaults to false
4290 * @return string containing parsed output
4292 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4293 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4295 if ( !$parserOptions ) {
4296 $parserOptions = $this->getParserOptions();
4300 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4301 $parserOptions, true, true, $this->getRevIdFetched() );
4306 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4307 $this->mTitle
->getPrefixedDBkey() ) );
4310 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4311 $parserCache = ParserCache
::singleton();
4312 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4315 // Make sure file cache is not used on uncacheable content.
4316 // Output that has magic words in it can still use the parser cache
4317 // (if enabled), though it will generally expire sooner.
4318 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4319 $wgUseFileCache = false;
4322 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4324 return $this->mParserOutput
;
4328 * Get parser options suitable for rendering the primary article wikitext
4329 * @return ParserOptions object
4331 public function getParserOptions() {
4333 if ( !$this->mParserOptions
) {
4334 $this->mParserOptions
= $this->makeParserOptions( $wgUser );
4336 // Clone to allow modifications of the return value without affecting cache
4337 return clone $this->mParserOptions
;
4341 * Get parser options suitable for rendering the primary article wikitext
4343 * @return ParserOptions
4345 public function makeParserOptions( User
$user ) {
4346 $options = ParserOptions
::newFromUser( $user );
4347 $options->enableLimitReport(); // show inclusion/loop reports
4348 $options->setTidy( true ); // fix bad HTML
4353 * Updates cascading protections
4355 * @param $parserOutput ParserOutput object, or boolean false
4357 protected function doCascadeProtectionUpdates( $parserOutput ) {
4358 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4362 // templatelinks table may have become out of sync,
4363 // especially if using variable-based transclusions.
4364 // For paranoia, check if things have changed and if
4365 // so apply updates to the database. This will ensure
4366 // that cascaded protections apply as soon as the changes
4369 # Get templates from templatelinks
4370 $id = $this->mTitle
->getArticleID();
4372 $tlTemplates = array();
4374 $dbr = wfGetDB( DB_SLAVE
);
4375 $res = $dbr->select( array( 'templatelinks' ),
4376 array( 'tl_namespace', 'tl_title' ),
4377 array( 'tl_from' => $id ),
4381 foreach ( $res as $row ) {
4382 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4385 # Get templates from parser output.
4386 $poTemplates = array();
4387 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4388 foreach ( $templates as $dbk => $id ) {
4389 $poTemplates["$ns:$dbk"] = true;
4394 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4396 if ( count( $templates_diff ) > 0 ) {
4397 # Whee, link updates time.
4398 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4404 * Update all the appropriate counts in the category table, given that
4405 * we've added the categories $added and deleted the categories $deleted.
4407 * @param $added array The names of categories that were added
4408 * @param $deleted array The names of categories that were deleted
4410 public function updateCategoryCounts( $added, $deleted ) {
4411 $ns = $this->mTitle
->getNamespace();
4412 $dbw = wfGetDB( DB_MASTER
);
4414 # First make sure the rows exist. If one of the "deleted" ones didn't
4415 # exist, we might legitimately not create it, but it's simpler to just
4416 # create it and then give it a negative value, since the value is bogus
4419 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4420 $insertCats = array_merge( $added, $deleted );
4421 if ( !$insertCats ) {
4422 # Okay, nothing to do
4426 $insertRows = array();
4428 foreach ( $insertCats as $cat ) {
4429 $insertRows[] = array(
4430 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4434 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4436 $addFields = array( 'cat_pages = cat_pages + 1' );
4437 $removeFields = array( 'cat_pages = cat_pages - 1' );
4439 if ( $ns == NS_CATEGORY
) {
4440 $addFields[] = 'cat_subcats = cat_subcats + 1';
4441 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4442 } elseif ( $ns == NS_FILE
) {
4443 $addFields[] = 'cat_files = cat_files + 1';
4444 $removeFields[] = 'cat_files = cat_files - 1';
4451 array( 'cat_title' => $added ),
4460 array( 'cat_title' => $deleted ),
4467 * Lightweight method to get the parser output for a page, checking the parser cache
4468 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4469 * consider, so it's not appropriate to use there.
4471 * @since 1.16 (r52326) for LiquidThreads
4473 * @param $oldid mixed integer Revision ID or null
4474 * @return ParserOutput or false if the given revsion ID is not found
4476 public function getParserOutput( $oldid = null ) {
4477 global $wgEnableParserCache, $wgUser;
4479 // Should the parser cache be used?
4480 $useParserCache = $wgEnableParserCache &&
4481 $wgUser->getStubThreshold() == 0 &&
4485 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4487 if ( $wgUser->getStubThreshold() ) {
4488 wfIncrStats( 'pcache_miss_stub' );
4491 if ( $useParserCache ) {
4492 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4493 if ( $parserOutput !== false ) {
4494 return $parserOutput;
4498 // Cache miss; parse and output it.
4499 if ( $oldid === null ) {
4500 $text = $this->getRawText();
4502 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4503 if ( $rev === null ) {
4506 $text = $rev->getText();
4509 return $this->getOutputFromWikitext( $text, $useParserCache );
4513 * Sets the context this Article is executed in
4515 * @param $context RequestContext
4518 public function setContext( $context ) {
4519 $this->mContext
= $context;
4523 * Gets the context this Article is executed in
4525 * @return RequestContext
4528 public function getContext() {
4529 if ( $this->mContext
instanceof RequestContext
) {
4530 return $this->mContext
;
4532 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4533 return RequestContext
::getMain();
4539 class PoolWorkArticleView
extends PoolCounterWork
{
4546 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4547 parent
::__construct( 'ArticleView', $key );
4548 $this->mArticle
= $article;
4549 $this->cacheable
= $useParserCache;
4550 $this->parserOptions
= $parserOptions;
4554 return $this->mArticle
->doViewParse();
4557 function getCachedWork() {
4560 $parserCache = ParserCache
::singleton();
4561 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4563 if ( $this->mArticle
->mParserOutput
!== false ) {
4564 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4565 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4566 # Ensure that UI elements requiring revision ID have
4567 # the correct version information.
4568 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4574 function fallback() {
4575 return $this->mArticle
->tryDirtyCache();
4579 * @param $status Status
4581 function error( $status ) {
4584 $wgOut->clearHTML(); // for release() errors
4585 $wgOut->enableClientCache( false );
4586 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4588 $errortext = $status->getWikiText( false, 'view-pool-error' );
4589 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );