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 $cur_text = $this->getRawText();
367 if ( $cur_text === false ) {
368 return false; // no page
370 $undo_text = $undo->getText();
371 $undoafter_text = $undoafter->getText();
373 if ( $cur_text == $undo_text ) {
374 # No use doing a merge if it's just a straight revert.
375 return $undoafter_text;
380 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
388 * @return int The oldid of the article that is to be shown, 0 for the
391 public function getOldID() {
392 if ( is_null( $this->mOldId
) ) {
393 $this->mOldId
= $this->getOldIDFromRequest();
396 return $this->mOldId
;
400 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
402 * @return int The old id for the request
404 public function getOldIDFromRequest() {
407 $this->mRedirectUrl
= false;
409 $oldid = $wgRequest->getVal( 'oldid' );
411 if ( isset( $oldid ) ) {
412 $oldid = intval( $oldid );
413 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
414 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
418 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
420 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
421 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
436 * Load the revision (including text) into this object
438 function loadContent() {
439 if ( $this->mContentLoaded
) {
443 wfProfileIn( __METHOD__
);
445 $this->fetchContent( $this->getOldID() );
447 wfProfileOut( __METHOD__
);
451 * Return the list of revision fields that should be selected to create
454 public static function selectFields() {
471 * Fetch a page record with the given conditions
472 * @param $dbr DatabaseBase object
473 * @param $conditions Array
474 * @return mixed Database result resource, or false on failure
476 protected function pageData( $dbr, $conditions ) {
477 $fields = self
::selectFields();
479 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
481 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
483 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
489 * Fetch a page record matching the Title object's namespace and title
490 * using a sanitized title string
492 * @param $dbr DatabaseBase object
493 * @param $title Title object
494 * @return mixed Database result resource, or false on failure
496 protected function pageDataFromTitle( $dbr, $title ) {
497 return $this->pageData( $dbr, array(
498 'page_namespace' => $title->getNamespace(),
499 'page_title' => $title->getDBkey() ) );
503 * Fetch a page record matching the requested ID
505 * @param $dbr DatabaseBase
507 * @return mixed Database result resource, or false on failure
509 protected function pageDataFromId( $dbr, $id ) {
510 return $this->pageData( $dbr, array( 'page_id' => $id ) );
514 * Set the general counter, title etc data loaded from
517 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
519 public function loadPageData( $data = 'fromdb' ) {
520 if ( $data === 'fromdb' ) {
521 $dbr = wfGetDB( DB_SLAVE
);
522 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
525 $lc = LinkCache
::singleton();
528 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
530 $this->mTitle
->mArticleID
= intval( $data->page_id
);
532 # Old-fashioned restrictions
533 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
535 $this->mCounter
= intval( $data->page_counter
);
536 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
537 $this->mIsRedirect
= intval( $data->page_is_redirect
);
538 $this->mLatest
= intval( $data->page_latest
);
540 $lc->addBadLinkObj( $this->mTitle
);
541 $this->mTitle
->mArticleID
= 0;
544 $this->mDataLoaded
= true;
548 * Get text of an article from database
549 * Does *NOT* follow redirects.
551 * @param $oldid Int: 0 for whatever the latest revision is
552 * @return mixed string containing article contents, or false if null
554 function fetchContent( $oldid = 0 ) {
555 if ( $this->mContentLoaded
) {
556 return $this->mContent
;
559 # Pre-fill content with error message so that if something
560 # fails we'll have something telling us what we intended.
561 $t = $this->mTitle
->getPrefixedText();
562 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
563 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
566 $revision = Revision
::newFromId( $oldid );
567 if ( $revision === null ) {
568 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
572 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
573 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
576 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
580 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
581 $this->loadPageData( $data );
584 if ( !$this->mDataLoaded
) {
585 $this->loadPageData();
588 if ( $this->mLatest
=== false ) {
589 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
593 $revision = Revision
::newFromId( $this->mLatest
);
594 if ( $revision === null ) {
595 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
600 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
601 // We should instead work with the Revision object when we need it...
602 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
604 if ( $revision->getId() == $this->mLatest
) {
605 $this->setLastEdit( $revision );
608 $this->mRevIdFetched
= $revision->getId();
609 $this->mContentLoaded
= true;
610 $this->mRevision
=& $revision;
612 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
614 return $this->mContent
;
619 * @deprecated since 1.18
621 public function forUpdate() {
622 wfDeprecated( __METHOD__
);
626 * @return int Page ID
628 public function getID() {
629 return $this->mTitle
->getArticleID();
633 * @return bool Whether or not the page exists in the database
635 public function exists() {
636 return $this->getId() > 0;
640 * Check if this page is something we're going to be showing
641 * some sort of sensible content for. If we return false, page
642 * views (plain action=view) will return an HTTP 404 response,
643 * so spiders and robots can know they're following a bad link.
647 public function hasViewableContent() {
648 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
652 * @return int The view count for the page
654 public function getCount() {
655 if ( -1 == $this->mCounter
) {
656 $id = $this->getID();
661 $dbr = wfGetDB( DB_SLAVE
);
662 $this->mCounter
= $dbr->selectField( 'page',
664 array( 'page_id' => $id ),
670 return $this->mCounter
;
674 * Determine whether a page would be suitable for being counted as an
675 * article in the site_stats table based on the title & its content
677 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
678 * if false, the current database state will be used
681 public function isCountable( $editInfo = false ) {
682 global $wgArticleCountMethod;
684 if ( !$this->mTitle
->isContentPage() ) {
688 $text = $editInfo ?
$editInfo->pst
: false;
690 if ( $this->isRedirect( $text ) ) {
694 switch ( $wgArticleCountMethod ) {
698 if ( $text === false ) {
699 $text = $this->getRawText();
701 return strpos( $text, ',' ) !== false;
704 // ParserOutput::getLinks() is a 2D array of page links, so
705 // to be really correct we would need to recurse in the array
706 // but the main array should only have items in it if there are
708 return (bool)count( $editInfo->output
->getLinks() );
710 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
711 array( 'pl_from' => $this->getId() ), __METHOD__
);
717 * Tests if the article text represents a redirect
719 * @param $text mixed string containing article contents, or boolean
722 public function isRedirect( $text = false ) {
723 if ( $text === false ) {
724 if ( !$this->mDataLoaded
) {
725 $this->loadPageData();
728 return (bool)$this->mIsRedirect
;
730 return Title
::newFromRedirect( $text ) !== null;
735 * Returns true if the currently-referenced revision is the current edit
736 * to this page (and it exists).
739 public function isCurrent() {
740 # If no oldid, this is the current version.
741 if ( $this->getOldID() == 0 ) {
745 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
749 * Loads everything except the text
750 * This isn't necessary for all uses, so it's only done if needed.
752 protected function loadLastEdit() {
753 if ( $this->mLastRevision
!== null ) {
754 return; // already loaded
757 # New or non-existent articles have no user information
758 $id = $this->getID();
763 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
765 $this->setLastEdit( $revision );
770 * Set the latest revision
772 protected function setLastEdit( Revision
$revision ) {
773 $this->mLastRevision
= $revision;
774 $this->mTimestamp
= $revision->getTimestamp();
778 * @return string GMT timestamp of last article revision
780 public function getTimestamp() {
781 // Check if the field has been filled by ParserCache::get()
782 if ( !$this->mTimestamp
) {
783 $this->loadLastEdit();
785 return wfTimestamp( TS_MW
, $this->mTimestamp
);
789 * @param $audience Integer: one of:
790 * Revision::FOR_PUBLIC to be displayed to all users
791 * Revision::FOR_THIS_USER to be displayed to $wgUser
792 * Revision::RAW get the text regardless of permissions
793 * @return int user ID for the user that made the last article revision
795 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
796 $this->loadLastEdit();
797 if ( $this->mLastRevision
) {
798 return $this->mLastRevision
->getUser( $audience );
805 * @param $audience Integer: one of:
806 * Revision::FOR_PUBLIC to be displayed to all users
807 * Revision::FOR_THIS_USER to be displayed to $wgUser
808 * Revision::RAW get the text regardless of permissions
809 * @return string username of the user that made the last article revision
811 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
812 $this->loadLastEdit();
813 if ( $this->mLastRevision
) {
814 return $this->mLastRevision
->getUserText( $audience );
821 * @param $audience Integer: one of:
822 * Revision::FOR_PUBLIC to be displayed to all users
823 * Revision::FOR_THIS_USER to be displayed to $wgUser
824 * Revision::RAW get the text regardless of permissions
825 * @return string Comment stored for the last article revision
827 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
828 $this->loadLastEdit();
829 if ( $this->mLastRevision
) {
830 return $this->mLastRevision
->getComment( $audience );
837 * Returns true if last revision was marked as "minor edit"
839 * @return boolean Minor edit indicator for the last article revision.
841 public function getMinorEdit() {
842 $this->loadLastEdit();
843 if ( $this->mLastRevision
) {
844 return $this->mLastRevision
->isMinor();
851 * Use this to fetch the rev ID used on page views
853 * @return int revision ID of last article revision
855 public function getRevIdFetched() {
856 if ( $this->mRevIdFetched
) {
857 return $this->mRevIdFetched
;
859 return $this->getLatest();
864 * Get a list of users who have edited this article, not including the user who made
865 * the most recent revision, which you can get from $article->getUser() if you want it
866 * @return UserArrayFromResult
868 public function getContributors() {
869 # @todo FIXME: This is expensive; cache this info somewhere.
871 $dbr = wfGetDB( DB_SLAVE
);
873 if ( $dbr->implicitGroupby() ) {
874 $realNameField = 'user_real_name';
876 $realNameField = 'FIRST(user_real_name) AS user_real_name';
879 $tables = array( 'revision', 'user' );
882 'rev_user as user_id',
883 'rev_user_text AS user_name',
885 'MAX(rev_timestamp) AS timestamp',
888 $conds = array( 'rev_page' => $this->getId() );
890 // The user who made the top revision gets credited as "this page was last edited by
891 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
892 $user = $this->getUser();
894 $conds[] = "rev_user != $user";
896 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
899 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
902 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
906 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
907 'ORDER BY' => 'timestamp DESC',
910 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
911 return new UserArrayFromResult( $res );
915 * This is the default action of the index.php entry point: just view the
916 * page of the given title.
918 public function view() {
919 global $wgUser, $wgOut, $wgRequest, $wgParser;
920 global $wgUseFileCache, $wgUseETag;
922 wfProfileIn( __METHOD__
);
924 # Get variables from query string
925 $oldid = $this->getOldID();
927 # getOldID may want us to redirect somewhere else
928 if ( $this->mRedirectUrl
) {
929 $wgOut->redirect( $this->mRedirectUrl
);
930 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
931 wfProfileOut( __METHOD__
);
936 $wgOut->setArticleFlag( true );
937 # Set page title (may be overridden by DISPLAYTITLE)
938 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
940 # If we got diff in the query, we want to see a diff page instead of the article.
941 if ( $wgRequest->getCheck( 'diff' ) ) {
942 wfDebug( __METHOD__
. ": showing diff page\n" );
943 $this->showDiffPage();
944 wfProfileOut( __METHOD__
);
949 # Allow frames by default
950 $wgOut->allowClickjacking();
952 $parserCache = ParserCache
::singleton();
954 $parserOptions = $this->getParserOptions();
955 # Render printable version, use printable version cache
956 if ( $wgOut->isPrintable() ) {
957 $parserOptions->setIsPrintable( true );
958 $parserOptions->setEditSection( false );
959 } elseif ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
960 $parserOptions->setEditSection( false );
963 # Try client and file cache
964 if ( $oldid === 0 && $this->checkTouched() ) {
966 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
969 # Is it client cached?
970 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
971 wfDebug( __METHOD__
. ": done 304\n" );
972 wfProfileOut( __METHOD__
);
976 } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
977 wfDebug( __METHOD__
. ": done file cache\n" );
978 # tell wgOut that output is taken care of
980 $this->viewUpdates();
981 wfProfileOut( __METHOD__
);
987 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
988 $parserOptions->setEditSection( false );
991 # Should the parser cache be used?
992 $useParserCache = $this->useParserCache( $oldid );
993 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
994 if ( $wgUser->getStubThreshold() ) {
995 wfIncrStats( 'pcache_miss_stub' );
998 $wasRedirected = $this->showRedirectedFromHeader();
999 $this->showNamespaceHeader();
1001 # Iterate through the possible ways of constructing the output text.
1002 # Keep going until $outputDone is set, or we run out of things to do.
1004 $outputDone = false;
1005 $this->mParserOutput
= false;
1007 while ( !$outputDone && ++
$pass ) {
1010 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
1013 # Try the parser cache
1014 if ( $useParserCache ) {
1015 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1017 if ( $this->mParserOutput
!== false ) {
1018 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
1019 $wgOut->addParserOutput( $this->mParserOutput
);
1020 # Ensure that UI elements requiring revision ID have
1021 # the correct version information.
1022 $wgOut->setRevisionId( $this->mLatest
);
1028 $text = $this->getContent();
1029 if ( $text === false ||
$this->getID() == 0 ) {
1030 wfDebug( __METHOD__
. ": showing missing article\n" );
1031 $this->showMissingArticle();
1032 wfProfileOut( __METHOD__
);
1036 # Another whitelist check in case oldid is altering the title
1037 if ( !$this->mTitle
->userCanRead() ) {
1038 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
1039 $wgOut->loginToUse();
1042 wfProfileOut( __METHOD__
);
1046 # Are we looking at an old revision
1047 if ( $oldid && !is_null( $this->mRevision
) ) {
1048 $this->setOldSubtitle( $oldid );
1050 if ( !$this->showDeletedRevisionHeader() ) {
1051 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
1052 wfProfileOut( __METHOD__
);
1056 # If this "old" version is the current, then try the parser cache...
1057 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
1058 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1059 if ( $this->mParserOutput
) {
1060 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
1061 $wgOut->addParserOutput( $this->mParserOutput
);
1062 $wgOut->setRevisionId( $this->mLatest
);
1069 # Ensure that UI elements requiring revision ID have
1070 # the correct version information.
1071 $wgOut->setRevisionId( $this->getRevIdFetched() );
1073 # Pages containing custom CSS or JavaScript get special treatment
1074 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1075 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1076 $this->showCssOrJsPage();
1079 $rt = Title
::newFromRedirectArray( $text );
1081 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1082 # Viewing a redirect page (e.g. with parameter redirect=no)
1083 # Don't append the subtitle if this was an old revision
1084 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1085 # Parse just to get categories, displaytitle, etc.
1086 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1087 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1093 # Run the parse, protected by a pool counter
1094 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1096 $key = $parserCache->getKey( $this, $parserOptions );
1097 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1099 if ( !$poolArticleView->execute() ) {
1100 # Connection or timeout error
1101 wfProfileOut( __METHOD__
);
1107 # Should be unreachable, but just in case...
1113 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1114 if ( $this->mParserOutput
) {
1115 $titleText = $this->mParserOutput
->getTitleText();
1117 if ( strval( $titleText ) !== '' ) {
1118 $wgOut->setPageTitle( $titleText );
1122 # For the main page, overwrite the <title> element with the con-
1123 # tents of 'pagetitle-view-mainpage' instead of the default (if
1124 # that's not empty).
1125 # This message always exists because it is in the i18n files
1126 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1127 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1128 if ( !$msg->isDisabled() ) {
1129 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1133 # Now that we've filled $this->mParserOutput, we know whether
1134 # there are any __NOINDEX__ tags on the page
1135 $policy = $this->getRobotPolicy( 'view' );
1136 $wgOut->setIndexPolicy( $policy['index'] );
1137 $wgOut->setFollowPolicy( $policy['follow'] );
1139 $this->showViewFooter();
1140 $this->viewUpdates();
1141 wfProfileOut( __METHOD__
);
1145 * Show a diff page according to current request variables. For use within
1146 * Article::view() only, other callers should use the DifferenceEngine class.
1148 public function showDiffPage() {
1149 global $wgRequest, $wgUser;
1151 $diff = $wgRequest->getVal( 'diff' );
1152 $rcid = $wgRequest->getVal( 'rcid' );
1153 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1154 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1155 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1156 $oldid = $this->getOldID();
1158 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1159 // DifferenceEngine directly fetched the revision:
1160 $this->mRevIdFetched
= $de->mNewid
;
1161 $de->showDiffPage( $diffOnly );
1163 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1164 # Run view updates for current revision only
1165 $this->viewUpdates();
1170 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1171 * Article::view() only.
1173 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1176 protected function showCssOrJsPage() {
1179 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1181 // Give hooks a chance to customise the output
1182 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1183 // Wrap the whole lot in a <pre> and don't parse
1185 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1186 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1187 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1188 $wgOut->addHTML( "\n</pre>\n" );
1193 * Get the robot policy to be used for the current view
1194 * @param $action String the action= GET parameter
1195 * @return Array the policy that should be set
1196 * TODO: actions other than 'view'
1198 public function getRobotPolicy( $action ) {
1199 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1200 global $wgDefaultRobotPolicy, $wgRequest;
1202 $ns = $this->mTitle
->getNamespace();
1204 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1205 # Don't index user and user talk pages for blocked users (bug 11443)
1206 if ( !$this->mTitle
->isSubpage() ) {
1207 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1209 'index' => 'noindex',
1210 'follow' => 'nofollow'
1216 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1217 # Non-articles (special pages etc), and old revisions
1219 'index' => 'noindex',
1220 'follow' => 'nofollow'
1222 } elseif ( $wgOut->isPrintable() ) {
1223 # Discourage indexing of printable versions, but encourage following
1225 'index' => 'noindex',
1226 'follow' => 'follow'
1228 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1229 # For ?curid=x urls, disallow indexing
1231 'index' => 'noindex',
1232 'follow' => 'follow'
1236 # Otherwise, construct the policy based on the various config variables.
1237 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1239 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1240 # Honour customised robot policies for this namespace
1241 $policy = array_merge(
1243 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1246 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1247 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1248 # a final sanity check that we have really got the parser output.
1249 $policy = array_merge(
1251 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1255 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1256 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1257 $policy = array_merge(
1259 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1267 * Converts a String robot policy into an associative array, to allow
1268 * merging of several policies using array_merge().
1269 * @param $policy Mixed, returns empty array on null/false/'', transparent
1270 * to already-converted arrays, converts String.
1271 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1273 public static function formatRobotPolicy( $policy ) {
1274 if ( is_array( $policy ) ) {
1276 } elseif ( !$policy ) {
1280 $policy = explode( ',', $policy );
1281 $policy = array_map( 'trim', $policy );
1284 foreach ( $policy as $var ) {
1285 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1286 $arr['index'] = $var;
1287 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1288 $arr['follow'] = $var;
1296 * If this request is a redirect view, send "redirected from" subtitle to
1297 * $wgOut. Returns true if the header was needed, false if this is not a
1298 * redirect view. Handles both local and remote redirects.
1302 public function showRedirectedFromHeader() {
1303 global $wgOut, $wgRequest, $wgRedirectSources;
1305 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1307 if ( isset( $this->mRedirectedFrom
) ) {
1308 // This is an internally redirected page view.
1309 // We'll need a backlink to the source page for navigation.
1310 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1311 $redir = Linker
::link(
1312 $this->mRedirectedFrom
,
1315 array( 'redirect' => 'no' ),
1316 array( 'known', 'noclasses' )
1319 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1320 $wgOut->setSubtitle( $s );
1322 // Set the fragment if one was specified in the redirect
1323 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1324 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1325 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1328 // Add a <link rel="canonical"> tag
1329 $wgOut->addLink( array( 'rel' => 'canonical',
1330 'href' => $this->mTitle
->getLocalURL() )
1335 } elseif ( $rdfrom ) {
1336 // This is an externally redirected view, from some other wiki.
1337 // If it was reported from a trusted site, supply a backlink.
1338 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1339 $redir = Linker
::makeExternalLink( $rdfrom, $rdfrom );
1340 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1341 $wgOut->setSubtitle( $s );
1351 * Show a header specific to the namespace currently being viewed, like
1352 * [[MediaWiki:Talkpagetext]]. For Article::view().
1354 public function showNamespaceHeader() {
1357 if ( $this->mTitle
->isTalkPage() ) {
1358 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1359 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1365 * Show the footer section of an ordinary page view
1367 public function showViewFooter() {
1368 global $wgOut, $wgUseTrackbacks;
1370 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1371 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1372 $wgOut->addWikiMsg( 'anontalkpagetext' );
1375 # If we have been passed an &rcid= parameter, we want to give the user a
1376 # chance to mark this new article as patrolled.
1377 $this->showPatrolFooter();
1380 if ( $wgUseTrackbacks ) {
1381 $this->addTrackbacks();
1384 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1389 * If patrol is possible, output a patrol UI box. This is called from the
1390 * footer section of ordinary page views. If patrol is not possible or not
1391 * desired, does nothing.
1393 public function showPatrolFooter() {
1394 global $wgOut, $wgRequest, $wgUser;
1396 $rcid = $wgRequest->getVal( 'rcid' );
1398 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1402 $token = $wgUser->editToken( $rcid );
1403 $wgOut->preventClickjacking();
1406 "<div class='patrollink'>" .
1408 'markaspatrolledlink',
1411 wfMsgHtml( 'markaspatrolledtext' ),
1414 'action' => 'markpatrolled',
1418 array( 'known', 'noclasses' )
1426 * Show the error text for a missing article. For articles in the MediaWiki
1427 * namespace, show the default message text. To be called from Article::view().
1429 public function showMissingArticle() {
1430 global $wgOut, $wgRequest, $wgUser;
1432 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1433 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1434 $parts = explode( '/', $this->mTitle
->getText() );
1435 $rootPart = $parts[0];
1436 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1437 $ip = User
::isIP( $rootPart );
1439 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1440 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1441 array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
1442 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1443 LogEventsList
::showLogExtract(
1446 $user->getUserPage()->getPrefixedText(),
1450 'showIfEmpty' => false,
1452 'blocked-notice-logextract',
1453 $user->getName() # Support GENDER in notice
1460 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1462 # Show delete and move logs
1463 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1465 'conds' => array( "log_action != 'revision'" ),
1466 'showIfEmpty' => false,
1467 'msgKey' => array( 'moveddeleted-notice' ) )
1470 # Show error message
1471 $oldid = $this->getOldID();
1473 $text = wfMsgNoTrans( 'missing-article',
1474 $this->mTitle
->getPrefixedText(),
1475 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1476 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1477 // Use the default message text
1478 $text = $this->mTitle
->getDefaultMessageText();
1480 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1481 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1482 $errors = array_merge( $createErrors, $editErrors );
1484 if ( !count( $errors ) ) {
1485 $text = wfMsgNoTrans( 'noarticletext' );
1487 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1490 $text = "<div class='noarticletext'>\n$text\n</div>";
1492 if ( !$this->hasViewableContent() ) {
1493 // If there's no backing content, send a 404 Not Found
1494 // for better machine handling of broken links.
1495 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1498 $wgOut->addWikiText( $text );
1502 * If the revision requested for view is deleted, check permissions.
1503 * Send either an error message or a warning header to $wgOut.
1505 * @return boolean true if the view is allowed, false if not.
1507 public function showDeletedRevisionHeader() {
1508 global $wgOut, $wgRequest;
1510 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1515 // If the user is not allowed to see it...
1516 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1517 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1518 'rev-deleted-text-permission' );
1521 // If the user needs to confirm that they want to see it...
1522 } elseif ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1523 # Give explanation and add a link to view the revision...
1524 $oldid = intval( $this->getOldID() );
1525 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1526 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1527 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1528 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1529 array( $msg, $link ) );
1532 // We are allowed to see...
1534 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1535 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1536 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1543 * Should the parser cache be used?
1547 public function useParserCache( $oldid ) {
1548 global $wgUser, $wgEnableParserCache;
1550 return $wgEnableParserCache
1551 && $wgUser->getStubThreshold() == 0
1554 && !$this->mTitle
->isCssOrJsPage()
1555 && !$this->mTitle
->isCssJsSubpage();
1559 * Execute the uncached parse for action=view
1561 public function doViewParse() {
1564 $oldid = $this->getOldID();
1565 $parserOptions = $this->getParserOptions();
1567 # Render printable version, use printable version cache
1568 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1570 # Don't show section-edit links on old revisions... this way lies madness.
1571 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1572 $parserOptions->setEditSection( false );
1575 $useParserCache = $this->useParserCache( $oldid );
1576 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1582 * Try to fetch an expired entry from the parser cache. If it is present,
1583 * output it and return true. If it is not present, output nothing and
1584 * return false. This is used as a callback function for
1585 * PoolCounter::executeProtected().
1589 public function tryDirtyCache() {
1591 $parserCache = ParserCache
::singleton();
1592 $options = $this->getParserOptions();
1594 if ( $wgOut->isPrintable() ) {
1595 $options->setIsPrintable( true );
1596 $options->setEditSection( false );
1599 $output = $parserCache->getDirty( $this, $options );
1602 wfDebug( __METHOD__
. ": sending dirty output\n" );
1603 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1604 $wgOut->setSquidMaxage( 0 );
1605 $this->mParserOutput
= $output;
1606 $wgOut->addParserOutput( $output );
1607 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1611 wfDebugLog( 'dirty', "dirty missing\n" );
1612 wfDebug( __METHOD__
. ": no dirty cache\n" );
1621 * @param $target Title|Array of destination(s) to redirect
1622 * @param $appendSubtitle Boolean [optional]
1623 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1624 * @return string containing HMTL with redirect link
1626 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1627 global $wgOut, $wgStylePath;
1629 if ( !is_array( $target ) ) {
1630 $target = array( $target );
1633 $imageDir = wfUILang()->getDir();
1635 if ( $appendSubtitle ) {
1636 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1639 // the loop prepends the arrow image before the link, so the first case needs to be outside
1640 $title = array_shift( $target );
1642 if ( $forceKnown ) {
1643 $link = Linker
::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1645 $link = Linker
::link( $title, htmlspecialchars( $title->getFullText() ) );
1648 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1649 $alt = wfUILang()->isRTL() ?
'←' : '→';
1650 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1651 foreach ( $target as $rt ) {
1652 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1653 if ( $forceKnown ) {
1654 $link .= Linker
::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1656 $link .= Linker
::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1660 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1661 return '<div class="redirectMsg">' .
1662 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1663 '<span class="redirectText">' . $link . '</span></div>';
1667 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1669 public function addTrackbacks() {
1672 $dbr = wfGetDB( DB_SLAVE
);
1673 $tbs = $dbr->select( 'trackbacks',
1674 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1675 array( 'tb_page' => $this->getID() )
1678 if ( !$dbr->numRows( $tbs ) ) {
1682 $wgOut->preventClickjacking();
1685 foreach ( $tbs as $o ) {
1688 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1689 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1690 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1691 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1695 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1703 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1707 * Removes trackback record for current article from trackbacks table
1708 * @deprecated since 1.19
1710 public function deletetrackback() {
1711 return Action
::factory( 'deletetrackback', $this )->show();
1715 * Handle action=render
1718 public function render() {
1721 $wgOut->setArticleBodyOnly( true );
1726 * Handle action=purge
1728 public function purge() {
1729 return Action
::factory( 'purge', $this )->show();
1733 * Perform the actions of a page purging
1735 public function doPurge() {
1738 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1742 // Invalidate the cache
1743 $this->mTitle
->invalidateCache();
1746 if ( $wgUseSquid ) {
1747 // Commit the transaction before the purge is sent
1748 $dbw = wfGetDB( DB_MASTER
);
1752 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1753 $update->doUpdate();
1756 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1757 if ( $this->getID() == 0 ) {
1760 $text = $this->getRawText();
1763 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1768 * Mark this particular edit/page as patrolled
1769 * @deprecated since 1.19
1771 public function markpatrolled() {
1772 Action
::factory( 'markpatrolled', $this )->show();
1776 * User-interface handler for the "watch" action.
1777 * Requires Request to pass a token as of 1.19.
1778 * @deprecated since 1.18
1780 public function watch() {
1781 Action
::factory( 'watch', $this )->show();
1785 * Add this page to $wgUser's watchlist
1787 * This is safe to be called multiple times
1789 * @return bool true on successful watch operation
1790 * @deprecated since 1.18
1792 public function doWatch() {
1794 return WatchAction
::doWatch( $this->mTitle
, $wgUser );
1798 * User interface handler for the "unwatch" action.
1799 * Requires Request to pass a token as of 1.19.
1800 * @deprecated since 1.18
1802 public function unwatch() {
1803 Action
::factory( 'unwatch', $this )->show();
1807 * Stop watching a page
1808 * @return bool true on successful unwatch
1809 * @deprecated since 1.18
1811 public function doUnwatch() {
1813 return WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1817 * action=protect handler
1819 public function protect() {
1820 $form = new ProtectionForm( $this );
1825 * action=unprotect handler (alias)
1827 public function unprotect() {
1832 * Info about this page
1833 * Called for ?action=info when $wgAllowPageInfo is on.
1835 public function info() {
1836 Action
::factory( 'info', $this )->show();
1840 * Insert a new empty page record for this article.
1841 * This *must* be followed up by creating a revision
1842 * and running $this->updateRevisionOn( ... );
1843 * or else the record will be left in a funky state.
1844 * Best if all done inside a transaction.
1846 * @param $dbw DatabaseBase
1847 * @return int The newly created page_id key, or false if the title already existed
1850 public function insertOn( $dbw ) {
1851 wfProfileIn( __METHOD__
);
1853 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1854 $dbw->insert( 'page', array(
1855 'page_id' => $page_id,
1856 'page_namespace' => $this->mTitle
->getNamespace(),
1857 'page_title' => $this->mTitle
->getDBkey(),
1858 'page_counter' => 0,
1859 'page_restrictions' => '',
1860 'page_is_redirect' => 0, # Will set this shortly...
1862 'page_random' => wfRandom(),
1863 'page_touched' => $dbw->timestamp(),
1864 'page_latest' => 0, # Fill this in shortly...
1865 'page_len' => 0, # Fill this in shortly...
1866 ), __METHOD__
, 'IGNORE' );
1868 $affected = $dbw->affectedRows();
1871 $newid = $dbw->insertId();
1872 $this->mTitle
->resetArticleID( $newid );
1874 wfProfileOut( __METHOD__
);
1876 return $affected ?
$newid : false;
1880 * Update the page record to point to a newly saved revision.
1882 * @param $dbw DatabaseBase: object
1883 * @param $revision Revision: For ID number, and text used to set
1884 length and redirect status fields
1885 * @param $lastRevision Integer: if given, will not overwrite the page field
1886 * when different from the currently set value.
1887 * Giving 0 indicates the new page flag should be set
1889 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1890 * removing rows in redirect table.
1891 * @return bool true on success, false on failure
1894 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1895 wfProfileIn( __METHOD__
);
1897 $text = $revision->getText();
1898 $rt = Title
::newFromRedirectRecurse( $text );
1900 $conditions = array( 'page_id' => $this->getId() );
1902 if ( !is_null( $lastRevision ) ) {
1903 # An extra check against threads stepping on each other
1904 $conditions['page_latest'] = $lastRevision;
1907 $dbw->update( 'page',
1909 'page_latest' => $revision->getId(),
1910 'page_touched' => $dbw->timestamp(),
1911 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1912 'page_is_redirect' => $rt !== null ?
1 : 0,
1913 'page_len' => strlen( $text ),
1918 $result = $dbw->affectedRows() != 0;
1920 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1923 wfProfileOut( __METHOD__
);
1928 * Add row to the redirect table if this is a redirect, remove otherwise.
1930 * @param $dbw DatabaseBase
1931 * @param $redirectTitle Title object pointing to the redirect target,
1932 * or NULL if this is not a redirect
1933 * @param $lastRevIsRedirect If given, will optimize adding and
1934 * removing rows in redirect table.
1935 * @return bool true on success, false on failure
1938 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1939 // Always update redirects (target link might have changed)
1940 // Update/Insert if we don't know if the last revision was a redirect or not
1941 // Delete if changing from redirect to non-redirect
1942 $isRedirect = !is_null( $redirectTitle );
1944 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1948 wfProfileIn( __METHOD__
);
1949 if ( $isRedirect ) {
1950 $this->insertRedirectEntry( $redirectTitle );
1952 // This is not a redirect, remove row from redirect table
1953 $where = array( 'rd_from' => $this->getId() );
1954 $dbw->delete( 'redirect', $where, __METHOD__
);
1957 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1958 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1960 wfProfileOut( __METHOD__
);
1962 return ( $dbw->affectedRows() != 0 );
1966 * If the given revision is newer than the currently set page_latest,
1967 * update the page record. Otherwise, do nothing.
1969 * @param $dbw Database object
1970 * @param $revision Revision object
1973 public function updateIfNewerOn( &$dbw, $revision ) {
1974 wfProfileIn( __METHOD__
);
1976 $row = $dbw->selectRow(
1977 array( 'revision', 'page' ),
1978 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1980 'page_id' => $this->getId(),
1981 'page_latest=rev_id' ),
1985 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1986 wfProfileOut( __METHOD__
);
1989 $prev = $row->rev_id
;
1990 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1992 # No or missing previous revision; mark the page as new
1994 $lastRevIsRedirect = null;
1997 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1999 wfProfileOut( __METHOD__
);
2004 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
2005 * @param $text String: new text of the section
2006 * @param $summary String: new section's subject, only if $section is 'new'
2007 * @param $edittime String: revision timestamp or null to use the current revision
2008 * @return string Complete article text, or null if error
2010 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
2011 wfProfileIn( __METHOD__
);
2013 if ( strval( $section ) == '' ) {
2014 // Whole-page edit; let the whole text through
2016 if ( is_null( $edittime ) ) {
2017 $rev = Revision
::newFromTitle( $this->mTitle
);
2019 $dbw = wfGetDB( DB_MASTER
);
2020 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
2024 wfDebug( "Article::replaceSection asked for bogus section (page: " .
2025 $this->getId() . "; section: $section; edittime: $edittime)\n" );
2026 wfProfileOut( __METHOD__
);
2030 $oldtext = $rev->getText();
2032 if ( $section == 'new' ) {
2033 # Inserting a new section
2034 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
2035 $text = strlen( trim( $oldtext ) ) > 0
2036 ?
"{$oldtext}\n\n{$subject}{$text}"
2037 : "{$subject}{$text}";
2039 # Replacing an existing section; roll out the big guns
2042 $text = $wgParser->replaceSection( $oldtext, $section, $text );
2046 wfProfileOut( __METHOD__
);
2051 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
2053 * @return Int updated $flags
2055 function checkFlags( $flags ) {
2056 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
2057 if ( $this->mTitle
->getArticleID() ) {
2058 $flags |
= EDIT_UPDATE
;
2070 * Change an existing article or create a new article. Updates RC and all necessary caches,
2071 * optionally via the deferred update array.
2073 * $wgUser must be set before calling this function.
2075 * @param $text String: new text
2076 * @param $summary String: edit summary
2077 * @param $flags Integer bitfield:
2079 * Article is known or assumed to be non-existent, create a new one
2081 * Article is known or assumed to be pre-existing, update it
2083 * Mark this edit minor, if the user is allowed to do so
2085 * Do not log the change in recentchanges
2087 * Mark the edit a "bot" edit regardless of user rights
2088 * EDIT_DEFER_UPDATES
2089 * Defer some of the updates until the end of index.php
2091 * Fill in blank summaries with generated text where possible
2093 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2094 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2095 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2096 * edit-already-exists error will be returned. These two conditions are also possible with
2097 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2099 * @param $baseRevId the revision ID this edit was based off, if any
2100 * @param $user User (optional), $wgUser will be used if not passed
2102 * @return Status object. Possible errors:
2103 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2104 * edit-gone-missing: In update mode, but the article didn't exist
2105 * edit-conflict: In update mode, the article changed unexpectedly
2106 * edit-no-change: Warning that the text was the same as before
2107 * edit-already-exists: In creation mode, but the article already exists
2109 * Extensions may define additional errors.
2111 * $return->value will contain an associative array with members as follows:
2112 * new: Boolean indicating if the function attempted to create a new article
2113 * revision: The revision object for the inserted revision, or null
2115 * Compatibility note: this function previously returned a boolean value indicating success/failure
2117 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2118 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2120 # Low-level sanity check
2121 if ( $this->mTitle
->getText() === '' ) {
2122 throw new MWException( 'Something is trying to edit an article with an empty title' );
2125 wfProfileIn( __METHOD__
);
2127 $user = is_null( $user ) ?
$wgUser : $user;
2128 $status = Status
::newGood( array() );
2130 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2131 $this->loadPageData();
2133 $flags = $this->checkFlags( $flags );
2135 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2136 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2138 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2140 if ( $status->isOK() ) {
2141 $status->fatal( 'edit-hook-aborted' );
2144 wfProfileOut( __METHOD__
);
2148 # Silently ignore EDIT_MINOR if not allowed
2149 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2150 $bot = $flags & EDIT_FORCE_BOT
;
2152 $oldtext = $this->getRawText(); // current revision
2153 $oldsize = strlen( $oldtext );
2155 # Provide autosummaries if one is not provided and autosummaries are enabled.
2156 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2157 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2160 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2161 $text = $editInfo->pst
;
2162 $newsize = strlen( $text );
2164 $dbw = wfGetDB( DB_MASTER
);
2165 $now = wfTimestampNow();
2166 $this->mTimestamp
= $now;
2168 if ( $flags & EDIT_UPDATE
) {
2169 # Update article, but only if changed.
2170 $status->value
['new'] = false;
2172 # Make sure the revision is either completely inserted or not inserted at all
2173 if ( !$wgDBtransactions ) {
2174 $userAbort = ignore_user_abort( true );
2177 $changed = ( strcmp( $text, $oldtext ) != 0 );
2180 if ( !$this->mLatest
) {
2181 # Article gone missing
2182 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2183 $status->fatal( 'edit-gone-missing' );
2185 wfProfileOut( __METHOD__
);
2189 $revision = new Revision( array(
2190 'page' => $this->getId(),
2191 'comment' => $summary,
2192 'minor_edit' => $isminor,
2194 'parent_id' => $this->mLatest
,
2195 'user' => $user->getId(),
2196 'user_text' => $user->getName(),
2201 $revisionId = $revision->insertOn( $dbw );
2205 # Note that we use $this->mLatest instead of fetching a value from the master DB
2206 # during the course of this function. This makes sure that EditPage can detect
2207 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2208 # before this function is called. A previous function used a separate query, this
2209 # creates a window where concurrent edits can cause an ignored edit conflict.
2210 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2213 /* Belated edit conflict! Run away!! */
2214 $status->fatal( 'edit-conflict' );
2216 # Delete the invalid revision if the DB is not transactional
2217 if ( !$wgDBtransactions ) {
2218 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2224 global $wgUseRCPatrol;
2225 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2226 # Update recentchanges
2227 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2228 # Mark as patrolled if the user can do so
2229 $patrolled = $wgUseRCPatrol && !count(
2230 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2231 # Add RC row to the DB
2232 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2233 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2234 $revisionId, $patrolled
2237 # Log auto-patrolled edits
2239 PatrolLog
::record( $rc, true );
2242 $user->incEditCount();
2246 $status->warning( 'edit-no-change' );
2248 // Keep the same revision ID, but do some updates on it
2249 $revisionId = $this->getLatest();
2250 // Update page_touched, this is usually implicit in the page update
2251 // Other cache updates are done in onArticleEdit()
2252 $this->mTitle
->invalidateCache();
2255 if ( !$wgDBtransactions ) {
2256 ignore_user_abort( $userAbort );
2259 // Now that ignore_user_abort is restored, we can respond to fatal errors
2260 if ( !$status->isOK() ) {
2261 wfProfileOut( __METHOD__
);
2265 # Invalidate cache of this article and all pages using this article
2266 # as a template. Partly deferred.
2267 Article
::onArticleEdit( $this->mTitle
);
2268 # Update links tables, site stats, etc.
2269 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2271 # Create new article
2272 $status->value
['new'] = true;
2276 # Add the page record; stake our claim on this title!
2277 # This will return false if the article already exists
2278 $newid = $this->insertOn( $dbw );
2280 if ( $newid === false ) {
2282 $status->fatal( 'edit-already-exists' );
2284 wfProfileOut( __METHOD__
);
2288 # Save the revision text...
2289 $revision = new Revision( array(
2291 'comment' => $summary,
2292 'minor_edit' => $isminor,
2294 'user' => $user->getId(),
2295 'user_text' => $user->getName(),
2298 $revisionId = $revision->insertOn( $dbw );
2300 $this->mTitle
->resetArticleID( $newid );
2301 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
2303 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2305 # Update the page record with revision data
2306 $this->updateRevisionOn( $dbw, $revision, 0 );
2308 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2310 # Update recentchanges
2311 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2312 global $wgUseRCPatrol, $wgUseNPPatrol;
2314 # Mark as patrolled if the user can do so
2315 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2316 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2317 # Add RC row to the DB
2318 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2319 '', strlen( $text ), $revisionId, $patrolled );
2321 # Log auto-patrolled edits
2323 PatrolLog
::record( $rc, true );
2326 $user->incEditCount();
2329 # Update links, etc.
2330 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user, true );
2333 Article
::onArticleCreate( $this->mTitle
);
2335 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2336 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2339 # Do updates right now unless deferral was requested
2340 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2344 // Return the new revision (or null) to the caller
2345 $status->value
['revision'] = $revision;
2347 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2348 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2350 # Promote user to any groups they meet the criteria for
2351 $user->addAutopromoteOnceGroups( 'onEdit' );
2353 wfProfileOut( __METHOD__
);
2358 * Output a redirect back to the article.
2359 * This is typically used after an edit.
2361 * @deprecated in 1.19; call $wgOut->redirect() directly
2362 * @param $noRedir Boolean: add redirect=no
2363 * @param $sectionAnchor String: section to redirect to, including "#"
2364 * @param $extraQuery String: extra query params
2366 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2367 wfDeprecated( __METHOD__
);
2371 $query = 'redirect=no';
2373 $query .= "&$extraQuery";
2375 $query = $extraQuery;
2378 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2382 * Update the article's restriction field, and leave a log entry.
2384 * @param $limit Array: set of restriction keys
2385 * @param $reason String
2386 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2387 * @param $expiry Array: per restriction type expiration
2388 * @return bool true on success
2390 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2391 global $wgUser, $wgContLang;
2393 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2395 $id = $this->mTitle
->getArticleID();
2398 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2402 if ( wfReadOnly() ) {
2403 wfDebug( "updateRestrictions failed: read-only\n" );
2407 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2408 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2416 // Take this opportunity to purge out expired restrictions
2417 Title
::purgeExpiredRestrictions();
2419 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2420 # we expect a single selection, but the schema allows otherwise.
2422 $updated = Article
::flattenRestrictions( $limit );
2425 foreach ( $restrictionTypes as $action ) {
2426 if ( isset( $expiry[$action] ) ) {
2427 # Get current restrictions on $action
2428 $aLimits = $this->mTitle
->getRestrictions( $action );
2429 $current[$action] = implode( '', $aLimits );
2430 # Are any actual restrictions being dealt with here?
2431 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2433 # If something changed, we need to log it. Checking $aRChanged
2434 # assures that "unprotecting" a page that is not protected does
2435 # not log just because the expiry was "changed".
2436 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2442 $current = Article
::flattenRestrictions( $current );
2444 $changed = ( $changed ||
$current != $updated );
2445 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2446 $protect = ( $updated != '' );
2448 # If nothing's changed, do nothing
2450 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2451 $dbw = wfGetDB( DB_MASTER
);
2453 # Prepare a null revision to be added to the history
2454 $modified = $current != '' && $protect;
2457 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2459 $comment_type = 'unprotectedarticle';
2462 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2464 # Only restrictions with the 'protect' right can cascade...
2465 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2466 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2468 # The schema allows multiple restrictions
2469 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2473 $cascade_description = '';
2476 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2480 $comment .= ": $reason";
2483 $editComment = $comment;
2484 $encodedExpiry = array();
2485 $protect_description = '';
2486 foreach ( $limit as $action => $restrictions ) {
2487 if ( !isset( $expiry[$action] ) )
2488 $expiry[$action] = $dbw->getInfinity();
2490 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2491 if ( $restrictions != '' ) {
2492 $protect_description .= "[$action=$restrictions] (";
2493 if ( $encodedExpiry[$action] != 'infinity' ) {
2494 $protect_description .= wfMsgForContent( 'protect-expiring',
2495 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2496 $wgContLang->date( $expiry[$action], false, false ) ,
2497 $wgContLang->time( $expiry[$action], false, false ) );
2499 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2502 $protect_description .= ') ';
2505 $protect_description = trim( $protect_description );
2507 if ( $protect_description && $protect ) {
2508 $editComment .= " ($protect_description)";
2512 $editComment .= "$cascade_description";
2515 # Update restrictions table
2516 foreach ( $limit as $action => $restrictions ) {
2517 if ( $restrictions != '' ) {
2518 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2519 array( 'pr_page' => $id,
2520 'pr_type' => $action,
2521 'pr_level' => $restrictions,
2522 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2523 'pr_expiry' => $encodedExpiry[$action]
2528 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2529 'pr_type' => $action ), __METHOD__
);
2533 # Insert a null revision
2534 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2535 $nullRevId = $nullRevision->insertOn( $dbw );
2537 $latest = $this->getLatest();
2538 # Update page record
2539 $dbw->update( 'page',
2541 'page_touched' => $dbw->timestamp(),
2542 'page_restrictions' => '',
2543 'page_latest' => $nullRevId
2544 ), array( /* WHERE */
2546 ), 'Article::protect'
2549 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2550 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2552 # Update the protection log
2553 $log = new LogPage( 'protect' );
2555 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2556 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2558 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2561 } # End "changed" check
2567 * Take an array of page restrictions and flatten it to a string
2568 * suitable for insertion into the page_restrictions field.
2569 * @param $limit Array
2572 protected static function flattenRestrictions( $limit ) {
2573 if ( !is_array( $limit ) ) {
2574 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2580 foreach ( $limit as $action => $restrictions ) {
2581 if ( $restrictions != '' ) {
2582 $bits[] = "$action=$restrictions";
2586 return implode( ':', $bits );
2590 * Auto-generates a deletion reason
2592 * @param &$hasHistory Boolean: whether the page has a history
2593 * @return mixed String containing deletion reason or empty string, or boolean false
2594 * if no revision occurred
2596 public function generateReason( &$hasHistory ) {
2599 $dbw = wfGetDB( DB_MASTER
);
2600 // Get the last revision
2601 $rev = Revision
::newFromTitle( $this->mTitle
);
2603 if ( is_null( $rev ) ) {
2607 // Get the article's contents
2608 $contents = $rev->getText();
2611 // If the page is blank, use the text from the previous revision,
2612 // which can only be blank if there's a move/import/protect dummy revision involved
2613 if ( $contents == '' ) {
2614 $prev = $rev->getPrevious();
2617 $contents = $prev->getText();
2622 // Find out if there was only one contributor
2623 // Only scan the last 20 revisions
2624 $res = $dbw->select( 'revision', 'rev_user_text',
2625 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2627 array( 'LIMIT' => 20 )
2630 if ( $res === false ) {
2631 // This page has no revisions, which is very weird
2635 $hasHistory = ( $res->numRows() > 1 );
2636 $row = $dbw->fetchObject( $res );
2638 if ( $row ) { // $row is false if the only contributor is hidden
2639 $onlyAuthor = $row->rev_user_text
;
2640 // Try to find a second contributor
2641 foreach ( $res as $row ) {
2642 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2643 $onlyAuthor = false;
2648 $onlyAuthor = false;
2651 // Generate the summary with a '$1' placeholder
2653 // The current revision is blank and the one before is also
2654 // blank. It's just not our lucky day
2655 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2657 if ( $onlyAuthor ) {
2658 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2660 $reason = wfMsgForContent( 'excontent', '$1' );
2664 if ( $reason == '-' ) {
2665 // Allow these UI messages to be blanked out cleanly
2669 // Replace newlines with spaces to prevent uglyness
2670 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2671 // Calculate the maximum amount of chars to get
2672 // Max content length = max comment length - length of the comment (excl. $1)
2673 $maxLength = 255 - ( strlen( $reason ) - 2 );
2674 $contents = $wgContLang->truncate( $contents, $maxLength );
2675 // Remove possible unfinished links
2676 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2677 // Now replace the '$1' placeholder
2678 $reason = str_replace( '$1', $contents, $reason );
2685 * UI entry point for page deletion
2687 public function delete() {
2688 global $wgOut, $wgRequest;
2690 $confirm = $wgRequest->wasPosted() &&
2691 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2693 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2694 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2696 $reason = $this->DeleteReasonList
;
2698 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2699 // Entry from drop down menu + additional comment
2700 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2701 } elseif ( $reason == 'other' ) {
2702 $reason = $this->DeleteReason
;
2705 # Flag to hide all contents of the archived revisions
2706 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2708 # This code desperately needs to be totally rewritten
2710 # Read-only check...
2711 if ( wfReadOnly() ) {
2712 $wgOut->readOnlyPage();
2718 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2720 if ( count( $permission_errors ) > 0 ) {
2721 $wgOut->showPermissionsErrorPage( $permission_errors );
2726 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2728 # Better double-check that it hasn't been deleted yet!
2729 $dbw = wfGetDB( DB_MASTER
);
2730 $conds = $this->mTitle
->pageCond();
2731 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2732 if ( $latest === false ) {
2733 $wgOut->showFatalError(
2736 array( 'class' => 'error mw-error-cannotdelete' ),
2737 wfMsgExt( 'cannotdelete', array( 'parse' ),
2738 wfEscapeWikiText( $this->mTitle
->getPrefixedText() ) )
2741 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2742 LogEventsList
::showLogExtract(
2745 $this->mTitle
->getPrefixedText()
2751 # Hack for big sites
2752 $bigHistory = $this->isBigDeletion();
2753 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2754 global $wgLang, $wgDeleteRevisionsLimit;
2756 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2757 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2763 $this->doDelete( $reason, $suppress );
2765 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2767 } elseif ( $this->mTitle
->userIsWatching() ) {
2774 // Generate deletion reason
2775 $hasHistory = false;
2777 $reason = $this->generateReason( $hasHistory );
2780 // If the page has a history, insert a warning
2781 if ( $hasHistory && !$confirm ) {
2784 $revisions = $this->estimateRevisionCount();
2785 // @todo FIXME: i18n issue/patchwork message
2786 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2787 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2788 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->mTitle
,
2789 wfMsgHtml( 'history' ),
2790 array( 'rel' => 'archives' ),
2791 array( 'action' => 'history' ) ) .
2795 if ( $bigHistory ) {
2796 global $wgDeleteRevisionsLimit;
2797 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2798 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2802 return $this->confirmDelete( $reason );
2806 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2808 public function isBigDeletion() {
2809 global $wgDeleteRevisionsLimit;
2811 if ( $wgDeleteRevisionsLimit ) {
2812 $revCount = $this->estimateRevisionCount();
2814 return $revCount > $wgDeleteRevisionsLimit;
2821 * @return int approximate revision count
2823 public function estimateRevisionCount() {
2824 $dbr = wfGetDB( DB_SLAVE
);
2826 // For an exact count...
2827 // return $dbr->selectField( 'revision', 'COUNT(*)',
2828 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2829 return $dbr->estimateRowCount( 'revision', '*',
2830 array( 'rev_page' => $this->getId() ), __METHOD__
);
2834 * Get the last N authors
2835 * @param $num Integer: number of revisions to get
2836 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2837 * @return array Array of authors, duplicates not removed
2839 public function getLastNAuthors( $num, $revLatest = 0 ) {
2840 wfProfileIn( __METHOD__
);
2841 // First try the slave
2842 // If that doesn't have the latest revision, try the master
2844 $db = wfGetDB( DB_SLAVE
);
2847 $res = $db->select( array( 'page', 'revision' ),
2848 array( 'rev_id', 'rev_user_text' ),
2850 'page_namespace' => $this->mTitle
->getNamespace(),
2851 'page_title' => $this->mTitle
->getDBkey(),
2852 'rev_page = page_id'
2855 'ORDER BY' => 'rev_timestamp DESC',
2861 wfProfileOut( __METHOD__
);
2865 $row = $db->fetchObject( $res );
2867 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2868 $db = wfGetDB( DB_MASTER
);
2873 } while ( $continue );
2875 $authors = array( $row->rev_user_text
);
2877 foreach ( $res as $row ) {
2878 $authors[] = $row->rev_user_text
;
2881 wfProfileOut( __METHOD__
);
2886 * Output deletion confirmation dialog
2887 * @todo FIXME: Move to another file?
2888 * @param $reason String: prefilled reason
2890 public function confirmDelete( $reason ) {
2893 wfDebug( "Article::confirmDelete\n" );
2895 $deleteBackLink = Linker
::linkKnown( $this->mTitle
);
2896 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2897 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2898 $wgOut->addWikiMsg( 'confirmdeletetext' );
2900 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2902 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2903 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2905 <td class='mw-input'><strong>" .
2906 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2907 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2913 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2915 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2916 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2917 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2918 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2919 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2920 "<tr id=\"wpDeleteReasonListRow\">
2921 <td class='mw-label'>" .
2922 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2924 <td class='mw-input'>" .
2925 Xml
::listDropDown( 'wpDeleteReasonList',
2926 wfMsgForContent( 'deletereason-dropdown' ),
2927 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2930 <tr id=\"wpDeleteReasonRow\">
2931 <td class='mw-label'>" .
2932 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2934 <td class='mw-input'>" .
2935 Html
::input( 'wpReason', $reason, 'text', array(
2937 'maxlength' => '255',
2945 # Disallow watching if user is not logged in
2946 if ( $wgOut->getUser()->isLoggedIn() ) {
2950 <td class='mw-input'>" .
2951 Xml
::checkLabel( wfMsg( 'watchthis' ),
2952 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2961 <td class='mw-submit'>" .
2962 Xml
::submitButton( wfMsg( 'deletepage' ),
2963 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2966 Xml
::closeElement( 'table' ) .
2967 Xml
::closeElement( 'fieldset' ) .
2968 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2969 Xml
::closeElement( 'form' );
2971 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2972 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2973 $link = Linker
::link(
2975 wfMsgHtml( 'delete-edit-reasonlist' ),
2977 array( 'action' => 'edit' )
2979 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2982 $wgOut->addHTML( $form );
2983 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2984 LogEventsList
::showLogExtract( $wgOut, 'delete',
2985 $this->mTitle
->getPrefixedText()
2990 * Perform a deletion and output success or failure messages
2992 public function doDelete( $reason, $suppress = false ) {
2995 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2998 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
2999 $deleted = $this->mTitle
->getPrefixedText();
3001 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3002 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3004 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3006 $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
3007 $wgOut->returnToMain( false );
3009 if ( $error == '' ) {
3010 $wgOut->showFatalError(
3013 array( 'class' => 'error mw-error-cannotdelete' ),
3014 wfMsgExt( 'cannotdelete', array( 'parse' ),
3015 wfEscapeWikiText( $this->mTitle
->getPrefixedText() ) )
3019 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3021 LogEventsList
::showLogExtract(
3024 $this->mTitle
->getPrefixedText()
3027 $wgOut->showFatalError( $error );
3033 * Back-end article deletion
3034 * Deletes the article with database consistency, writes logs, purges caches
3036 * @param $reason string delete reason for deletion log
3037 * @param suppress bitfield
3038 * Revision::DELETED_TEXT
3039 * Revision::DELETED_COMMENT
3040 * Revision::DELETED_USER
3041 * Revision::DELETED_RESTRICTED
3042 * @param $id int article ID
3043 * @param $commit boolean defaults to true, triggers transaction end
3044 * @return boolean true if successful
3046 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3047 global $wgDeferredUpdateList, $wgUseTrackbacks;
3050 wfDebug( __METHOD__
. "\n" );
3052 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3055 $dbw = wfGetDB( DB_MASTER
);
3056 $t = $this->mTitle
->getDBkey();
3057 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3059 if ( $t === '' ||
$id == 0 ) {
3063 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
3064 array_push( $wgDeferredUpdateList, $u );
3066 // Bitfields to further suppress the content
3069 // This should be 15...
3070 $bitfield |
= Revision
::DELETED_TEXT
;
3071 $bitfield |
= Revision
::DELETED_COMMENT
;
3072 $bitfield |
= Revision
::DELETED_USER
;
3073 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3075 $bitfield = 'rev_deleted';
3079 // For now, shunt the revision data into the archive table.
3080 // Text is *not* removed from the text table; bulk storage
3081 // is left intact to avoid breaking block-compression or
3082 // immutable storage schemes.
3084 // For backwards compatibility, note that some older archive
3085 // table entries will have ar_text and ar_flags fields still.
3087 // In the future, we may keep revisions and mark them with
3088 // the rev_deleted field, which is reserved for this purpose.
3089 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3091 'ar_namespace' => 'page_namespace',
3092 'ar_title' => 'page_title',
3093 'ar_comment' => 'rev_comment',
3094 'ar_user' => 'rev_user',
3095 'ar_user_text' => 'rev_user_text',
3096 'ar_timestamp' => 'rev_timestamp',
3097 'ar_minor_edit' => 'rev_minor_edit',
3098 'ar_rev_id' => 'rev_id',
3099 'ar_text_id' => 'rev_text_id',
3100 'ar_text' => '\'\'', // Be explicit to appease
3101 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3102 'ar_len' => 'rev_len',
3103 'ar_page_id' => 'page_id',
3104 'ar_deleted' => $bitfield
3107 'page_id = rev_page'
3111 # Delete restrictions for it
3112 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3114 # Now that it's safely backed up, delete it
3115 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3116 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3123 # Fix category table counts
3125 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3127 foreach ( $res as $row ) {
3128 $cats [] = $row->cl_to
;
3131 $this->updateCategoryCounts( array(), $cats );
3133 # If using cascading deletes, we can skip some explicit deletes
3134 if ( !$dbw->cascadingDeletes() ) {
3135 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3137 if ( $wgUseTrackbacks )
3138 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3140 # Delete outgoing links
3141 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3142 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3143 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3144 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3145 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3146 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3147 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3148 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3151 # If using cleanup triggers, we can skip some manual deletes
3152 if ( !$dbw->cleanupTriggers() ) {
3153 # Clean up recentchanges entries...
3154 $dbw->delete( 'recentchanges',
3155 array( 'rc_type != ' . RC_LOG
,
3156 'rc_namespace' => $this->mTitle
->getNamespace(),
3157 'rc_title' => $this->mTitle
->getDBkey() ),
3159 $dbw->delete( 'recentchanges',
3160 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3165 Article
::onArticleDelete( $this->mTitle
);
3167 # Clear the cached article id so the interface doesn't act like we exist
3168 $this->mTitle
->resetArticleID( 0 );
3170 # Log the deletion, if the page was suppressed, log it at Oversight instead
3171 $logtype = $suppress ?
'suppress' : 'delete';
3172 $log = new LogPage( $logtype );
3174 # Make sure logging got through
3175 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3181 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3186 * Roll back the most recent consecutive set of edits to a page
3187 * from the same user; fails if there are no eligible edits to
3188 * roll back to, e.g. user is the sole contributor. This function
3189 * performs permissions checks on $wgUser, then calls commitRollback()
3190 * to do the dirty work
3192 * @param $fromP String: Name of the user whose edits to rollback.
3193 * @param $summary String: Custom summary. Set to default summary if empty.
3194 * @param $token String: Rollback token.
3195 * @param $bot Boolean: If true, mark all reverted edits as bot.
3197 * @param $resultDetails Array: contains result-specific array of additional values
3198 * 'alreadyrolled' : 'current' (rev)
3199 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3201 * @return array of errors, each error formatted as
3202 * array(messagekey, param1, param2, ...).
3203 * On success, the array is empty. This array can also be passed to
3204 * OutputPage::showPermissionsErrorPage().
3206 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3209 $resultDetails = null;
3212 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3213 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3214 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3216 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3217 $errors[] = array( 'sessionfailure' );
3220 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3221 $errors[] = array( 'actionthrottledtext' );
3224 # If there were errors, bail out now
3225 if ( !empty( $errors ) ) {
3229 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3233 * Backend implementation of doRollback(), please refer there for parameter
3234 * and return value documentation
3236 * NOTE: This function does NOT check ANY permissions, it just commits the
3237 * rollback to the DB Therefore, you should only call this function direct-
3238 * ly if you want to use custom permissions checks. If you don't, use
3239 * doRollback() instead.
3241 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3242 global $wgUseRCPatrol, $wgUser, $wgLang;
3244 $dbw = wfGetDB( DB_MASTER
);
3246 if ( wfReadOnly() ) {
3247 return array( array( 'readonlytext' ) );
3250 # Get the last editor
3251 $current = Revision
::newFromTitle( $this->mTitle
);
3252 if ( is_null( $current ) ) {
3253 # Something wrong... no page?
3254 return array( array( 'notanarticle' ) );
3257 $from = str_replace( '_', ' ', $fromP );
3258 # User name given should match up with the top revision.
3259 # If the user was deleted then $from should be empty.
3260 if ( $from != $current->getUserText() ) {
3261 $resultDetails = array( 'current' => $current );
3262 return array( array( 'alreadyrolled',
3263 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3264 htmlspecialchars( $fromP ),
3265 htmlspecialchars( $current->getUserText() )
3269 # Get the last edit not by this guy...
3270 # Note: these may not be public values
3271 $user = intval( $current->getRawUser() );
3272 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3273 $s = $dbw->selectRow( 'revision',
3274 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3275 array( 'rev_page' => $current->getPage(),
3276 "rev_user != {$user} OR rev_user_text != {$user_text}"
3278 array( 'USE INDEX' => 'page_timestamp',
3279 'ORDER BY' => 'rev_timestamp DESC' )
3281 if ( $s === false ) {
3282 # No one else ever edited this page
3283 return array( array( 'cantrollback' ) );
3284 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3285 # Only admins can see this text
3286 return array( array( 'notvisiblerev' ) );
3290 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3291 # Mark all reverted edits as bot
3295 if ( $wgUseRCPatrol ) {
3296 # Mark all reverted edits as patrolled
3297 $set['rc_patrolled'] = 1;
3300 if ( count( $set ) ) {
3301 $dbw->update( 'recentchanges', $set,
3303 'rc_cur_id' => $current->getPage(),
3304 'rc_user_text' => $current->getUserText(),
3305 "rc_timestamp > '{$s->rev_timestamp}'",
3310 # Generate the edit summary if necessary
3311 $target = Revision
::newFromId( $s->rev_id
);
3312 if ( empty( $summary ) ) {
3313 if ( $from == '' ) { // no public user name
3314 $summary = wfMsgForContent( 'revertpage-nouser' );
3316 $summary = wfMsgForContent( 'revertpage' );
3320 # Allow the custom summary to use the same args as the default message
3322 $target->getUserText(), $from, $s->rev_id
,
3323 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3324 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3326 $summary = wfMsgReplaceArgs( $summary, $args );
3329 $flags = EDIT_UPDATE
;
3331 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3332 $flags |
= EDIT_MINOR
;
3335 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3336 $flags |
= EDIT_FORCE_BOT
;
3339 # Actually store the edit
3340 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3341 if ( !empty( $status->value
['revision'] ) ) {
3342 $revId = $status->value
['revision']->getId();
3347 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3349 $resultDetails = array(
3350 'summary' => $summary,
3351 'current' => $current,
3352 'target' => $target,
3360 * User interface for rollback operations
3362 public function rollback() {
3363 global $wgUser, $wgOut, $wgRequest;
3367 $result = $this->doRollback(
3368 $wgRequest->getVal( 'from' ),
3369 $wgRequest->getText( 'summary' ),
3370 $wgRequest->getVal( 'token' ),
3371 $wgRequest->getBool( 'bot' ),
3375 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3376 $wgOut->rateLimited();
3380 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3381 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3382 $errArray = $result[0];
3383 $errMsg = array_shift( $errArray );
3384 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3386 if ( isset( $details['current'] ) ) {
3387 $current = $details['current'];
3389 if ( $current->getComment() != '' ) {
3390 $wgOut->addWikiMsgArray( 'editcomment', array(
3391 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3398 # Display permissions errors before read-only message -- there's no
3399 # point in misleading the user into thinking the inability to rollback
3400 # is only temporary.
3401 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3402 # array_diff is completely broken for arrays of arrays, sigh.
3403 # Remove any 'readonlytext' error manually.
3405 foreach ( $result as $error ) {
3406 if ( $error != array( 'readonlytext' ) ) {
3410 $wgOut->showPermissionsErrorPage( $out );
3415 if ( $result == array( array( 'readonlytext' ) ) ) {
3416 $wgOut->readOnlyPage();
3421 $current = $details['current'];
3422 $target = $details['target'];
3423 $newId = $details['newid'];
3424 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3425 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3427 if ( $current->getUserText() === '' ) {
3428 $old = wfMsg( 'rev-deleted-user' );
3430 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
3431 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
3434 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
3435 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
3436 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3437 $wgOut->returnToMain( false, $this->mTitle
);
3439 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3440 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3441 $de->showDiff( '', '' );
3446 * Do standard deferred updates after page view
3448 public function viewUpdates() {
3449 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3450 if ( wfReadOnly() ) {
3454 # Don't update page view counters on views from bot users (bug 14044)
3455 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3456 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3457 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3460 # Update newtalk / watchlist notification status
3461 $wgUser->clearNotification( $this->mTitle
);
3465 * Prepare text which is about to be saved.
3466 * Returns a stdclass with source, pst and output members
3468 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3469 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3471 return $this->mPreparedEdit
;
3476 if( $user === null ) {
3480 $popts = ParserOptions
::newFromUser( $user );
3481 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3483 $edit = (object)array();
3484 $edit->revid
= $revid;
3485 $edit->newText
= $text;
3486 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3487 $edit->popts
= $this->getParserOptions( true );
3488 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3489 $edit->oldText
= $this->getRawText();
3491 $this->mPreparedEdit
= $edit;
3497 * Do standard deferred updates after page edit.
3498 * Update links tables, site stats, search index and message cache.
3499 * Purges pages that include this page if the text was changed here.
3500 * Every 100th edit, prune the recent changes table.
3503 * @param $text String: New text of the article
3504 * @param $summary String: Edit summary
3505 * @param $minoredit Boolean: Minor edit
3506 * @param $timestamp_of_pagechange String timestamp associated with the page change
3507 * @param $newid Integer: rev_id value of the new revision
3508 * @param $changed Boolean: Whether or not the content actually changed
3509 * @param $user User object: User doing the edit
3510 * @param $created Boolean: Whether the edit created the page
3512 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
3513 $changed = true, User
$user = null, $created = false )
3515 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3517 wfProfileIn( __METHOD__
);
3520 # Be careful not to double-PST: $text is usually already PST-ed once
3521 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3522 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3523 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3525 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3526 $editInfo = $this->mPreparedEdit
;
3529 # Save it to the parser cache
3530 if ( $wgEnableParserCache ) {
3531 $parserCache = ParserCache
::singleton();
3532 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3535 # Update the links tables
3536 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3539 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3541 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3542 if ( 0 == mt_rand( 0, 99 ) ) {
3543 // Flush old entries from the `recentchanges` table; we do this on
3544 // random requests so as to avoid an increase in writes for no good reason
3547 $dbw = wfGetDB( DB_MASTER
);
3548 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3551 array( "rc_timestamp < '$cutoff'" ),
3557 $id = $this->getID();
3558 $title = $this->mTitle
->getPrefixedDBkey();
3559 $shortTitle = $this->mTitle
->getDBkey();
3562 wfProfileOut( __METHOD__
);
3569 } elseif ( $created ) {
3570 $good = (int)$this->isCountable( $editInfo );
3573 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
3577 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
3578 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
3580 # If this is another user's talk page, update newtalk
3581 # Don't do this if $changed = false otherwise some idiot can null-edit a
3582 # load of user talk pages and piss people off, nor if it's a minor edit
3583 # by a properly-flagged bot.
3584 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3585 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3587 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3588 $other = User
::newFromName( $shortTitle, false );
3590 wfDebug( __METHOD__
. ": invalid username\n" );
3591 } elseif ( User
::isIP( $shortTitle ) ) {
3592 // An anonymous user
3593 $other->setNewtalk( true );
3594 } elseif ( $other->isLoggedIn() ) {
3595 $other->setNewtalk( true );
3597 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3602 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3603 MessageCache
::singleton()->replace( $shortTitle, $text );
3606 wfProfileOut( __METHOD__
);
3610 * Perform article updates on a special page creation.
3612 * @param $rev Revision object
3614 * @todo This is a shitty interface function. Kill it and replace the
3615 * other shitty functions like editUpdates and such so it's not needed
3618 public function createUpdates( $rev ) {
3619 $this->editUpdates( $rev->getText(), $rev->getComment(),
3620 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
3624 * Generate the navigation links when browsing through an article revisions
3625 * It shows the information as:
3626 * Revision as of \<date\>; view current revision
3627 * \<- Previous version | Next Version -\>
3629 * @param $oldid String: revision ID of this article revision
3631 public function setOldSubtitle( $oldid = 0 ) {
3632 global $wgLang, $wgOut, $wgUser, $wgRequest;
3634 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3638 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3640 # Cascade unhide param in links for easy deletion browsing
3641 $extraParams = array();
3642 if ( $wgRequest->getVal( 'unhide' ) ) {
3643 $extraParams['unhide'] = 1;
3646 $revision = Revision
::newFromId( $oldid );
3647 $timestamp = $revision->getTimestamp();
3649 $current = ( $oldid == $this->mLatest
);
3650 $td = $wgLang->timeanddate( $timestamp, true );
3651 $tddate = $wgLang->date( $timestamp, true );
3652 $tdtime = $wgLang->time( $timestamp, true );
3655 ?
wfMsgHtml( 'currentrevisionlink' )
3658 wfMsgHtml( 'currentrevisionlink' ),
3661 array( 'known', 'noclasses' )
3664 ?
wfMsgHtml( 'diff' )
3667 wfMsgHtml( 'diff' ),
3673 array( 'known', 'noclasses' )
3675 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3679 wfMsgHtml( 'previousrevision' ),
3682 'direction' => 'prev',
3685 array( 'known', 'noclasses' )
3687 : wfMsgHtml( 'previousrevision' );
3691 wfMsgHtml( 'diff' ),
3697 array( 'known', 'noclasses' )
3699 : wfMsgHtml( 'diff' );
3700 $nextlink = $current
3701 ?
wfMsgHtml( 'nextrevision' )
3704 wfMsgHtml( 'nextrevision' ),
3707 'direction' => 'next',
3710 array( 'known', 'noclasses' )
3712 $nextdiff = $current
3713 ?
wfMsgHtml( 'diff' )
3716 wfMsgHtml( 'diff' ),
3722 array( 'known', 'noclasses' )
3727 // User can delete revisions or view deleted revisions...
3728 $canHide = $wgUser->isAllowed( 'deleterevision' );
3729 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3730 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3731 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3734 'type' => 'revision',
3735 'target' => $this->mTitle
->getPrefixedDbkey(),
3738 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3743 # Show user links if allowed to see them. If hidden, then show them only if requested...
3744 $userlinks = Linker
::revUserTools( $revision, !$unhide );
3746 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3747 ?
'revision-info-current'
3750 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3753 array( 'parseinline', 'replaceafter' ),
3759 $revision->getUser()
3762 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3763 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3765 $wgOut->addHTML( $r );
3769 * This function is called right before saving the wikitext,
3770 * so we can do things like signatures and links-in-context.
3772 * @param $text String article contents
3773 * @param $user User object: user doing the edit, $wgUser will be used if
3775 * @param $popts ParserOptions object: parser options, default options for
3776 * the user loaded if null given
3777 * @return string article contents with altered wikitext markup (signatures
3778 * converted, {{subst:}}, templates, etc.)
3780 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3783 if ( $user === null ) {
3788 if ( $popts === null ) {
3789 $popts = ParserOptions
::newFromUser( $user );
3792 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3795 /* Caching functions */
3798 * checkLastModified returns true if it has taken care of all
3799 * output to the client that is necessary for this request.
3800 * (that is, it has sent a cached version of the page)
3802 * @return boolean true if cached version send, false otherwise
3804 protected function tryFileCache() {
3805 static $called = false;
3808 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3813 if ( $this->isFileCacheable() ) {
3814 $cache = new HTMLFileCache( $this->mTitle
);
3815 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3816 wfDebug( "Article::tryFileCache(): about to load file\n" );
3817 $cache->loadFromFileCache();
3820 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3821 ob_start( array( &$cache, 'saveToFileCache' ) );
3824 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3831 * Check if the page can be cached
3834 public function isFileCacheable() {
3837 if ( HTMLFileCache
::useFileCache() ) {
3838 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3839 // Extension may have reason to disable file caching on some pages.
3841 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3849 * Loads page_touched and returns a value indicating if it should be used
3850 * @return boolean true if not a redirect
3852 public function checkTouched() {
3853 if ( !$this->mDataLoaded
) {
3854 $this->loadPageData();
3857 return !$this->mIsRedirect
;
3861 * Get the page_touched field
3862 * @return string containing GMT timestamp
3864 public function getTouched() {
3865 if ( !$this->mDataLoaded
) {
3866 $this->loadPageData();
3869 return $this->mTouched
;
3873 * Get the page_latest field
3874 * @return integer rev_id of current revision
3876 public function getLatest() {
3877 if ( !$this->mDataLoaded
) {
3878 $this->loadPageData();
3881 return (int)$this->mLatest
;
3885 * Edit an article without doing all that other stuff
3886 * The article must already exist; link tables etc
3887 * are not updated, caches are not flushed.
3889 * @param $text String: text submitted
3890 * @param $comment String: comment submitted
3891 * @param $minor Boolean: whereas it's a minor modification
3893 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3894 wfProfileIn( __METHOD__
);
3896 $dbw = wfGetDB( DB_MASTER
);
3897 $revision = new Revision( array(
3898 'page' => $this->getId(),
3900 'comment' => $comment,
3901 'minor_edit' => $minor ?
1 : 0,
3903 $revision->insertOn( $dbw );
3904 $this->updateRevisionOn( $dbw, $revision );
3907 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3909 wfProfileOut( __METHOD__
);
3913 * The onArticle*() functions are supposed to be a kind of hooks
3914 * which should be called whenever any of the specified actions
3917 * This is a good place to put code to clear caches, for instance.
3919 * This is called on page move and undelete, as well as edit
3921 * @param $title Title object
3923 public static function onArticleCreate( $title ) {
3924 # Update existence markers on article/talk tabs...
3925 if ( $title->isTalkPage() ) {
3926 $other = $title->getSubjectPage();
3928 $other = $title->getTalkPage();
3931 $other->invalidateCache();
3932 $other->purgeSquid();
3934 $title->touchLinks();
3935 $title->purgeSquid();
3936 $title->deleteTitleProtection();
3940 * Clears caches when article is deleted
3942 * @param $title Title
3944 public static function onArticleDelete( $title ) {
3945 # Update existence markers on article/talk tabs...
3946 if ( $title->isTalkPage() ) {
3947 $other = $title->getSubjectPage();
3949 $other = $title->getTalkPage();
3952 $other->invalidateCache();
3953 $other->purgeSquid();
3955 $title->touchLinks();
3956 $title->purgeSquid();
3959 HTMLFileCache
::clearFileCache( $title );
3962 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3963 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3967 if ( $title->getNamespace() == NS_FILE
) {
3968 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3969 $update->doUpdate();
3973 if ( $title->getNamespace() == NS_USER_TALK
) {
3974 $user = User
::newFromName( $title->getText(), false );
3975 $user->setNewtalk( false );
3979 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3983 * Purge caches on page update etc
3985 * @param $title Title object
3986 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3988 public static function onArticleEdit( $title ) {
3989 global $wgDeferredUpdateList;
3991 // Invalidate caches of articles which include this page
3992 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3994 // Invalidate the caches of all pages which redirect here
3995 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3997 # Purge squid for this page only
3998 $title->purgeSquid();
4000 # Clear file cache for this page only
4001 HTMLFileCache
::clearFileCache( $title );
4007 * Overriden by ImagePage class, only present here to avoid a fatal error
4008 * Called for ?action=revert
4010 public function revert() {
4012 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4016 * Return a list of templates used by this article.
4017 * Uses the templatelinks table
4019 * @return Array of Title objects
4021 public function getUsedTemplates() {
4023 $id = $this->mTitle
->getArticleID();
4029 $dbr = wfGetDB( DB_SLAVE
);
4030 $res = $dbr->select( array( 'templatelinks' ),
4031 array( 'tl_namespace', 'tl_title' ),
4032 array( 'tl_from' => $id ),
4035 if ( $res !== false ) {
4036 foreach ( $res as $row ) {
4037 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4045 * Returns a list of hidden categories this page is a member of.
4046 * Uses the page_props and categorylinks tables.
4048 * @return Array of Title objects
4050 public function getHiddenCategories() {
4052 $id = $this->mTitle
->getArticleID();
4058 $dbr = wfGetDB( DB_SLAVE
);
4059 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4061 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4062 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4065 if ( $res !== false ) {
4066 foreach ( $res as $row ) {
4067 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4075 * Return an applicable autosummary if one exists for the given edit.
4076 * @param $oldtext String: the previous text of the page.
4077 * @param $newtext String: The submitted text of the page.
4078 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4079 * @return string An appropriate autosummary, or an empty string.
4081 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4084 # Decide what kind of autosummary is needed.
4086 # Redirect autosummaries
4087 $ot = Title
::newFromRedirect( $oldtext );
4088 $rt = Title
::newFromRedirect( $newtext );
4090 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4091 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4094 # New page autosummaries
4095 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4096 # If they're making a new article, give its text, truncated, in the summary.
4098 $truncatedtext = $wgContLang->truncate(
4099 str_replace( "\n", ' ', $newtext ),
4100 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4102 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4105 # Blanking autosummaries
4106 if ( $oldtext != '' && $newtext == '' ) {
4107 return wfMsgForContent( 'autosumm-blank' );
4108 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4109 # Removing more than 90% of the article
4111 $truncatedtext = $wgContLang->truncate(
4113 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4115 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4118 # If we reach this point, there's no applicable autosummary for our case, so our
4119 # autosummary is empty.
4124 * Add the primary page-view wikitext to the output buffer
4125 * Saves the text into the parser cache if possible.
4126 * Updates templatelinks if it is out of date.
4128 * @param $text String
4129 * @param $cache Boolean
4130 * @param $parserOptions mixed ParserOptions object, or boolean false
4132 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4135 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4136 $wgOut->addParserOutput( $this->mParserOutput
);
4140 * This does all the heavy lifting for outputWikitext, except it returns the parser
4141 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4142 * say, embedding thread pages within a discussion system (LiquidThreads)
4144 * @param $text string
4145 * @param $cache boolean
4146 * @param $parserOptions parsing options, defaults to false
4147 * @return string containing parsed output
4149 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4150 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4152 if ( !$parserOptions ) {
4153 $parserOptions = $this->getParserOptions();
4157 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4158 $parserOptions, true, true, $this->getRevIdFetched() );
4163 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4164 $this->mTitle
->getPrefixedDBkey() ) );
4167 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4168 $parserCache = ParserCache
::singleton();
4169 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4172 // Make sure file cache is not used on uncacheable content.
4173 // Output that has magic words in it can still use the parser cache
4174 // (if enabled), though it will generally expire sooner.
4175 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4176 $wgUseFileCache = false;
4179 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4181 return $this->mParserOutput
;
4185 * Get parser options suitable for rendering the primary article wikitext
4186 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
4187 * @return mixed ParserOptions object or boolean false
4189 public function getParserOptions( $canonical = false ) {
4190 global $wgUser, $wgLanguageCode;
4192 if ( !$this->mParserOptions ||
$canonical ) {
4193 $user = !$canonical ?
$wgUser : new User
;
4194 $parserOptions = new ParserOptions( $user );
4195 $parserOptions->setTidy( true );
4196 $parserOptions->enableLimitReport();
4199 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
4200 return $parserOptions;
4202 $this->mParserOptions
= $parserOptions;
4204 // Clone to allow modifications of the return value without affecting cache
4205 return clone $this->mParserOptions
;
4209 * Get parser options suitable for rendering the primary article wikitext
4211 * @return ParserOptions
4213 public function makeParserOptions( User
$user ) {
4214 $options = ParserOptions
::newFromUser( $user );
4215 $options->enableLimitReport(); // show inclusion/loop reports
4216 $options->setTidy( true ); // fix bad HTML
4221 * Updates cascading protections
4223 * @param $parserOutput ParserOutput object, or boolean false
4225 protected function doCascadeProtectionUpdates( $parserOutput ) {
4226 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4230 // templatelinks table may have become out of sync,
4231 // especially if using variable-based transclusions.
4232 // For paranoia, check if things have changed and if
4233 // so apply updates to the database. This will ensure
4234 // that cascaded protections apply as soon as the changes
4237 # Get templates from templatelinks
4238 $id = $this->mTitle
->getArticleID();
4240 $tlTemplates = array();
4242 $dbr = wfGetDB( DB_SLAVE
);
4243 $res = $dbr->select( array( 'templatelinks' ),
4244 array( 'tl_namespace', 'tl_title' ),
4245 array( 'tl_from' => $id ),
4249 foreach ( $res as $row ) {
4250 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4253 # Get templates from parser output.
4254 $poTemplates = array();
4255 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4256 foreach ( $templates as $dbk => $id ) {
4257 $poTemplates["$ns:$dbk"] = true;
4262 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4264 if ( count( $templates_diff ) > 0 ) {
4265 # Whee, link updates time.
4266 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4272 * Update all the appropriate counts in the category table, given that
4273 * we've added the categories $added and deleted the categories $deleted.
4275 * @param $added array The names of categories that were added
4276 * @param $deleted array The names of categories that were deleted
4278 public function updateCategoryCounts( $added, $deleted ) {
4279 $ns = $this->mTitle
->getNamespace();
4280 $dbw = wfGetDB( DB_MASTER
);
4282 # First make sure the rows exist. If one of the "deleted" ones didn't
4283 # exist, we might legitimately not create it, but it's simpler to just
4284 # create it and then give it a negative value, since the value is bogus
4287 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4288 $insertCats = array_merge( $added, $deleted );
4289 if ( !$insertCats ) {
4290 # Okay, nothing to do
4294 $insertRows = array();
4296 foreach ( $insertCats as $cat ) {
4297 $insertRows[] = array(
4298 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4302 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4304 $addFields = array( 'cat_pages = cat_pages + 1' );
4305 $removeFields = array( 'cat_pages = cat_pages - 1' );
4307 if ( $ns == NS_CATEGORY
) {
4308 $addFields[] = 'cat_subcats = cat_subcats + 1';
4309 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4310 } elseif ( $ns == NS_FILE
) {
4311 $addFields[] = 'cat_files = cat_files + 1';
4312 $removeFields[] = 'cat_files = cat_files - 1';
4319 array( 'cat_title' => $added ),
4328 array( 'cat_title' => $deleted ),
4335 * Lightweight method to get the parser output for a page, checking the parser cache
4336 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4337 * consider, so it's not appropriate to use there.
4339 * @since 1.16 (r52326) for LiquidThreads
4341 * @param $oldid mixed integer Revision ID or null
4342 * @return ParserOutput or false if the given revsion ID is not found
4344 public function getParserOutput( $oldid = null ) {
4345 global $wgEnableParserCache, $wgUser;
4347 // Should the parser cache be used?
4348 $useParserCache = $wgEnableParserCache &&
4349 $wgUser->getStubThreshold() == 0 &&
4353 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4355 if ( $wgUser->getStubThreshold() ) {
4356 wfIncrStats( 'pcache_miss_stub' );
4359 if ( $useParserCache ) {
4360 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4361 if ( $parserOutput !== false ) {
4362 return $parserOutput;
4366 // Cache miss; parse and output it.
4367 if ( $oldid === null ) {
4368 $text = $this->getRawText();
4370 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4371 if ( $rev === null ) {
4374 $text = $rev->getText();
4377 return $this->getOutputFromWikitext( $text, $useParserCache );
4381 * Sets the context this Article is executed in
4383 * @param $context RequestContext
4386 public function setContext( $context ) {
4387 $this->mContext
= $context;
4391 * Gets the context this Article is executed in
4393 * @return RequestContext
4396 public function getContext() {
4397 if ( $this->mContext
instanceof RequestContext
) {
4398 return $this->mContext
;
4400 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4401 return RequestContext
::getMain();
4407 class PoolWorkArticleView
extends PoolCounterWork
{
4414 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4415 parent
::__construct( 'ArticleView', $key );
4416 $this->mArticle
= $article;
4417 $this->cacheable
= $useParserCache;
4418 $this->parserOptions
= $parserOptions;
4422 return $this->mArticle
->doViewParse();
4425 function getCachedWork() {
4428 $parserCache = ParserCache
::singleton();
4429 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4431 if ( $this->mArticle
->mParserOutput
!== false ) {
4432 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4433 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4434 # Ensure that UI elements requiring revision ID have
4435 # the correct version information.
4436 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4442 function fallback() {
4443 return $this->mArticle
->tryDirtyCache();
4447 * @param $status Status
4449 function error( $status ) {
4452 $wgOut->clearHTML(); // for release() errors
4453 $wgOut->enableClientCache( false );
4454 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4456 $errortext = $status->getWikiText( false, 'view-pool-error' );
4457 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );