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;
46 * @var mixed: boolean false or URL string
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'; // !<
66 * @var ParserOptions: ParserOptions object for $wgUser articles
78 * Constructor and clear the article
79 * @param $title 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 strpos( $text, ',' ) !== false;
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
867 * @return UserArrayFromResult
869 public function getContributors() {
870 # @todo FIXME: This is expensive; cache this info somewhere.
872 $dbr = wfGetDB( DB_SLAVE
);
874 if ( $dbr->implicitGroupby() ) {
875 $realNameField = 'user_real_name';
877 $realNameField = 'FIRST(user_real_name) AS user_real_name';
880 $tables = array( 'revision', 'user' );
883 'rev_user as user_id',
884 'rev_user_text AS user_name',
886 'MAX(rev_timestamp) AS timestamp',
889 $conds = array( 'rev_page' => $this->getId() );
891 // The user who made the top revision gets credited as "this page was last edited by
892 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
893 $user = $this->getUser();
895 $conds[] = "rev_user != $user";
897 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
900 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
903 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
907 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
908 'ORDER BY' => 'timestamp DESC',
911 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
912 return new UserArrayFromResult( $res );
916 * This is the default action of the index.php entry point: just view the
917 * page of the given title.
919 public function view() {
920 global $wgUser, $wgOut, $wgRequest, $wgParser;
921 global $wgUseFileCache, $wgUseETag;
923 wfProfileIn( __METHOD__
);
925 # Get variables from query string
926 $oldid = $this->getOldID();
928 # getOldID may want us to redirect somewhere else
929 if ( $this->mRedirectUrl
) {
930 $wgOut->redirect( $this->mRedirectUrl
);
931 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
932 wfProfileOut( __METHOD__
);
937 $wgOut->setArticleFlag( true );
938 # Set page title (may be overridden by DISPLAYTITLE)
939 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
941 # If we got diff in the query, we want to see a diff page instead of the article.
942 if ( $wgRequest->getCheck( 'diff' ) ) {
943 wfDebug( __METHOD__
. ": showing diff page\n" );
944 $this->showDiffPage();
945 wfProfileOut( __METHOD__
);
950 # Allow frames by default
951 $wgOut->allowClickjacking();
953 $parserCache = ParserCache
::singleton();
955 $parserOptions = $this->getParserOptions();
956 # Render printable version, use printable version cache
957 if ( $wgOut->isPrintable() ) {
958 $parserOptions->setIsPrintable( true );
959 $parserOptions->setEditSection( false );
960 } elseif ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
961 $parserOptions->setEditSection( false );
964 # Try client and file cache
965 if ( $oldid === 0 && $this->checkTouched() ) {
967 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
970 # Is it client cached?
971 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
972 wfDebug( __METHOD__
. ": done 304\n" );
973 wfProfileOut( __METHOD__
);
977 } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
978 wfDebug( __METHOD__
. ": done file cache\n" );
979 # tell wgOut that output is taken care of
981 $this->viewUpdates();
982 wfProfileOut( __METHOD__
);
988 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
989 $parserOptions->setEditSection( false );
992 # Should the parser cache be used?
993 $useParserCache = $this->useParserCache( $oldid );
994 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
995 if ( $wgUser->getStubThreshold() ) {
996 wfIncrStats( 'pcache_miss_stub' );
999 $wasRedirected = $this->showRedirectedFromHeader();
1000 $this->showNamespaceHeader();
1002 # Iterate through the possible ways of constructing the output text.
1003 # Keep going until $outputDone is set, or we run out of things to do.
1005 $outputDone = false;
1006 $this->mParserOutput
= false;
1008 while ( !$outputDone && ++
$pass ) {
1011 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
1014 # Try the parser cache
1015 if ( $useParserCache ) {
1016 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1018 if ( $this->mParserOutput
!== false ) {
1019 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
1020 $wgOut->addParserOutput( $this->mParserOutput
);
1021 # Ensure that UI elements requiring revision ID have
1022 # the correct version information.
1023 $wgOut->setRevisionId( $this->mLatest
);
1029 $text = $this->getContent();
1030 if ( $text === false ||
$this->getID() == 0 ) {
1031 wfDebug( __METHOD__
. ": showing missing article\n" );
1032 $this->showMissingArticle();
1033 wfProfileOut( __METHOD__
);
1037 # Another whitelist check in case oldid is altering the title
1038 if ( !$this->mTitle
->userCanRead() ) {
1039 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
1040 $wgOut->loginToUse();
1043 wfProfileOut( __METHOD__
);
1047 # Are we looking at an old revision
1048 if ( $oldid && !is_null( $this->mRevision
) ) {
1049 $this->setOldSubtitle( $oldid );
1051 if ( !$this->showDeletedRevisionHeader() ) {
1052 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
1053 wfProfileOut( __METHOD__
);
1057 # If this "old" version is the current, then try the parser cache...
1058 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
1059 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1060 if ( $this->mParserOutput
) {
1061 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
1062 $wgOut->addParserOutput( $this->mParserOutput
);
1063 $wgOut->setRevisionId( $this->mLatest
);
1070 # Ensure that UI elements requiring revision ID have
1071 # the correct version information.
1072 $wgOut->setRevisionId( $this->getRevIdFetched() );
1074 # Pages containing custom CSS or JavaScript get special treatment
1075 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1076 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1077 $this->showCssOrJsPage();
1080 $rt = Title
::newFromRedirectArray( $text );
1082 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1083 # Viewing a redirect page (e.g. with parameter redirect=no)
1084 # Don't append the subtitle if this was an old revision
1085 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1086 # Parse just to get categories, displaytitle, etc.
1087 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1088 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1094 # Run the parse, protected by a pool counter
1095 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1097 $key = $parserCache->getKey( $this, $parserOptions );
1098 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1100 if ( !$poolArticleView->execute() ) {
1101 # Connection or timeout error
1102 wfProfileOut( __METHOD__
);
1108 # Should be unreachable, but just in case...
1114 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1115 if ( $this->mParserOutput
) {
1116 $titleText = $this->mParserOutput
->getTitleText();
1118 if ( strval( $titleText ) !== '' ) {
1119 $wgOut->setPageTitle( $titleText );
1123 # For the main page, overwrite the <title> element with the con-
1124 # tents of 'pagetitle-view-mainpage' instead of the default (if
1125 # that's not empty).
1126 # This message always exists because it is in the i18n files
1127 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1128 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1129 if ( !$msg->isDisabled() ) {
1130 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1134 # Now that we've filled $this->mParserOutput, we know whether
1135 # there are any __NOINDEX__ tags on the page
1136 $policy = $this->getRobotPolicy( 'view' );
1137 $wgOut->setIndexPolicy( $policy['index'] );
1138 $wgOut->setFollowPolicy( $policy['follow'] );
1140 $this->showViewFooter();
1141 $this->viewUpdates();
1142 wfProfileOut( __METHOD__
);
1146 * Show a diff page according to current request variables. For use within
1147 * Article::view() only, other callers should use the DifferenceEngine class.
1149 public function showDiffPage() {
1150 global $wgRequest, $wgUser;
1152 $diff = $wgRequest->getVal( 'diff' );
1153 $rcid = $wgRequest->getVal( 'rcid' );
1154 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1155 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1156 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1157 $oldid = $this->getOldID();
1159 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1160 // DifferenceEngine directly fetched the revision:
1161 $this->mRevIdFetched
= $de->mNewid
;
1162 $de->showDiffPage( $diffOnly );
1164 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1165 # Run view updates for current revision only
1166 $this->viewUpdates();
1171 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1172 * Article::view() only.
1174 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1177 protected function showCssOrJsPage() {
1180 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1182 // Give hooks a chance to customise the output
1183 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1184 // Wrap the whole lot in a <pre> and don't parse
1186 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1187 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1188 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1189 $wgOut->addHTML( "\n</pre>\n" );
1194 * Get the robot policy to be used for the current view
1195 * @param $action String the action= GET parameter
1196 * @return Array the policy that should be set
1197 * TODO: actions other than 'view'
1199 public function getRobotPolicy( $action ) {
1200 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1201 global $wgDefaultRobotPolicy, $wgRequest;
1203 $ns = $this->mTitle
->getNamespace();
1205 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1206 # Don't index user and user talk pages for blocked users (bug 11443)
1207 if ( !$this->mTitle
->isSubpage() ) {
1208 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1210 'index' => 'noindex',
1211 'follow' => 'nofollow'
1217 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1218 # Non-articles (special pages etc), and old revisions
1220 'index' => 'noindex',
1221 'follow' => 'nofollow'
1223 } elseif ( $wgOut->isPrintable() ) {
1224 # Discourage indexing of printable versions, but encourage following
1226 'index' => 'noindex',
1227 'follow' => 'follow'
1229 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1230 # For ?curid=x urls, disallow indexing
1232 'index' => 'noindex',
1233 'follow' => 'follow'
1237 # Otherwise, construct the policy based on the various config variables.
1238 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1240 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1241 # Honour customised robot policies for this namespace
1242 $policy = array_merge(
1244 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1247 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1248 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1249 # a final sanity check that we have really got the parser output.
1250 $policy = array_merge(
1252 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1256 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1257 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1258 $policy = array_merge(
1260 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1268 * Converts a String robot policy into an associative array, to allow
1269 * merging of several policies using array_merge().
1270 * @param $policy Mixed, returns empty array on null/false/'', transparent
1271 * to already-converted arrays, converts String.
1272 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1274 public static function formatRobotPolicy( $policy ) {
1275 if ( is_array( $policy ) ) {
1277 } elseif ( !$policy ) {
1281 $policy = explode( ',', $policy );
1282 $policy = array_map( 'trim', $policy );
1285 foreach ( $policy as $var ) {
1286 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1287 $arr['index'] = $var;
1288 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1289 $arr['follow'] = $var;
1297 * If this request is a redirect view, send "redirected from" subtitle to
1298 * $wgOut. Returns true if the header was needed, false if this is not a
1299 * redirect view. Handles both local and remote redirects.
1303 public function showRedirectedFromHeader() {
1304 global $wgOut, $wgRequest, $wgRedirectSources;
1306 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1308 if ( isset( $this->mRedirectedFrom
) ) {
1309 // This is an internally redirected page view.
1310 // We'll need a backlink to the source page for navigation.
1311 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1312 $redir = Linker
::link(
1313 $this->mRedirectedFrom
,
1316 array( 'redirect' => 'no' ),
1317 array( 'known', 'noclasses' )
1320 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1321 $wgOut->setSubtitle( $s );
1323 // Set the fragment if one was specified in the redirect
1324 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1325 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1326 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1329 // Add a <link rel="canonical"> tag
1330 $wgOut->addLink( array( 'rel' => 'canonical',
1331 'href' => $this->mTitle
->getLocalURL() )
1336 } elseif ( $rdfrom ) {
1337 // This is an externally redirected view, from some other wiki.
1338 // If it was reported from a trusted site, supply a backlink.
1339 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1340 $redir = Linker
::makeExternalLink( $rdfrom, $rdfrom );
1341 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1342 $wgOut->setSubtitle( $s );
1352 * Show a header specific to the namespace currently being viewed, like
1353 * [[MediaWiki:Talkpagetext]]. For Article::view().
1355 public function showNamespaceHeader() {
1358 if ( $this->mTitle
->isTalkPage() ) {
1359 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1360 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1366 * Show the footer section of an ordinary page view
1368 public function showViewFooter() {
1369 global $wgOut, $wgUseTrackbacks;
1371 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1372 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1373 $wgOut->addWikiMsg( 'anontalkpagetext' );
1376 # If we have been passed an &rcid= parameter, we want to give the user a
1377 # chance to mark this new article as patrolled.
1378 $this->showPatrolFooter();
1381 if ( $wgUseTrackbacks ) {
1382 $this->addTrackbacks();
1385 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1390 * If patrol is possible, output a patrol UI box. This is called from the
1391 * footer section of ordinary page views. If patrol is not possible or not
1392 * desired, does nothing.
1394 public function showPatrolFooter() {
1395 global $wgOut, $wgRequest, $wgUser;
1397 $rcid = $wgRequest->getVal( 'rcid' );
1399 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1403 $token = $wgUser->editToken( $rcid );
1404 $wgOut->preventClickjacking();
1407 "<div class='patrollink'>" .
1409 'markaspatrolledlink',
1412 wfMsgHtml( 'markaspatrolledtext' ),
1415 'action' => 'markpatrolled',
1419 array( 'known', 'noclasses' )
1427 * Show the error text for a missing article. For articles in the MediaWiki
1428 * namespace, show the default message text. To be called from Article::view().
1430 public function showMissingArticle() {
1431 global $wgOut, $wgRequest, $wgUser;
1433 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1434 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1435 $parts = explode( '/', $this->mTitle
->getText() );
1436 $rootPart = $parts[0];
1437 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1438 $ip = User
::isIP( $rootPart );
1440 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1441 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1442 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1443 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1444 LogEventsList
::showLogExtract(
1447 $user->getUserPage()->getPrefixedText(),
1451 'showIfEmpty' => false,
1453 'blocked-notice-logextract',
1454 $user->getName() # Support GENDER in notice
1461 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1463 # Show delete and move logs
1464 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1466 'conds' => array( "log_action != 'revision'" ),
1467 'showIfEmpty' => false,
1468 'msgKey' => array( 'moveddeleted-notice' ) )
1471 # Show error message
1472 $oldid = $this->getOldID();
1474 $text = wfMsgNoTrans( 'missing-article',
1475 $this->mTitle
->getPrefixedText(),
1476 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1477 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1478 // Use the default message text
1479 $text = $this->mTitle
->getDefaultMessageText();
1481 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1482 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1483 $errors = array_merge( $createErrors, $editErrors );
1485 if ( !count( $errors ) ) {
1486 $text = wfMsgNoTrans( 'noarticletext' );
1488 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1491 $text = "<div class='noarticletext'>\n$text\n</div>";
1493 if ( !$this->hasViewableContent() ) {
1494 // If there's no backing content, send a 404 Not Found
1495 // for better machine handling of broken links.
1496 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1499 $wgOut->addWikiText( $text );
1503 * If the revision requested for view is deleted, check permissions.
1504 * Send either an error message or a warning header to $wgOut.
1506 * @return boolean true if the view is allowed, false if not.
1508 public function showDeletedRevisionHeader() {
1509 global $wgOut, $wgRequest;
1511 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1516 // If the user is not allowed to see it...
1517 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1518 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1519 'rev-deleted-text-permission' );
1522 // If the user needs to confirm that they want to see it...
1523 } elseif ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1524 # Give explanation and add a link to view the revision...
1525 $oldid = intval( $this->getOldID() );
1526 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1527 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1528 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1529 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1530 array( $msg, $link ) );
1533 // We are allowed to see...
1535 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1536 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1537 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1544 * Should the parser cache be used?
1548 public function useParserCache( $oldid ) {
1549 global $wgUser, $wgEnableParserCache;
1551 return $wgEnableParserCache
1552 && $wgUser->getStubThreshold() == 0
1555 && !$this->mTitle
->isCssOrJsPage()
1556 && !$this->mTitle
->isCssJsSubpage();
1560 * Execute the uncached parse for action=view
1562 public function doViewParse() {
1565 $oldid = $this->getOldID();
1566 $parserOptions = $this->getParserOptions();
1568 # Render printable version, use printable version cache
1569 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1571 # Don't show section-edit links on old revisions... this way lies madness.
1572 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1573 $parserOptions->setEditSection( false );
1576 $useParserCache = $this->useParserCache( $oldid );
1577 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1583 * Try to fetch an expired entry from the parser cache. If it is present,
1584 * output it and return true. If it is not present, output nothing and
1585 * return false. This is used as a callback function for
1586 * PoolCounter::executeProtected().
1590 public function tryDirtyCache() {
1592 $parserCache = ParserCache
::singleton();
1593 $options = $this->getParserOptions();
1595 if ( $wgOut->isPrintable() ) {
1596 $options->setIsPrintable( true );
1597 $options->setEditSection( false );
1600 $output = $parserCache->getDirty( $this, $options );
1603 wfDebug( __METHOD__
. ": sending dirty output\n" );
1604 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1605 $wgOut->setSquidMaxage( 0 );
1606 $this->mParserOutput
= $output;
1607 $wgOut->addParserOutput( $output );
1608 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1612 wfDebugLog( 'dirty', "dirty missing\n" );
1613 wfDebug( __METHOD__
. ": no dirty cache\n" );
1622 * @param $target Title|Array of destination(s) to redirect
1623 * @param $appendSubtitle Boolean [optional]
1624 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1625 * @return string containing HMTL with redirect link
1627 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1628 global $wgOut, $wgContLang, $wgStylePath;
1630 if ( !is_array( $target ) ) {
1631 $target = array( $target );
1634 $imageDir = $wgContLang->getDir();
1636 if ( $appendSubtitle ) {
1637 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1640 // the loop prepends the arrow image before the link, so the first case needs to be outside
1641 $title = array_shift( $target );
1643 if ( $forceKnown ) {
1644 $link = Linker
::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1646 $link = Linker
::link( $title, htmlspecialchars( $title->getFullText() ) );
1649 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1650 $alt = $wgContLang->isRTL() ?
'←' : '→';
1651 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1652 foreach ( $target as $rt ) {
1653 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1654 if ( $forceKnown ) {
1655 $link .= Linker
::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1657 $link .= Linker
::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1661 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1662 return '<div class="redirectMsg">' .
1663 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1664 '<span class="redirectText">' . $link . '</span></div>';
1668 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1670 public function addTrackbacks() {
1673 $dbr = wfGetDB( DB_SLAVE
);
1674 $tbs = $dbr->select( 'trackbacks',
1675 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1676 array( 'tb_page' => $this->getID() )
1679 if ( !$dbr->numRows( $tbs ) ) {
1683 $wgOut->preventClickjacking();
1686 foreach ( $tbs as $o ) {
1689 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1690 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1691 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1692 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1696 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1704 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1708 * Removes trackback record for current article from trackbacks table
1709 * @deprecated since 1.19
1711 public function deletetrackback() {
1712 return Action
::factory( 'deletetrackback', $this )->show();
1716 * Handle action=render
1719 public function render() {
1722 $wgOut->setArticleBodyOnly( true );
1727 * Handle action=purge
1729 public function purge() {
1730 return Action
::factory( 'purge', $this )->show();
1734 * Perform the actions of a page purging
1736 public function doPurge() {
1739 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1743 // Invalidate the cache
1744 $this->mTitle
->invalidateCache();
1747 if ( $wgUseSquid ) {
1748 // Commit the transaction before the purge is sent
1749 $dbw = wfGetDB( DB_MASTER
);
1753 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1754 $update->doUpdate();
1757 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1758 if ( $this->getID() == 0 ) {
1761 $text = $this->getRawText();
1764 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1769 * Mark this particular edit/page as patrolled
1770 * @deprecated since 1.19
1772 public function markpatrolled() {
1773 Action
::factory( 'markpatrolled', $this )->show();
1777 * User-interface handler for the "watch" action.
1778 * Requires Request to pass a token as of 1.19.
1779 * @deprecated since 1.18
1781 public function watch() {
1782 Action
::factory( 'watch', $this )->show();
1786 * Add this page to $wgUser's watchlist
1788 * This is safe to be called multiple times
1790 * @return bool true on successful watch operation
1791 * @deprecated since 1.18
1793 public function doWatch() {
1795 return WatchAction
::doWatch( $this->mTitle
, $wgUser );
1799 * User interface handler for the "unwatch" action.
1800 * Requires Request to pass a token as of 1.19.
1801 * @deprecated since 1.18
1803 public function unwatch() {
1804 Action
::factory( 'unwatch', $this )->show();
1808 * Stop watching a page
1809 * @return bool true on successful unwatch
1810 * @deprecated since 1.18
1812 public function doUnwatch() {
1814 return WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1818 * action=protect handler
1820 public function protect() {
1821 $form = new ProtectionForm( $this );
1826 * action=unprotect handler (alias)
1828 public function unprotect() {
1833 * Info about this page
1834 * Called for ?action=info when $wgAllowPageInfo is on.
1836 public function info() {
1837 Action
::factory( 'info', $this )->show();
1841 * Insert a new empty page record for this article.
1842 * This *must* be followed up by creating a revision
1843 * and running $this->updateRevisionOn( ... );
1844 * or else the record will be left in a funky state.
1845 * Best if all done inside a transaction.
1847 * @param $dbw DatabaseBase
1848 * @return int The newly created page_id key, or false if the title already existed
1851 public function insertOn( $dbw ) {
1852 wfProfileIn( __METHOD__
);
1854 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1855 $dbw->insert( 'page', array(
1856 'page_id' => $page_id,
1857 'page_namespace' => $this->mTitle
->getNamespace(),
1858 'page_title' => $this->mTitle
->getDBkey(),
1859 'page_counter' => 0,
1860 'page_restrictions' => '',
1861 'page_is_redirect' => 0, # Will set this shortly...
1863 'page_random' => wfRandom(),
1864 'page_touched' => $dbw->timestamp(),
1865 'page_latest' => 0, # Fill this in shortly...
1866 'page_len' => 0, # Fill this in shortly...
1867 ), __METHOD__
, 'IGNORE' );
1869 $affected = $dbw->affectedRows();
1872 $newid = $dbw->insertId();
1873 $this->mTitle
->resetArticleID( $newid );
1875 wfProfileOut( __METHOD__
);
1877 return $affected ?
$newid : false;
1881 * Update the page record to point to a newly saved revision.
1883 * @param $dbw DatabaseBase: object
1884 * @param $revision Revision: For ID number, and text used to set
1885 length and redirect status fields
1886 * @param $lastRevision Integer: if given, will not overwrite the page field
1887 * when different from the currently set value.
1888 * Giving 0 indicates the new page flag should be set
1890 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1891 * removing rows in redirect table.
1892 * @return bool true on success, false on failure
1895 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1896 wfProfileIn( __METHOD__
);
1898 $text = $revision->getText();
1899 $rt = Title
::newFromRedirectRecurse( $text );
1901 $conditions = array( 'page_id' => $this->getId() );
1903 if ( !is_null( $lastRevision ) ) {
1904 # An extra check against threads stepping on each other
1905 $conditions['page_latest'] = $lastRevision;
1908 $dbw->update( 'page',
1910 'page_latest' => $revision->getId(),
1911 'page_touched' => $dbw->timestamp(),
1912 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1913 'page_is_redirect' => $rt !== null ?
1 : 0,
1914 'page_len' => strlen( $text ),
1919 $result = $dbw->affectedRows() != 0;
1921 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1924 wfProfileOut( __METHOD__
);
1929 * Add row to the redirect table if this is a redirect, remove otherwise.
1931 * @param $dbw DatabaseBase
1932 * @param $redirectTitle Title object pointing to the redirect target,
1933 * or NULL if this is not a redirect
1934 * @param $lastRevIsRedirect If given, will optimize adding and
1935 * removing rows in redirect table.
1936 * @return bool true on success, false on failure
1939 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1940 // Always update redirects (target link might have changed)
1941 // Update/Insert if we don't know if the last revision was a redirect or not
1942 // Delete if changing from redirect to non-redirect
1943 $isRedirect = !is_null( $redirectTitle );
1945 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1949 wfProfileIn( __METHOD__
);
1950 if ( $isRedirect ) {
1951 $this->insertRedirectEntry( $redirectTitle );
1953 // This is not a redirect, remove row from redirect table
1954 $where = array( 'rd_from' => $this->getId() );
1955 $dbw->delete( 'redirect', $where, __METHOD__
);
1958 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1959 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1961 wfProfileOut( __METHOD__
);
1963 return ( $dbw->affectedRows() != 0 );
1967 * If the given revision is newer than the currently set page_latest,
1968 * update the page record. Otherwise, do nothing.
1970 * @param $dbw Database object
1971 * @param $revision Revision object
1974 public function updateIfNewerOn( &$dbw, $revision ) {
1975 wfProfileIn( __METHOD__
);
1977 $row = $dbw->selectRow(
1978 array( 'revision', 'page' ),
1979 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1981 'page_id' => $this->getId(),
1982 'page_latest=rev_id' ),
1986 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1987 wfProfileOut( __METHOD__
);
1990 $prev = $row->rev_id
;
1991 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1993 # No or missing previous revision; mark the page as new
1995 $lastRevIsRedirect = null;
1998 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
2000 wfProfileOut( __METHOD__
);
2005 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
2006 * @param $text String: new text of the section
2007 * @param $summary String: new section's subject, only if $section is 'new'
2008 * @param $edittime String: revision timestamp or null to use the current revision
2009 * @return string Complete article text, or null if error
2011 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
2012 wfProfileIn( __METHOD__
);
2014 if ( strval( $section ) == '' ) {
2015 // Whole-page edit; let the whole text through
2017 if ( is_null( $edittime ) ) {
2018 $rev = Revision
::newFromTitle( $this->mTitle
);
2020 $dbw = wfGetDB( DB_MASTER
);
2021 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
2025 wfDebug( "Article::replaceSection asked for bogus section (page: " .
2026 $this->getId() . "; section: $section; edittime: $edittime)\n" );
2027 wfProfileOut( __METHOD__
);
2031 $oldtext = $rev->getText();
2033 if ( $section == 'new' ) {
2034 # Inserting a new section
2035 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
2036 $text = strlen( trim( $oldtext ) ) > 0
2037 ?
"{$oldtext}\n\n{$subject}{$text}"
2038 : "{$subject}{$text}";
2040 # Replacing an existing section; roll out the big guns
2043 $text = $wgParser->replaceSection( $oldtext, $section, $text );
2047 wfProfileOut( __METHOD__
);
2052 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
2054 * @return Int updated $flags
2056 function checkFlags( $flags ) {
2057 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
2058 if ( $this->mTitle
->getArticleID() ) {
2059 $flags |
= EDIT_UPDATE
;
2071 * Change an existing article or create a new article. Updates RC and all necessary caches,
2072 * optionally via the deferred update array.
2074 * $wgUser must be set before calling this function.
2076 * @param $text String: new text
2077 * @param $summary String: edit summary
2078 * @param $flags Integer bitfield:
2080 * Article is known or assumed to be non-existent, create a new one
2082 * Article is known or assumed to be pre-existing, update it
2084 * Mark this edit minor, if the user is allowed to do so
2086 * Do not log the change in recentchanges
2088 * Mark the edit a "bot" edit regardless of user rights
2089 * EDIT_DEFER_UPDATES
2090 * Defer some of the updates until the end of index.php
2092 * Fill in blank summaries with generated text where possible
2094 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2095 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2096 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2097 * edit-already-exists error will be returned. These two conditions are also possible with
2098 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2100 * @param $baseRevId the revision ID this edit was based off, if any
2101 * @param $user User (optional), $wgUser will be used if not passed
2103 * @return Status object. Possible errors:
2104 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2105 * edit-gone-missing: In update mode, but the article didn't exist
2106 * edit-conflict: In update mode, the article changed unexpectedly
2107 * edit-no-change: Warning that the text was the same as before
2108 * edit-already-exists: In creation mode, but the article already exists
2110 * Extensions may define additional errors.
2112 * $return->value will contain an associative array with members as follows:
2113 * new: Boolean indicating if the function attempted to create a new article
2114 * revision: The revision object for the inserted revision, or null
2116 * Compatibility note: this function previously returned a boolean value indicating success/failure
2118 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2119 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2121 # Low-level sanity check
2122 if ( $this->mTitle
->getText() === '' ) {
2123 throw new MWException( 'Something is trying to edit an article with an empty title' );
2126 wfProfileIn( __METHOD__
);
2128 $user = is_null( $user ) ?
$wgUser : $user;
2129 $status = Status
::newGood( array() );
2131 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2132 $this->loadPageData();
2134 $flags = $this->checkFlags( $flags );
2136 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2137 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2139 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2141 if ( $status->isOK() ) {
2142 $status->fatal( 'edit-hook-aborted' );
2145 wfProfileOut( __METHOD__
);
2149 # Silently ignore EDIT_MINOR if not allowed
2150 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2151 $bot = $flags & EDIT_FORCE_BOT
;
2153 $oldtext = $this->getRawText(); // current revision
2154 $oldsize = strlen( $oldtext );
2156 # Provide autosummaries if one is not provided and autosummaries are enabled.
2157 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2158 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2161 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2162 $text = $editInfo->pst
;
2163 $newsize = strlen( $text );
2165 $dbw = wfGetDB( DB_MASTER
);
2166 $now = wfTimestampNow();
2167 $this->mTimestamp
= $now;
2169 if ( $flags & EDIT_UPDATE
) {
2170 # Update article, but only if changed.
2171 $status->value
['new'] = false;
2173 # Make sure the revision is either completely inserted or not inserted at all
2174 if ( !$wgDBtransactions ) {
2175 $userAbort = ignore_user_abort( true );
2178 $changed = ( strcmp( $text, $oldtext ) != 0 );
2181 if ( !$this->mLatest
) {
2182 # Article gone missing
2183 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2184 $status->fatal( 'edit-gone-missing' );
2186 wfProfileOut( __METHOD__
);
2190 $revision = new Revision( array(
2191 'page' => $this->getId(),
2192 'comment' => $summary,
2193 'minor_edit' => $isminor,
2195 'parent_id' => $this->mLatest
,
2196 'user' => $user->getId(),
2197 'user_text' => $user->getName(),
2202 $revisionId = $revision->insertOn( $dbw );
2206 # Note that we use $this->mLatest instead of fetching a value from the master DB
2207 # during the course of this function. This makes sure that EditPage can detect
2208 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2209 # before this function is called. A previous function used a separate query, this
2210 # creates a window where concurrent edits can cause an ignored edit conflict.
2211 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2214 /* Belated edit conflict! Run away!! */
2215 $status->fatal( 'edit-conflict' );
2217 # Delete the invalid revision if the DB is not transactional
2218 if ( !$wgDBtransactions ) {
2219 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2225 global $wgUseRCPatrol;
2226 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2227 # Update recentchanges
2228 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2229 # Mark as patrolled if the user can do so
2230 $patrolled = $wgUseRCPatrol && !count(
2231 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2232 # Add RC row to the DB
2233 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2234 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2235 $revisionId, $patrolled
2238 # Log auto-patrolled edits
2240 PatrolLog
::record( $rc, true );
2243 $user->incEditCount();
2247 $status->warning( 'edit-no-change' );
2249 // Keep the same revision ID, but do some updates on it
2250 $revisionId = $this->getLatest();
2251 // Update page_touched, this is usually implicit in the page update
2252 // Other cache updates are done in onArticleEdit()
2253 $this->mTitle
->invalidateCache();
2256 if ( !$wgDBtransactions ) {
2257 ignore_user_abort( $userAbort );
2260 // Now that ignore_user_abort is restored, we can respond to fatal errors
2261 if ( !$status->isOK() ) {
2262 wfProfileOut( __METHOD__
);
2266 # Invalidate cache of this article and all pages using this article
2267 # as a template. Partly deferred.
2268 Article
::onArticleEdit( $this->mTitle
);
2269 # Update links tables, site stats, etc.
2270 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2272 # Create new article
2273 $status->value
['new'] = true;
2277 # Add the page record; stake our claim on this title!
2278 # This will return false if the article already exists
2279 $newid = $this->insertOn( $dbw );
2281 if ( $newid === false ) {
2283 $status->fatal( 'edit-already-exists' );
2285 wfProfileOut( __METHOD__
);
2289 # Save the revision text...
2290 $revision = new Revision( array(
2292 'comment' => $summary,
2293 'minor_edit' => $isminor,
2295 'user' => $user->getId(),
2296 'user_text' => $user->getName(),
2299 $revisionId = $revision->insertOn( $dbw );
2301 $this->mTitle
->resetArticleID( $newid );
2302 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
2304 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2306 # Update the page record with revision data
2307 $this->updateRevisionOn( $dbw, $revision, 0 );
2309 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2311 # Update recentchanges
2312 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2313 global $wgUseRCPatrol, $wgUseNPPatrol;
2315 # Mark as patrolled if the user can do so
2316 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2317 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2318 # Add RC row to the DB
2319 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2320 '', strlen( $text ), $revisionId, $patrolled );
2322 # Log auto-patrolled edits
2324 PatrolLog
::record( $rc, true );
2327 $user->incEditCount();
2330 # Update links, etc.
2331 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user, true );
2334 Article
::onArticleCreate( $this->mTitle
);
2336 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2337 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2340 # Do updates right now unless deferral was requested
2341 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2345 // Return the new revision (or null) to the caller
2346 $status->value
['revision'] = $revision;
2348 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2349 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2351 wfProfileOut( __METHOD__
);
2356 * Output a redirect back to the article.
2357 * This is typically used after an edit.
2359 * @deprecated in 1.19; call $wgOut->redirect() directly
2360 * @param $noRedir Boolean: add redirect=no
2361 * @param $sectionAnchor String: section to redirect to, including "#"
2362 * @param $extraQuery String: extra query params
2364 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2365 wfDeprecated( __METHOD__
);
2369 $query = 'redirect=no';
2371 $query .= "&$extraQuery";
2373 $query = $extraQuery;
2376 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2380 * Update the article's restriction field, and leave a log entry.
2382 * @param $limit Array: set of restriction keys
2383 * @param $reason String
2384 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2385 * @param $expiry Array: per restriction type expiration
2386 * @return bool true on success
2388 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2389 global $wgUser, $wgContLang;
2391 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2393 $id = $this->mTitle
->getArticleID();
2396 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2400 if ( wfReadOnly() ) {
2401 wfDebug( "updateRestrictions failed: read-only\n" );
2405 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2406 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2414 // Take this opportunity to purge out expired restrictions
2415 Title
::purgeExpiredRestrictions();
2417 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2418 # we expect a single selection, but the schema allows otherwise.
2420 $updated = Article
::flattenRestrictions( $limit );
2423 foreach ( $restrictionTypes as $action ) {
2424 if ( isset( $expiry[$action] ) ) {
2425 # Get current restrictions on $action
2426 $aLimits = $this->mTitle
->getRestrictions( $action );
2427 $current[$action] = implode( '', $aLimits );
2428 # Are any actual restrictions being dealt with here?
2429 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2431 # If something changed, we need to log it. Checking $aRChanged
2432 # assures that "unprotecting" a page that is not protected does
2433 # not log just because the expiry was "changed".
2434 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2440 $current = Article
::flattenRestrictions( $current );
2442 $changed = ( $changed ||
$current != $updated );
2443 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2444 $protect = ( $updated != '' );
2446 # If nothing's changed, do nothing
2448 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2449 $dbw = wfGetDB( DB_MASTER
);
2451 # Prepare a null revision to be added to the history
2452 $modified = $current != '' && $protect;
2455 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2457 $comment_type = 'unprotectedarticle';
2460 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2462 # Only restrictions with the 'protect' right can cascade...
2463 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2464 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2466 # The schema allows multiple restrictions
2467 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2471 $cascade_description = '';
2474 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2478 $comment .= ": $reason";
2481 $editComment = $comment;
2482 $encodedExpiry = array();
2483 $protect_description = '';
2484 foreach ( $limit as $action => $restrictions ) {
2485 if ( !isset( $expiry[$action] ) )
2486 $expiry[$action] = $dbw->getInfinity();
2488 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2489 if ( $restrictions != '' ) {
2490 $protect_description .= "[$action=$restrictions] (";
2491 if ( $encodedExpiry[$action] != 'infinity' ) {
2492 $protect_description .= wfMsgForContent( 'protect-expiring',
2493 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2494 $wgContLang->date( $expiry[$action], false, false ) ,
2495 $wgContLang->time( $expiry[$action], false, false ) );
2497 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2500 $protect_description .= ') ';
2503 $protect_description = trim( $protect_description );
2505 if ( $protect_description && $protect ) {
2506 $editComment .= " ($protect_description)";
2510 $editComment .= "$cascade_description";
2513 # Update restrictions table
2514 foreach ( $limit as $action => $restrictions ) {
2515 if ( $restrictions != '' ) {
2516 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2517 array( 'pr_page' => $id,
2518 'pr_type' => $action,
2519 'pr_level' => $restrictions,
2520 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2521 'pr_expiry' => $encodedExpiry[$action]
2526 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2527 'pr_type' => $action ), __METHOD__
);
2531 # Insert a null revision
2532 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2533 $nullRevId = $nullRevision->insertOn( $dbw );
2535 $latest = $this->getLatest();
2536 # Update page record
2537 $dbw->update( 'page',
2539 'page_touched' => $dbw->timestamp(),
2540 'page_restrictions' => '',
2541 'page_latest' => $nullRevId
2542 ), array( /* WHERE */
2544 ), 'Article::protect'
2547 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2548 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2550 # Update the protection log
2551 $log = new LogPage( 'protect' );
2553 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2554 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2556 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2559 } # End "changed" check
2565 * Take an array of page restrictions and flatten it to a string
2566 * suitable for insertion into the page_restrictions field.
2567 * @param $limit Array
2570 protected static function flattenRestrictions( $limit ) {
2571 if ( !is_array( $limit ) ) {
2572 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2578 foreach ( $limit as $action => $restrictions ) {
2579 if ( $restrictions != '' ) {
2580 $bits[] = "$action=$restrictions";
2584 return implode( ':', $bits );
2588 * Auto-generates a deletion reason
2590 * @param &$hasHistory Boolean: whether the page has a history
2591 * @return mixed String containing deletion reason or empty string, or boolean false
2592 * if no revision occurred
2594 public function generateReason( &$hasHistory ) {
2597 $dbw = wfGetDB( DB_MASTER
);
2598 // Get the last revision
2599 $rev = Revision
::newFromTitle( $this->mTitle
);
2601 if ( is_null( $rev ) ) {
2605 // Get the article's contents
2606 $contents = $rev->getText();
2609 // If the page is blank, use the text from the previous revision,
2610 // which can only be blank if there's a move/import/protect dummy revision involved
2611 if ( $contents == '' ) {
2612 $prev = $rev->getPrevious();
2615 $contents = $prev->getText();
2620 // Find out if there was only one contributor
2621 // Only scan the last 20 revisions
2622 $res = $dbw->select( 'revision', 'rev_user_text',
2623 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2625 array( 'LIMIT' => 20 )
2628 if ( $res === false ) {
2629 // This page has no revisions, which is very weird
2633 $hasHistory = ( $res->numRows() > 1 );
2634 $row = $dbw->fetchObject( $res );
2636 if ( $row ) { // $row is false if the only contributor is hidden
2637 $onlyAuthor = $row->rev_user_text
;
2638 // Try to find a second contributor
2639 foreach ( $res as $row ) {
2640 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2641 $onlyAuthor = false;
2646 $onlyAuthor = false;
2649 // Generate the summary with a '$1' placeholder
2651 // The current revision is blank and the one before is also
2652 // blank. It's just not our lucky day
2653 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2655 if ( $onlyAuthor ) {
2656 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2658 $reason = wfMsgForContent( 'excontent', '$1' );
2662 if ( $reason == '-' ) {
2663 // Allow these UI messages to be blanked out cleanly
2667 // Replace newlines with spaces to prevent uglyness
2668 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2669 // Calculate the maximum amount of chars to get
2670 // Max content length = max comment length - length of the comment (excl. $1)
2671 $maxLength = 255 - ( strlen( $reason ) - 2 );
2672 $contents = $wgContLang->truncate( $contents, $maxLength );
2673 // Remove possible unfinished links
2674 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2675 // Now replace the '$1' placeholder
2676 $reason = str_replace( '$1', $contents, $reason );
2683 * UI entry point for page deletion
2685 public function delete() {
2686 global $wgOut, $wgRequest;
2688 $confirm = $wgRequest->wasPosted() &&
2689 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2691 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2692 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2694 $reason = $this->DeleteReasonList
;
2696 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2697 // Entry from drop down menu + additional comment
2698 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2699 } elseif ( $reason == 'other' ) {
2700 $reason = $this->DeleteReason
;
2703 # Flag to hide all contents of the archived revisions
2704 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2706 # This code desperately needs to be totally rewritten
2708 # Read-only check...
2709 if ( wfReadOnly() ) {
2710 $wgOut->readOnlyPage();
2716 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2718 if ( count( $permission_errors ) > 0 ) {
2719 $wgOut->showPermissionsErrorPage( $permission_errors );
2724 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2726 # Better double-check that it hasn't been deleted yet!
2727 $dbw = wfGetDB( DB_MASTER
);
2728 $conds = $this->mTitle
->pageCond();
2729 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2730 if ( $latest === false ) {
2731 $wgOut->showFatalError(
2734 array( 'class' => 'error mw-error-cannotdelete' ),
2735 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2738 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2739 LogEventsList
::showLogExtract(
2742 $this->mTitle
->getPrefixedText()
2748 # Hack for big sites
2749 $bigHistory = $this->isBigDeletion();
2750 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2751 global $wgLang, $wgDeleteRevisionsLimit;
2753 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2754 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2760 $this->doDelete( $reason, $suppress );
2762 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2764 } elseif ( $this->mTitle
->userIsWatching() ) {
2771 // Generate deletion reason
2772 $hasHistory = false;
2774 $reason = $this->generateReason( $hasHistory );
2777 // If the page has a history, insert a warning
2778 if ( $hasHistory && !$confirm ) {
2781 $revisions = $this->estimateRevisionCount();
2782 // @todo FIXME: i18n issue/patchwork message
2783 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2784 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2785 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->mTitle
,
2786 wfMsgHtml( 'history' ),
2787 array( 'rel' => 'archives' ),
2788 array( 'action' => 'history' ) ) .
2792 if ( $bigHistory ) {
2793 global $wgDeleteRevisionsLimit;
2794 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2795 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2799 return $this->confirmDelete( $reason );
2803 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2805 public function isBigDeletion() {
2806 global $wgDeleteRevisionsLimit;
2808 if ( $wgDeleteRevisionsLimit ) {
2809 $revCount = $this->estimateRevisionCount();
2811 return $revCount > $wgDeleteRevisionsLimit;
2818 * @return int approximate revision count
2820 public function estimateRevisionCount() {
2821 $dbr = wfGetDB( DB_SLAVE
);
2823 // For an exact count...
2824 // return $dbr->selectField( 'revision', 'COUNT(*)',
2825 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2826 return $dbr->estimateRowCount( 'revision', '*',
2827 array( 'rev_page' => $this->getId() ), __METHOD__
);
2831 * Get the last N authors
2832 * @param $num Integer: number of revisions to get
2833 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2834 * @return array Array of authors, duplicates not removed
2836 public function getLastNAuthors( $num, $revLatest = 0 ) {
2837 wfProfileIn( __METHOD__
);
2838 // First try the slave
2839 // If that doesn't have the latest revision, try the master
2841 $db = wfGetDB( DB_SLAVE
);
2844 $res = $db->select( array( 'page', 'revision' ),
2845 array( 'rev_id', 'rev_user_text' ),
2847 'page_namespace' => $this->mTitle
->getNamespace(),
2848 'page_title' => $this->mTitle
->getDBkey(),
2849 'rev_page = page_id'
2852 'ORDER BY' => 'rev_timestamp DESC',
2858 wfProfileOut( __METHOD__
);
2862 $row = $db->fetchObject( $res );
2864 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2865 $db = wfGetDB( DB_MASTER
);
2870 } while ( $continue );
2872 $authors = array( $row->rev_user_text
);
2874 foreach ( $res as $row ) {
2875 $authors[] = $row->rev_user_text
;
2878 wfProfileOut( __METHOD__
);
2883 * Output deletion confirmation dialog
2884 * @todo FIXME: Move to another file?
2885 * @param $reason String: prefilled reason
2887 public function confirmDelete( $reason ) {
2890 wfDebug( "Article::confirmDelete\n" );
2892 $deleteBackLink = Linker
::linkKnown( $this->mTitle
);
2893 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2894 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2895 $wgOut->addWikiMsg( 'confirmdeletetext' );
2897 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2899 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2900 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2902 <td class='mw-input'><strong>" .
2903 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2904 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2910 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2912 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2913 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2914 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2915 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2916 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2917 "<tr id=\"wpDeleteReasonListRow\">
2918 <td class='mw-label'>" .
2919 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2921 <td class='mw-input'>" .
2922 Xml
::listDropDown( 'wpDeleteReasonList',
2923 wfMsgForContent( 'deletereason-dropdown' ),
2924 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2927 <tr id=\"wpDeleteReasonRow\">
2928 <td class='mw-label'>" .
2929 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2931 <td class='mw-input'>" .
2932 Html
::input( 'wpReason', $reason, 'text', array(
2934 'maxlength' => '255',
2942 # Disallow watching if user is not logged in
2943 if ( $wgOut->getUser()->isLoggedIn() ) {
2947 <td class='mw-input'>" .
2948 Xml
::checkLabel( wfMsg( 'watchthis' ),
2949 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2958 <td class='mw-submit'>" .
2959 Xml
::submitButton( wfMsg( 'deletepage' ),
2960 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2963 Xml
::closeElement( 'table' ) .
2964 Xml
::closeElement( 'fieldset' ) .
2965 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2966 Xml
::closeElement( 'form' );
2968 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2969 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2970 $link = Linker
::link(
2972 wfMsgHtml( 'delete-edit-reasonlist' ),
2974 array( 'action' => 'edit' )
2976 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2979 $wgOut->addHTML( $form );
2980 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2981 LogEventsList
::showLogExtract( $wgOut, 'delete',
2982 $this->mTitle
->getPrefixedText()
2987 * Perform a deletion and output success or failure messages
2989 public function doDelete( $reason, $suppress = false ) {
2992 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2995 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
2996 $deleted = $this->mTitle
->getPrefixedText();
2998 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2999 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3001 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3003 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3004 $wgOut->returnToMain( false );
3006 if ( $error == '' ) {
3007 $wgOut->showFatalError(
3010 array( 'class' => 'error mw-error-cannotdelete' ),
3011 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3015 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3017 LogEventsList
::showLogExtract(
3020 $this->mTitle
->getPrefixedText()
3023 $wgOut->showFatalError( $error );
3029 * Back-end article deletion
3030 * Deletes the article with database consistency, writes logs, purges caches
3032 * @param $reason string delete reason for deletion log
3033 * @param suppress bitfield
3034 * Revision::DELETED_TEXT
3035 * Revision::DELETED_COMMENT
3036 * Revision::DELETED_USER
3037 * Revision::DELETED_RESTRICTED
3038 * @param $id int article ID
3039 * @param $commit boolean defaults to true, triggers transaction end
3040 * @return boolean true if successful
3042 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3043 global $wgDeferredUpdateList, $wgUseTrackbacks;
3046 wfDebug( __METHOD__
. "\n" );
3048 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3051 $dbw = wfGetDB( DB_MASTER
);
3052 $t = $this->mTitle
->getDBkey();
3053 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3055 if ( $t === '' ||
$id == 0 ) {
3059 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
3060 array_push( $wgDeferredUpdateList, $u );
3062 // Bitfields to further suppress the content
3065 // This should be 15...
3066 $bitfield |
= Revision
::DELETED_TEXT
;
3067 $bitfield |
= Revision
::DELETED_COMMENT
;
3068 $bitfield |
= Revision
::DELETED_USER
;
3069 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3071 $bitfield = 'rev_deleted';
3075 // For now, shunt the revision data into the archive table.
3076 // Text is *not* removed from the text table; bulk storage
3077 // is left intact to avoid breaking block-compression or
3078 // immutable storage schemes.
3080 // For backwards compatibility, note that some older archive
3081 // table entries will have ar_text and ar_flags fields still.
3083 // In the future, we may keep revisions and mark them with
3084 // the rev_deleted field, which is reserved for this purpose.
3085 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3087 'ar_namespace' => 'page_namespace',
3088 'ar_title' => 'page_title',
3089 'ar_comment' => 'rev_comment',
3090 'ar_user' => 'rev_user',
3091 'ar_user_text' => 'rev_user_text',
3092 'ar_timestamp' => 'rev_timestamp',
3093 'ar_minor_edit' => 'rev_minor_edit',
3094 'ar_rev_id' => 'rev_id',
3095 'ar_text_id' => 'rev_text_id',
3096 'ar_text' => '\'\'', // Be explicit to appease
3097 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3098 'ar_len' => 'rev_len',
3099 'ar_page_id' => 'page_id',
3100 'ar_deleted' => $bitfield
3103 'page_id = rev_page'
3107 # Delete restrictions for it
3108 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3110 # Now that it's safely backed up, delete it
3111 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3112 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3119 # Fix category table counts
3121 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3123 foreach ( $res as $row ) {
3124 $cats [] = $row->cl_to
;
3127 $this->updateCategoryCounts( array(), $cats );
3129 # If using cascading deletes, we can skip some explicit deletes
3130 if ( !$dbw->cascadingDeletes() ) {
3131 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3133 if ( $wgUseTrackbacks )
3134 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3136 # Delete outgoing links
3137 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3138 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3139 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3140 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3141 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3142 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3143 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3144 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3147 # If using cleanup triggers, we can skip some manual deletes
3148 if ( !$dbw->cleanupTriggers() ) {
3149 # Clean up recentchanges entries...
3150 $dbw->delete( 'recentchanges',
3151 array( 'rc_type != ' . RC_LOG
,
3152 'rc_namespace' => $this->mTitle
->getNamespace(),
3153 'rc_title' => $this->mTitle
->getDBkey() ),
3155 $dbw->delete( 'recentchanges',
3156 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3161 Article
::onArticleDelete( $this->mTitle
);
3163 # Clear the cached article id so the interface doesn't act like we exist
3164 $this->mTitle
->resetArticleID( 0 );
3166 # Log the deletion, if the page was suppressed, log it at Oversight instead
3167 $logtype = $suppress ?
'suppress' : 'delete';
3168 $log = new LogPage( $logtype );
3170 # Make sure logging got through
3171 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3177 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3182 * Roll back the most recent consecutive set of edits to a page
3183 * from the same user; fails if there are no eligible edits to
3184 * roll back to, e.g. user is the sole contributor. This function
3185 * performs permissions checks on $wgUser, then calls commitRollback()
3186 * to do the dirty work
3188 * @param $fromP String: Name of the user whose edits to rollback.
3189 * @param $summary String: Custom summary. Set to default summary if empty.
3190 * @param $token String: Rollback token.
3191 * @param $bot Boolean: If true, mark all reverted edits as bot.
3193 * @param $resultDetails Array: contains result-specific array of additional values
3194 * 'alreadyrolled' : 'current' (rev)
3195 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3197 * @return array of errors, each error formatted as
3198 * array(messagekey, param1, param2, ...).
3199 * On success, the array is empty. This array can also be passed to
3200 * OutputPage::showPermissionsErrorPage().
3202 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3205 $resultDetails = null;
3208 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3209 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3210 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3212 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3213 $errors[] = array( 'sessionfailure' );
3216 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3217 $errors[] = array( 'actionthrottledtext' );
3220 # If there were errors, bail out now
3221 if ( !empty( $errors ) ) {
3225 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3229 * Backend implementation of doRollback(), please refer there for parameter
3230 * and return value documentation
3232 * NOTE: This function does NOT check ANY permissions, it just commits the
3233 * rollback to the DB Therefore, you should only call this function direct-
3234 * ly if you want to use custom permissions checks. If you don't, use
3235 * doRollback() instead.
3237 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3238 global $wgUseRCPatrol, $wgUser, $wgLang;
3240 $dbw = wfGetDB( DB_MASTER
);
3242 if ( wfReadOnly() ) {
3243 return array( array( 'readonlytext' ) );
3246 # Get the last editor
3247 $current = Revision
::newFromTitle( $this->mTitle
);
3248 if ( is_null( $current ) ) {
3249 # Something wrong... no page?
3250 return array( array( 'notanarticle' ) );
3253 $from = str_replace( '_', ' ', $fromP );
3254 # User name given should match up with the top revision.
3255 # If the user was deleted then $from should be empty.
3256 if ( $from != $current->getUserText() ) {
3257 $resultDetails = array( 'current' => $current );
3258 return array( array( 'alreadyrolled',
3259 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3260 htmlspecialchars( $fromP ),
3261 htmlspecialchars( $current->getUserText() )
3265 # Get the last edit not by this guy...
3266 # Note: these may not be public values
3267 $user = intval( $current->getRawUser() );
3268 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3269 $s = $dbw->selectRow( 'revision',
3270 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3271 array( 'rev_page' => $current->getPage(),
3272 "rev_user != {$user} OR rev_user_text != {$user_text}"
3274 array( 'USE INDEX' => 'page_timestamp',
3275 'ORDER BY' => 'rev_timestamp DESC' )
3277 if ( $s === false ) {
3278 # No one else ever edited this page
3279 return array( array( 'cantrollback' ) );
3280 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3281 # Only admins can see this text
3282 return array( array( 'notvisiblerev' ) );
3286 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3287 # Mark all reverted edits as bot
3291 if ( $wgUseRCPatrol ) {
3292 # Mark all reverted edits as patrolled
3293 $set['rc_patrolled'] = 1;
3296 if ( count( $set ) ) {
3297 $dbw->update( 'recentchanges', $set,
3299 'rc_cur_id' => $current->getPage(),
3300 'rc_user_text' => $current->getUserText(),
3301 "rc_timestamp > '{$s->rev_timestamp}'",
3306 # Generate the edit summary if necessary
3307 $target = Revision
::newFromId( $s->rev_id
);
3308 if ( empty( $summary ) ) {
3309 if ( $from == '' ) { // no public user name
3310 $summary = wfMsgForContent( 'revertpage-nouser' );
3312 $summary = wfMsgForContent( 'revertpage' );
3316 # Allow the custom summary to use the same args as the default message
3318 $target->getUserText(), $from, $s->rev_id
,
3319 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3320 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3322 $summary = wfMsgReplaceArgs( $summary, $args );
3325 $flags = EDIT_UPDATE
;
3327 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3328 $flags |
= EDIT_MINOR
;
3331 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3332 $flags |
= EDIT_FORCE_BOT
;
3335 # Actually store the edit
3336 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3337 if ( !empty( $status->value
['revision'] ) ) {
3338 $revId = $status->value
['revision']->getId();
3343 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3345 $resultDetails = array(
3346 'summary' => $summary,
3347 'current' => $current,
3348 'target' => $target,
3356 * User interface for rollback operations
3358 public function rollback() {
3359 global $wgUser, $wgOut, $wgRequest;
3363 $result = $this->doRollback(
3364 $wgRequest->getVal( 'from' ),
3365 $wgRequest->getText( 'summary' ),
3366 $wgRequest->getVal( 'token' ),
3367 $wgRequest->getBool( 'bot' ),
3371 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3372 $wgOut->rateLimited();
3376 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3377 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3378 $errArray = $result[0];
3379 $errMsg = array_shift( $errArray );
3380 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3382 if ( isset( $details['current'] ) ) {
3383 $current = $details['current'];
3385 if ( $current->getComment() != '' ) {
3386 $wgOut->addWikiMsgArray( 'editcomment', array(
3387 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3394 # Display permissions errors before read-only message -- there's no
3395 # point in misleading the user into thinking the inability to rollback
3396 # is only temporary.
3397 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3398 # array_diff is completely broken for arrays of arrays, sigh.
3399 # Remove any 'readonlytext' error manually.
3401 foreach ( $result as $error ) {
3402 if ( $error != array( 'readonlytext' ) ) {
3406 $wgOut->showPermissionsErrorPage( $out );
3411 if ( $result == array( array( 'readonlytext' ) ) ) {
3412 $wgOut->readOnlyPage();
3417 $current = $details['current'];
3418 $target = $details['target'];
3419 $newId = $details['newid'];
3420 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3421 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3423 if ( $current->getUserText() === '' ) {
3424 $old = wfMsg( 'rev-deleted-user' );
3426 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
3427 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
3430 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
3431 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
3432 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3433 $wgOut->returnToMain( false, $this->mTitle
);
3435 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3436 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3437 $de->showDiff( '', '' );
3442 * Do standard deferred updates after page view
3444 public function viewUpdates() {
3445 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3446 if ( wfReadOnly() ) {
3450 # Don't update page view counters on views from bot users (bug 14044)
3451 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3452 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3453 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3456 # Update newtalk / watchlist notification status
3457 $wgUser->clearNotification( $this->mTitle
);
3461 * Prepare text which is about to be saved.
3462 * Returns a stdclass with source, pst and output members
3464 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3465 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3467 return $this->mPreparedEdit
;
3472 if( $user === null ) {
3476 $popts = ParserOptions
::newFromUser( $user );
3477 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3479 $edit = (object)array();
3480 $edit->revid
= $revid;
3481 $edit->newText
= $text;
3482 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3483 $edit->popts
= $this->getParserOptions( true );
3484 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3485 $edit->oldText
= $this->getRawText();
3487 $this->mPreparedEdit
= $edit;
3493 * Do standard deferred updates after page edit.
3494 * Update links tables, site stats, search index and message cache.
3495 * Purges pages that include this page if the text was changed here.
3496 * Every 100th edit, prune the recent changes table.
3499 * @param $text String: New text of the article
3500 * @param $summary String: Edit summary
3501 * @param $minoredit Boolean: Minor edit
3502 * @param $timestamp_of_pagechange String timestamp associated with the page change
3503 * @param $newid Integer: rev_id value of the new revision
3504 * @param $changed Boolean: Whether or not the content actually changed
3505 * @param $user User object: User doing the edit
3506 * @param $created Boolean: Whether the edit created the page
3508 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
3509 $changed = true, User
$user = null, $created = false )
3511 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3513 wfProfileIn( __METHOD__
);
3516 # Be careful not to double-PST: $text is usually already PST-ed once
3517 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3518 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3519 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3521 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3522 $editInfo = $this->mPreparedEdit
;
3525 # Save it to the parser cache
3526 if ( $wgEnableParserCache ) {
3527 $parserCache = ParserCache
::singleton();
3528 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3531 # Update the links tables
3532 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3535 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3537 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3538 if ( 0 == mt_rand( 0, 99 ) ) {
3539 // Flush old entries from the `recentchanges` table; we do this on
3540 // random requests so as to avoid an increase in writes for no good reason
3543 $dbw = wfGetDB( DB_MASTER
);
3544 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3547 array( "rc_timestamp < '$cutoff'" ),
3553 $id = $this->getID();
3554 $title = $this->mTitle
->getPrefixedDBkey();
3555 $shortTitle = $this->mTitle
->getDBkey();
3558 wfProfileOut( __METHOD__
);
3565 } elseif ( $created ) {
3566 $good = (int)$this->isCountable( $editInfo );
3569 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
3573 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
3574 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
3576 # If this is another user's talk page, update newtalk
3577 # Don't do this if $changed = false otherwise some idiot can null-edit a
3578 # load of user talk pages and piss people off, nor if it's a minor edit
3579 # by a properly-flagged bot.
3580 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3581 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3583 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3584 $other = User
::newFromName( $shortTitle, false );
3586 wfDebug( __METHOD__
. ": invalid username\n" );
3587 } elseif ( User
::isIP( $shortTitle ) ) {
3588 // An anonymous user
3589 $other->setNewtalk( true );
3590 } elseif ( $other->isLoggedIn() ) {
3591 $other->setNewtalk( true );
3593 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3598 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3599 MessageCache
::singleton()->replace( $shortTitle, $text );
3602 wfProfileOut( __METHOD__
);
3606 * Perform article updates on a special page creation.
3608 * @param $rev Revision object
3610 * @todo This is a shitty interface function. Kill it and replace the
3611 * other shitty functions like editUpdates and such so it's not needed
3614 public function createUpdates( $rev ) {
3615 $this->editUpdates( $rev->getText(), $rev->getComment(),
3616 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
3620 * Generate the navigation links when browsing through an article revisions
3621 * It shows the information as:
3622 * Revision as of \<date\>; view current revision
3623 * \<- Previous version | Next Version -\>
3625 * @param $oldid String: revision ID of this article revision
3627 public function setOldSubtitle( $oldid = 0 ) {
3628 global $wgLang, $wgOut, $wgUser, $wgRequest;
3630 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3634 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3636 # Cascade unhide param in links for easy deletion browsing
3637 $extraParams = array();
3638 if ( $wgRequest->getVal( 'unhide' ) ) {
3639 $extraParams['unhide'] = 1;
3642 $revision = Revision
::newFromId( $oldid );
3643 $timestamp = $revision->getTimestamp();
3645 $current = ( $oldid == $this->mLatest
);
3646 $td = $wgLang->timeanddate( $timestamp, true );
3647 $tddate = $wgLang->date( $timestamp, true );
3648 $tdtime = $wgLang->time( $timestamp, true );
3651 ?
wfMsgHtml( 'currentrevisionlink' )
3654 wfMsgHtml( 'currentrevisionlink' ),
3657 array( 'known', 'noclasses' )
3660 ?
wfMsgHtml( 'diff' )
3663 wfMsgHtml( 'diff' ),
3669 array( 'known', 'noclasses' )
3671 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3675 wfMsgHtml( 'previousrevision' ),
3678 'direction' => 'prev',
3681 array( 'known', 'noclasses' )
3683 : wfMsgHtml( 'previousrevision' );
3687 wfMsgHtml( 'diff' ),
3693 array( 'known', 'noclasses' )
3695 : wfMsgHtml( 'diff' );
3696 $nextlink = $current
3697 ?
wfMsgHtml( 'nextrevision' )
3700 wfMsgHtml( 'nextrevision' ),
3703 'direction' => 'next',
3706 array( 'known', 'noclasses' )
3708 $nextdiff = $current
3709 ?
wfMsgHtml( 'diff' )
3712 wfMsgHtml( 'diff' ),
3718 array( 'known', 'noclasses' )
3723 // User can delete revisions or view deleted revisions...
3724 $canHide = $wgUser->isAllowed( 'deleterevision' );
3725 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3726 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3727 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3730 'type' => 'revision',
3731 'target' => $this->mTitle
->getPrefixedDbkey(),
3734 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3739 # Show user links if allowed to see them. If hidden, then show them only if requested...
3740 $userlinks = Linker
::revUserTools( $revision, !$unhide );
3742 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3743 ?
'revision-info-current'
3746 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3749 array( 'parseinline', 'replaceafter' ),
3755 $revision->getUser()
3758 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3759 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3761 $wgOut->addHTML( $r );
3765 * This function is called right before saving the wikitext,
3766 * so we can do things like signatures and links-in-context.
3768 * @param $text String article contents
3769 * @param $user User object: user doing the edit, $wgUser will be used if
3771 * @param $popts ParserOptions object: parser options, default options for
3772 * the user loaded if null given
3773 * @return string article contents with altered wikitext markup (signatures
3774 * converted, {{subst:}}, templates, etc.)
3776 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3779 if ( $user === null ) {
3784 if ( $popts === null ) {
3785 $popts = ParserOptions
::newFromUser( $user );
3788 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3791 /* Caching functions */
3794 * checkLastModified returns true if it has taken care of all
3795 * output to the client that is necessary for this request.
3796 * (that is, it has sent a cached version of the page)
3798 * @return boolean true if cached version send, false otherwise
3800 protected function tryFileCache() {
3801 static $called = false;
3804 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3809 if ( $this->isFileCacheable() ) {
3810 $cache = new HTMLFileCache( $this->mTitle
);
3811 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3812 wfDebug( "Article::tryFileCache(): about to load file\n" );
3813 $cache->loadFromFileCache();
3816 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3817 ob_start( array( &$cache, 'saveToFileCache' ) );
3820 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3827 * Check if the page can be cached
3830 public function isFileCacheable() {
3833 if ( HTMLFileCache
::useFileCache() ) {
3834 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3835 // Extension may have reason to disable file caching on some pages.
3837 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3845 * Loads page_touched and returns a value indicating if it should be used
3846 * @return boolean true if not a redirect
3848 public function checkTouched() {
3849 if ( !$this->mDataLoaded
) {
3850 $this->loadPageData();
3853 return !$this->mIsRedirect
;
3857 * Get the page_touched field
3858 * @return string containing GMT timestamp
3860 public function getTouched() {
3861 if ( !$this->mDataLoaded
) {
3862 $this->loadPageData();
3865 return $this->mTouched
;
3869 * Get the page_latest field
3870 * @return integer rev_id of current revision
3872 public function getLatest() {
3873 if ( !$this->mDataLoaded
) {
3874 $this->loadPageData();
3877 return (int)$this->mLatest
;
3881 * Edit an article without doing all that other stuff
3882 * The article must already exist; link tables etc
3883 * are not updated, caches are not flushed.
3885 * @param $text String: text submitted
3886 * @param $comment String: comment submitted
3887 * @param $minor Boolean: whereas it's a minor modification
3889 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3890 wfProfileIn( __METHOD__
);
3892 $dbw = wfGetDB( DB_MASTER
);
3893 $revision = new Revision( array(
3894 'page' => $this->getId(),
3896 'comment' => $comment,
3897 'minor_edit' => $minor ?
1 : 0,
3899 $revision->insertOn( $dbw );
3900 $this->updateRevisionOn( $dbw, $revision );
3903 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3905 wfProfileOut( __METHOD__
);
3909 * The onArticle*() functions are supposed to be a kind of hooks
3910 * which should be called whenever any of the specified actions
3913 * This is a good place to put code to clear caches, for instance.
3915 * This is called on page move and undelete, as well as edit
3917 * @param $title Title object
3919 public static function onArticleCreate( $title ) {
3920 # Update existence markers on article/talk tabs...
3921 if ( $title->isTalkPage() ) {
3922 $other = $title->getSubjectPage();
3924 $other = $title->getTalkPage();
3927 $other->invalidateCache();
3928 $other->purgeSquid();
3930 $title->touchLinks();
3931 $title->purgeSquid();
3932 $title->deleteTitleProtection();
3936 * Clears caches when article is deleted
3938 * @param $title Title
3940 public static function onArticleDelete( $title ) {
3941 # Update existence markers on article/talk tabs...
3942 if ( $title->isTalkPage() ) {
3943 $other = $title->getSubjectPage();
3945 $other = $title->getTalkPage();
3948 $other->invalidateCache();
3949 $other->purgeSquid();
3951 $title->touchLinks();
3952 $title->purgeSquid();
3955 HTMLFileCache
::clearFileCache( $title );
3958 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3959 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3963 if ( $title->getNamespace() == NS_FILE
) {
3964 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3965 $update->doUpdate();
3969 if ( $title->getNamespace() == NS_USER_TALK
) {
3970 $user = User
::newFromName( $title->getText(), false );
3971 $user->setNewtalk( false );
3975 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3979 * Purge caches on page update etc
3981 * @param $title Title object
3982 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3984 public static function onArticleEdit( $title ) {
3985 global $wgDeferredUpdateList;
3987 // Invalidate caches of articles which include this page
3988 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3990 // Invalidate the caches of all pages which redirect here
3991 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3993 # Purge squid for this page only
3994 $title->purgeSquid();
3996 # Clear file cache for this page only
3997 HTMLFileCache
::clearFileCache( $title );
4003 * Overriden by ImagePage class, only present here to avoid a fatal error
4004 * Called for ?action=revert
4006 public function revert() {
4008 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4012 * Return a list of templates used by this article.
4013 * Uses the templatelinks table
4015 * @return Array of Title objects
4017 public function getUsedTemplates() {
4019 $id = $this->mTitle
->getArticleID();
4025 $dbr = wfGetDB( DB_SLAVE
);
4026 $res = $dbr->select( array( 'templatelinks' ),
4027 array( 'tl_namespace', 'tl_title' ),
4028 array( 'tl_from' => $id ),
4031 if ( $res !== false ) {
4032 foreach ( $res as $row ) {
4033 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4041 * Returns a list of hidden categories this page is a member of.
4042 * Uses the page_props and categorylinks tables.
4044 * @return Array of Title objects
4046 public function getHiddenCategories() {
4048 $id = $this->mTitle
->getArticleID();
4054 $dbr = wfGetDB( DB_SLAVE
);
4055 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4057 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4058 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4061 if ( $res !== false ) {
4062 foreach ( $res as $row ) {
4063 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4071 * Return an applicable autosummary if one exists for the given edit.
4072 * @param $oldtext String: the previous text of the page.
4073 * @param $newtext String: The submitted text of the page.
4074 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4075 * @return string An appropriate autosummary, or an empty string.
4077 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4080 # Decide what kind of autosummary is needed.
4082 # Redirect autosummaries
4083 $ot = Title
::newFromRedirect( $oldtext );
4084 $rt = Title
::newFromRedirect( $newtext );
4086 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4087 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4090 # New page autosummaries
4091 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4092 # If they're making a new article, give its text, truncated, in the summary.
4094 $truncatedtext = $wgContLang->truncate(
4095 str_replace( "\n", ' ', $newtext ),
4096 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4098 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4101 # Blanking autosummaries
4102 if ( $oldtext != '' && $newtext == '' ) {
4103 return wfMsgForContent( 'autosumm-blank' );
4104 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4105 # Removing more than 90% of the article
4107 $truncatedtext = $wgContLang->truncate(
4109 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4111 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4114 # If we reach this point, there's no applicable autosummary for our case, so our
4115 # autosummary is empty.
4120 * Add the primary page-view wikitext to the output buffer
4121 * Saves the text into the parser cache if possible.
4122 * Updates templatelinks if it is out of date.
4124 * @param $text String
4125 * @param $cache Boolean
4126 * @param $parserOptions mixed ParserOptions object, or boolean false
4128 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4131 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4132 $wgOut->addParserOutput( $this->mParserOutput
);
4136 * This does all the heavy lifting for outputWikitext, except it returns the parser
4137 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4138 * say, embedding thread pages within a discussion system (LiquidThreads)
4140 * @param $text string
4141 * @param $cache boolean
4142 * @param $parserOptions parsing options, defaults to false
4143 * @return string containing parsed output
4145 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4146 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4148 if ( !$parserOptions ) {
4149 $parserOptions = $this->getParserOptions();
4153 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4154 $parserOptions, true, true, $this->getRevIdFetched() );
4159 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4160 $this->mTitle
->getPrefixedDBkey() ) );
4163 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4164 $parserCache = ParserCache
::singleton();
4165 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4168 // Make sure file cache is not used on uncacheable content.
4169 // Output that has magic words in it can still use the parser cache
4170 // (if enabled), though it will generally expire sooner.
4171 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4172 $wgUseFileCache = false;
4175 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4177 return $this->mParserOutput
;
4181 * Get parser options suitable for rendering the primary article wikitext
4182 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
4183 * @return mixed ParserOptions object or boolean false
4185 public function getParserOptions( $canonical = false ) {
4186 global $wgUser, $wgLanguageCode;
4188 if ( !$this->mParserOptions ||
$canonical ) {
4189 $user = !$canonical ?
$wgUser : new User
;
4190 $parserOptions = new ParserOptions( $user );
4191 $parserOptions->setTidy( true );
4192 $parserOptions->enableLimitReport();
4195 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
4196 return $parserOptions;
4198 $this->mParserOptions
= $parserOptions;
4200 // Clone to allow modifications of the return value without affecting cache
4201 return clone $this->mParserOptions
;
4205 * Get parser options suitable for rendering the primary article wikitext
4207 * @return ParserOptions
4209 public function makeParserOptions( User
$user ) {
4210 $options = ParserOptions
::newFromUser( $user );
4211 $options->enableLimitReport(); // show inclusion/loop reports
4212 $options->setTidy( true ); // fix bad HTML
4217 * Updates cascading protections
4219 * @param $parserOutput ParserOutput object, or boolean false
4221 protected function doCascadeProtectionUpdates( $parserOutput ) {
4222 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4226 // templatelinks table may have become out of sync,
4227 // especially if using variable-based transclusions.
4228 // For paranoia, check if things have changed and if
4229 // so apply updates to the database. This will ensure
4230 // that cascaded protections apply as soon as the changes
4233 # Get templates from templatelinks
4234 $id = $this->mTitle
->getArticleID();
4236 $tlTemplates = array();
4238 $dbr = wfGetDB( DB_SLAVE
);
4239 $res = $dbr->select( array( 'templatelinks' ),
4240 array( 'tl_namespace', 'tl_title' ),
4241 array( 'tl_from' => $id ),
4245 foreach ( $res as $row ) {
4246 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4249 # Get templates from parser output.
4250 $poTemplates = array();
4251 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4252 foreach ( $templates as $dbk => $id ) {
4253 $poTemplates["$ns:$dbk"] = true;
4258 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4260 if ( count( $templates_diff ) > 0 ) {
4261 # Whee, link updates time.
4262 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4268 * Update all the appropriate counts in the category table, given that
4269 * we've added the categories $added and deleted the categories $deleted.
4271 * @param $added array The names of categories that were added
4272 * @param $deleted array The names of categories that were deleted
4274 public function updateCategoryCounts( $added, $deleted ) {
4275 $ns = $this->mTitle
->getNamespace();
4276 $dbw = wfGetDB( DB_MASTER
);
4278 # First make sure the rows exist. If one of the "deleted" ones didn't
4279 # exist, we might legitimately not create it, but it's simpler to just
4280 # create it and then give it a negative value, since the value is bogus
4283 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4284 $insertCats = array_merge( $added, $deleted );
4285 if ( !$insertCats ) {
4286 # Okay, nothing to do
4290 $insertRows = array();
4292 foreach ( $insertCats as $cat ) {
4293 $insertRows[] = array(
4294 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4298 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4300 $addFields = array( 'cat_pages = cat_pages + 1' );
4301 $removeFields = array( 'cat_pages = cat_pages - 1' );
4303 if ( $ns == NS_CATEGORY
) {
4304 $addFields[] = 'cat_subcats = cat_subcats + 1';
4305 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4306 } elseif ( $ns == NS_FILE
) {
4307 $addFields[] = 'cat_files = cat_files + 1';
4308 $removeFields[] = 'cat_files = cat_files - 1';
4315 array( 'cat_title' => $added ),
4324 array( 'cat_title' => $deleted ),
4331 * Lightweight method to get the parser output for a page, checking the parser cache
4332 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4333 * consider, so it's not appropriate to use there.
4335 * @since 1.16 (r52326) for LiquidThreads
4337 * @param $oldid mixed integer Revision ID or null
4338 * @return ParserOutput or false if the given revsion ID is not found
4340 public function getParserOutput( $oldid = null ) {
4341 global $wgEnableParserCache, $wgUser;
4343 // Should the parser cache be used?
4344 $useParserCache = $wgEnableParserCache &&
4345 $wgUser->getStubThreshold() == 0 &&
4349 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4351 if ( $wgUser->getStubThreshold() ) {
4352 wfIncrStats( 'pcache_miss_stub' );
4355 if ( $useParserCache ) {
4356 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4357 if ( $parserOutput !== false ) {
4358 return $parserOutput;
4362 // Cache miss; parse and output it.
4363 if ( $oldid === null ) {
4364 $text = $this->getRawText();
4366 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4367 if ( $rev === null ) {
4370 $text = $rev->getText();
4373 return $this->getOutputFromWikitext( $text, $useParserCache );
4377 * Sets the context this Article is executed in
4379 * @param $context RequestContext
4382 public function setContext( $context ) {
4383 $this->mContext
= $context;
4387 * Gets the context this Article is executed in
4389 * @return RequestContext
4392 public function getContext() {
4393 if ( $this->mContext
instanceof RequestContext
) {
4394 return $this->mContext
;
4396 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4397 return RequestContext
::getMain();
4403 class PoolWorkArticleView
extends PoolCounterWork
{
4410 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4411 parent
::__construct( 'ArticleView', $key );
4412 $this->mArticle
= $article;
4413 $this->cacheable
= $useParserCache;
4414 $this->parserOptions
= $parserOptions;
4418 return $this->mArticle
->doViewParse();
4421 function getCachedWork() {
4424 $parserCache = ParserCache
::singleton();
4425 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4427 if ( $this->mArticle
->mParserOutput
!== false ) {
4428 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4429 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4430 # Ensure that UI elements requiring revision ID have
4431 # the correct version information.
4432 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4438 function fallback() {
4439 return $this->mArticle
->tryDirtyCache();
4443 * @param $status Status
4445 function error( $status ) {
4448 $wgOut->clearHTML(); // for release() errors
4449 $wgOut->enableClientCache( false );
4450 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4452 $errortext = $status->getWikiText( false, 'view-pool-error' );
4453 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );