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, $wgContLang, $wgStylePath;
1629 if ( !is_array( $target ) ) {
1630 $target = array( $target );
1633 $imageDir = $wgContLang->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 = $wgContLang->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 wfProfileOut( __METHOD__
);
2355 * Output a redirect back to the article.
2356 * This is typically used after an edit.
2358 * @deprecated in 1.19; call $wgOut->redirect() directly
2359 * @param $noRedir Boolean: add redirect=no
2360 * @param $sectionAnchor String: section to redirect to, including "#"
2361 * @param $extraQuery String: extra query params
2363 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2364 wfDeprecated( __METHOD__
);
2368 $query = 'redirect=no';
2370 $query .= "&$extraQuery";
2372 $query = $extraQuery;
2375 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2379 * Update the article's restriction field, and leave a log entry.
2381 * @param $limit Array: set of restriction keys
2382 * @param $reason String
2383 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2384 * @param $expiry Array: per restriction type expiration
2385 * @return bool true on success
2387 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2388 global $wgUser, $wgContLang;
2390 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2392 $id = $this->mTitle
->getArticleID();
2395 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2399 if ( wfReadOnly() ) {
2400 wfDebug( "updateRestrictions failed: read-only\n" );
2404 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2405 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2413 // Take this opportunity to purge out expired restrictions
2414 Title
::purgeExpiredRestrictions();
2416 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2417 # we expect a single selection, but the schema allows otherwise.
2419 $updated = Article
::flattenRestrictions( $limit );
2422 foreach ( $restrictionTypes as $action ) {
2423 if ( isset( $expiry[$action] ) ) {
2424 # Get current restrictions on $action
2425 $aLimits = $this->mTitle
->getRestrictions( $action );
2426 $current[$action] = implode( '', $aLimits );
2427 # Are any actual restrictions being dealt with here?
2428 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2430 # If something changed, we need to log it. Checking $aRChanged
2431 # assures that "unprotecting" a page that is not protected does
2432 # not log just because the expiry was "changed".
2433 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2439 $current = Article
::flattenRestrictions( $current );
2441 $changed = ( $changed ||
$current != $updated );
2442 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2443 $protect = ( $updated != '' );
2445 # If nothing's changed, do nothing
2447 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2448 $dbw = wfGetDB( DB_MASTER
);
2450 # Prepare a null revision to be added to the history
2451 $modified = $current != '' && $protect;
2454 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2456 $comment_type = 'unprotectedarticle';
2459 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2461 # Only restrictions with the 'protect' right can cascade...
2462 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2463 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2465 # The schema allows multiple restrictions
2466 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2470 $cascade_description = '';
2473 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2477 $comment .= ": $reason";
2480 $editComment = $comment;
2481 $encodedExpiry = array();
2482 $protect_description = '';
2483 foreach ( $limit as $action => $restrictions ) {
2484 if ( !isset( $expiry[$action] ) )
2485 $expiry[$action] = $dbw->getInfinity();
2487 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2488 if ( $restrictions != '' ) {
2489 $protect_description .= "[$action=$restrictions] (";
2490 if ( $encodedExpiry[$action] != 'infinity' ) {
2491 $protect_description .= wfMsgForContent( 'protect-expiring',
2492 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2493 $wgContLang->date( $expiry[$action], false, false ) ,
2494 $wgContLang->time( $expiry[$action], false, false ) );
2496 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2499 $protect_description .= ') ';
2502 $protect_description = trim( $protect_description );
2504 if ( $protect_description && $protect ) {
2505 $editComment .= " ($protect_description)";
2509 $editComment .= "$cascade_description";
2512 # Update restrictions table
2513 foreach ( $limit as $action => $restrictions ) {
2514 if ( $restrictions != '' ) {
2515 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2516 array( 'pr_page' => $id,
2517 'pr_type' => $action,
2518 'pr_level' => $restrictions,
2519 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2520 'pr_expiry' => $encodedExpiry[$action]
2525 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2526 'pr_type' => $action ), __METHOD__
);
2530 # Insert a null revision
2531 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2532 $nullRevId = $nullRevision->insertOn( $dbw );
2534 $latest = $this->getLatest();
2535 # Update page record
2536 $dbw->update( 'page',
2538 'page_touched' => $dbw->timestamp(),
2539 'page_restrictions' => '',
2540 'page_latest' => $nullRevId
2541 ), array( /* WHERE */
2543 ), 'Article::protect'
2546 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2547 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2549 # Update the protection log
2550 $log = new LogPage( 'protect' );
2552 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2553 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2555 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2558 } # End "changed" check
2564 * Take an array of page restrictions and flatten it to a string
2565 * suitable for insertion into the page_restrictions field.
2566 * @param $limit Array
2569 protected static function flattenRestrictions( $limit ) {
2570 if ( !is_array( $limit ) ) {
2571 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2577 foreach ( $limit as $action => $restrictions ) {
2578 if ( $restrictions != '' ) {
2579 $bits[] = "$action=$restrictions";
2583 return implode( ':', $bits );
2587 * Auto-generates a deletion reason
2589 * @param &$hasHistory Boolean: whether the page has a history
2590 * @return mixed String containing deletion reason or empty string, or boolean false
2591 * if no revision occurred
2593 public function generateReason( &$hasHistory ) {
2596 $dbw = wfGetDB( DB_MASTER
);
2597 // Get the last revision
2598 $rev = Revision
::newFromTitle( $this->mTitle
);
2600 if ( is_null( $rev ) ) {
2604 // Get the article's contents
2605 $contents = $rev->getText();
2608 // If the page is blank, use the text from the previous revision,
2609 // which can only be blank if there's a move/import/protect dummy revision involved
2610 if ( $contents == '' ) {
2611 $prev = $rev->getPrevious();
2614 $contents = $prev->getText();
2619 // Find out if there was only one contributor
2620 // Only scan the last 20 revisions
2621 $res = $dbw->select( 'revision', 'rev_user_text',
2622 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2624 array( 'LIMIT' => 20 )
2627 if ( $res === false ) {
2628 // This page has no revisions, which is very weird
2632 $hasHistory = ( $res->numRows() > 1 );
2633 $row = $dbw->fetchObject( $res );
2635 if ( $row ) { // $row is false if the only contributor is hidden
2636 $onlyAuthor = $row->rev_user_text
;
2637 // Try to find a second contributor
2638 foreach ( $res as $row ) {
2639 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2640 $onlyAuthor = false;
2645 $onlyAuthor = false;
2648 // Generate the summary with a '$1' placeholder
2650 // The current revision is blank and the one before is also
2651 // blank. It's just not our lucky day
2652 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2654 if ( $onlyAuthor ) {
2655 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2657 $reason = wfMsgForContent( 'excontent', '$1' );
2661 if ( $reason == '-' ) {
2662 // Allow these UI messages to be blanked out cleanly
2666 // Replace newlines with spaces to prevent uglyness
2667 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2668 // Calculate the maximum amount of chars to get
2669 // Max content length = max comment length - length of the comment (excl. $1)
2670 $maxLength = 255 - ( strlen( $reason ) - 2 );
2671 $contents = $wgContLang->truncate( $contents, $maxLength );
2672 // Remove possible unfinished links
2673 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2674 // Now replace the '$1' placeholder
2675 $reason = str_replace( '$1', $contents, $reason );
2682 * UI entry point for page deletion
2684 public function delete() {
2685 global $wgOut, $wgRequest;
2687 $confirm = $wgRequest->wasPosted() &&
2688 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2690 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2691 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2693 $reason = $this->DeleteReasonList
;
2695 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2696 // Entry from drop down menu + additional comment
2697 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2698 } elseif ( $reason == 'other' ) {
2699 $reason = $this->DeleteReason
;
2702 # Flag to hide all contents of the archived revisions
2703 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2705 # This code desperately needs to be totally rewritten
2707 # Read-only check...
2708 if ( wfReadOnly() ) {
2709 $wgOut->readOnlyPage();
2715 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2717 if ( count( $permission_errors ) > 0 ) {
2718 $wgOut->showPermissionsErrorPage( $permission_errors );
2723 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2725 # Better double-check that it hasn't been deleted yet!
2726 $dbw = wfGetDB( DB_MASTER
);
2727 $conds = $this->mTitle
->pageCond();
2728 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2729 if ( $latest === false ) {
2730 $wgOut->showFatalError(
2733 array( 'class' => 'error mw-error-cannotdelete' ),
2734 wfMsgExt( 'cannotdelete', array( 'parse' ),
2735 wfEscapeWikiText( $this->mTitle
->getPrefixedText() ) )
2738 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2739 LogEventsList
::showLogExtract(
2742 $this->mTitle
->getPrefixedText()
2748 # Hack for big sites
2749 $bigHistory = $this->isBigDeletion();
2750 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2751 global $wgLang, $wgDeleteRevisionsLimit;
2753 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2754 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2760 $this->doDelete( $reason, $suppress );
2762 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2764 } elseif ( $this->mTitle
->userIsWatching() ) {
2771 // Generate deletion reason
2772 $hasHistory = false;
2774 $reason = $this->generateReason( $hasHistory );
2777 // If the page has a history, insert a warning
2778 if ( $hasHistory && !$confirm ) {
2781 $revisions = $this->estimateRevisionCount();
2782 // @todo FIXME: i18n issue/patchwork message
2783 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2784 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2785 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->mTitle
,
2786 wfMsgHtml( 'history' ),
2787 array( 'rel' => 'archives' ),
2788 array( 'action' => 'history' ) ) .
2792 if ( $bigHistory ) {
2793 global $wgDeleteRevisionsLimit;
2794 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2795 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2799 return $this->confirmDelete( $reason );
2803 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2805 public function isBigDeletion() {
2806 global $wgDeleteRevisionsLimit;
2808 if ( $wgDeleteRevisionsLimit ) {
2809 $revCount = $this->estimateRevisionCount();
2811 return $revCount > $wgDeleteRevisionsLimit;
2818 * @return int approximate revision count
2820 public function estimateRevisionCount() {
2821 $dbr = wfGetDB( DB_SLAVE
);
2823 // For an exact count...
2824 // return $dbr->selectField( 'revision', 'COUNT(*)',
2825 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2826 return $dbr->estimateRowCount( 'revision', '*',
2827 array( 'rev_page' => $this->getId() ), __METHOD__
);
2831 * Get the last N authors
2832 * @param $num Integer: number of revisions to get
2833 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2834 * @return array Array of authors, duplicates not removed
2836 public function getLastNAuthors( $num, $revLatest = 0 ) {
2837 wfProfileIn( __METHOD__
);
2838 // First try the slave
2839 // If that doesn't have the latest revision, try the master
2841 $db = wfGetDB( DB_SLAVE
);
2844 $res = $db->select( array( 'page', 'revision' ),
2845 array( 'rev_id', 'rev_user_text' ),
2847 'page_namespace' => $this->mTitle
->getNamespace(),
2848 'page_title' => $this->mTitle
->getDBkey(),
2849 'rev_page = page_id'
2852 'ORDER BY' => 'rev_timestamp DESC',
2858 wfProfileOut( __METHOD__
);
2862 $row = $db->fetchObject( $res );
2864 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2865 $db = wfGetDB( DB_MASTER
);
2870 } while ( $continue );
2872 $authors = array( $row->rev_user_text
);
2874 foreach ( $res as $row ) {
2875 $authors[] = $row->rev_user_text
;
2878 wfProfileOut( __METHOD__
);
2883 * Output deletion confirmation dialog
2884 * @todo FIXME: Move to another file?
2885 * @param $reason String: prefilled reason
2887 public function confirmDelete( $reason ) {
2890 wfDebug( "Article::confirmDelete\n" );
2892 $deleteBackLink = Linker
::linkKnown( $this->mTitle
);
2893 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2894 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2895 $wgOut->addWikiMsg( 'confirmdeletetext' );
2897 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2899 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2900 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2902 <td class='mw-input'><strong>" .
2903 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2904 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2910 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2912 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2913 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2914 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2915 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2916 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2917 "<tr id=\"wpDeleteReasonListRow\">
2918 <td class='mw-label'>" .
2919 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2921 <td class='mw-input'>" .
2922 Xml
::listDropDown( 'wpDeleteReasonList',
2923 wfMsgForContent( 'deletereason-dropdown' ),
2924 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2927 <tr id=\"wpDeleteReasonRow\">
2928 <td class='mw-label'>" .
2929 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2931 <td class='mw-input'>" .
2932 Html
::input( 'wpReason', $reason, 'text', array(
2934 'maxlength' => '255',
2942 # Disallow watching if user is not logged in
2943 if ( $wgOut->getUser()->isLoggedIn() ) {
2947 <td class='mw-input'>" .
2948 Xml
::checkLabel( wfMsg( 'watchthis' ),
2949 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2958 <td class='mw-submit'>" .
2959 Xml
::submitButton( wfMsg( 'deletepage' ),
2960 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2963 Xml
::closeElement( 'table' ) .
2964 Xml
::closeElement( 'fieldset' ) .
2965 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2966 Xml
::closeElement( 'form' );
2968 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2969 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2970 $link = Linker
::link(
2972 wfMsgHtml( 'delete-edit-reasonlist' ),
2974 array( 'action' => 'edit' )
2976 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2979 $wgOut->addHTML( $form );
2980 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2981 LogEventsList
::showLogExtract( $wgOut, 'delete',
2982 $this->mTitle
->getPrefixedText()
2987 * Perform a deletion and output success or failure messages
2989 public function doDelete( $reason, $suppress = false ) {
2992 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2995 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
2996 $deleted = $this->mTitle
->getPrefixedText();
2998 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2999 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3001 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3003 $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
3004 $wgOut->returnToMain( false );
3006 if ( $error == '' ) {
3007 $wgOut->showFatalError(
3010 array( 'class' => 'error mw-error-cannotdelete' ),
3011 wfMsgExt( 'cannotdelete', array( 'parse' ),
3012 wfEscapeWikiText( $this->mTitle
->getPrefixedText() ) )
3016 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3018 LogEventsList
::showLogExtract(
3021 $this->mTitle
->getPrefixedText()
3024 $wgOut->showFatalError( $error );
3030 * Back-end article deletion
3031 * Deletes the article with database consistency, writes logs, purges caches
3033 * @param $reason string delete reason for deletion log
3034 * @param suppress bitfield
3035 * Revision::DELETED_TEXT
3036 * Revision::DELETED_COMMENT
3037 * Revision::DELETED_USER
3038 * Revision::DELETED_RESTRICTED
3039 * @param $id int article ID
3040 * @param $commit boolean defaults to true, triggers transaction end
3041 * @return boolean true if successful
3043 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3044 global $wgDeferredUpdateList, $wgUseTrackbacks;
3047 wfDebug( __METHOD__
. "\n" );
3049 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3052 $dbw = wfGetDB( DB_MASTER
);
3053 $t = $this->mTitle
->getDBkey();
3054 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3056 if ( $t === '' ||
$id == 0 ) {
3060 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
3061 array_push( $wgDeferredUpdateList, $u );
3063 // Bitfields to further suppress the content
3066 // This should be 15...
3067 $bitfield |
= Revision
::DELETED_TEXT
;
3068 $bitfield |
= Revision
::DELETED_COMMENT
;
3069 $bitfield |
= Revision
::DELETED_USER
;
3070 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3072 $bitfield = 'rev_deleted';
3076 // For now, shunt the revision data into the archive table.
3077 // Text is *not* removed from the text table; bulk storage
3078 // is left intact to avoid breaking block-compression or
3079 // immutable storage schemes.
3081 // For backwards compatibility, note that some older archive
3082 // table entries will have ar_text and ar_flags fields still.
3084 // In the future, we may keep revisions and mark them with
3085 // the rev_deleted field, which is reserved for this purpose.
3086 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3088 'ar_namespace' => 'page_namespace',
3089 'ar_title' => 'page_title',
3090 'ar_comment' => 'rev_comment',
3091 'ar_user' => 'rev_user',
3092 'ar_user_text' => 'rev_user_text',
3093 'ar_timestamp' => 'rev_timestamp',
3094 'ar_minor_edit' => 'rev_minor_edit',
3095 'ar_rev_id' => 'rev_id',
3096 'ar_text_id' => 'rev_text_id',
3097 'ar_text' => '\'\'', // Be explicit to appease
3098 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3099 'ar_len' => 'rev_len',
3100 'ar_page_id' => 'page_id',
3101 'ar_deleted' => $bitfield
3104 'page_id = rev_page'
3108 # Delete restrictions for it
3109 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3111 # Now that it's safely backed up, delete it
3112 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3113 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3120 # Fix category table counts
3122 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3124 foreach ( $res as $row ) {
3125 $cats [] = $row->cl_to
;
3128 $this->updateCategoryCounts( array(), $cats );
3130 # If using cascading deletes, we can skip some explicit deletes
3131 if ( !$dbw->cascadingDeletes() ) {
3132 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3134 if ( $wgUseTrackbacks )
3135 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3137 # Delete outgoing links
3138 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3139 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3140 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3141 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3142 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3143 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3144 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3145 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3148 # If using cleanup triggers, we can skip some manual deletes
3149 if ( !$dbw->cleanupTriggers() ) {
3150 # Clean up recentchanges entries...
3151 $dbw->delete( 'recentchanges',
3152 array( 'rc_type != ' . RC_LOG
,
3153 'rc_namespace' => $this->mTitle
->getNamespace(),
3154 'rc_title' => $this->mTitle
->getDBkey() ),
3156 $dbw->delete( 'recentchanges',
3157 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3162 Article
::onArticleDelete( $this->mTitle
);
3164 # Clear the cached article id so the interface doesn't act like we exist
3165 $this->mTitle
->resetArticleID( 0 );
3167 # Log the deletion, if the page was suppressed, log it at Oversight instead
3168 $logtype = $suppress ?
'suppress' : 'delete';
3169 $log = new LogPage( $logtype );
3171 # Make sure logging got through
3172 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3178 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3183 * Roll back the most recent consecutive set of edits to a page
3184 * from the same user; fails if there are no eligible edits to
3185 * roll back to, e.g. user is the sole contributor. This function
3186 * performs permissions checks on $wgUser, then calls commitRollback()
3187 * to do the dirty work
3189 * @param $fromP String: Name of the user whose edits to rollback.
3190 * @param $summary String: Custom summary. Set to default summary if empty.
3191 * @param $token String: Rollback token.
3192 * @param $bot Boolean: If true, mark all reverted edits as bot.
3194 * @param $resultDetails Array: contains result-specific array of additional values
3195 * 'alreadyrolled' : 'current' (rev)
3196 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3198 * @return array of errors, each error formatted as
3199 * array(messagekey, param1, param2, ...).
3200 * On success, the array is empty. This array can also be passed to
3201 * OutputPage::showPermissionsErrorPage().
3203 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3206 $resultDetails = null;
3209 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3210 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3211 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3213 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3214 $errors[] = array( 'sessionfailure' );
3217 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3218 $errors[] = array( 'actionthrottledtext' );
3221 # If there were errors, bail out now
3222 if ( !empty( $errors ) ) {
3226 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3230 * Backend implementation of doRollback(), please refer there for parameter
3231 * and return value documentation
3233 * NOTE: This function does NOT check ANY permissions, it just commits the
3234 * rollback to the DB Therefore, you should only call this function direct-
3235 * ly if you want to use custom permissions checks. If you don't, use
3236 * doRollback() instead.
3238 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3239 global $wgUseRCPatrol, $wgUser, $wgLang;
3241 $dbw = wfGetDB( DB_MASTER
);
3243 if ( wfReadOnly() ) {
3244 return array( array( 'readonlytext' ) );
3247 # Get the last editor
3248 $current = Revision
::newFromTitle( $this->mTitle
);
3249 if ( is_null( $current ) ) {
3250 # Something wrong... no page?
3251 return array( array( 'notanarticle' ) );
3254 $from = str_replace( '_', ' ', $fromP );
3255 # User name given should match up with the top revision.
3256 # If the user was deleted then $from should be empty.
3257 if ( $from != $current->getUserText() ) {
3258 $resultDetails = array( 'current' => $current );
3259 return array( array( 'alreadyrolled',
3260 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3261 htmlspecialchars( $fromP ),
3262 htmlspecialchars( $current->getUserText() )
3266 # Get the last edit not by this guy...
3267 # Note: these may not be public values
3268 $user = intval( $current->getRawUser() );
3269 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3270 $s = $dbw->selectRow( 'revision',
3271 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3272 array( 'rev_page' => $current->getPage(),
3273 "rev_user != {$user} OR rev_user_text != {$user_text}"
3275 array( 'USE INDEX' => 'page_timestamp',
3276 'ORDER BY' => 'rev_timestamp DESC' )
3278 if ( $s === false ) {
3279 # No one else ever edited this page
3280 return array( array( 'cantrollback' ) );
3281 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3282 # Only admins can see this text
3283 return array( array( 'notvisiblerev' ) );
3287 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3288 # Mark all reverted edits as bot
3292 if ( $wgUseRCPatrol ) {
3293 # Mark all reverted edits as patrolled
3294 $set['rc_patrolled'] = 1;
3297 if ( count( $set ) ) {
3298 $dbw->update( 'recentchanges', $set,
3300 'rc_cur_id' => $current->getPage(),
3301 'rc_user_text' => $current->getUserText(),
3302 "rc_timestamp > '{$s->rev_timestamp}'",
3307 # Generate the edit summary if necessary
3308 $target = Revision
::newFromId( $s->rev_id
);
3309 if ( empty( $summary ) ) {
3310 if ( $from == '' ) { // no public user name
3311 $summary = wfMsgForContent( 'revertpage-nouser' );
3313 $summary = wfMsgForContent( 'revertpage' );
3317 # Allow the custom summary to use the same args as the default message
3319 $target->getUserText(), $from, $s->rev_id
,
3320 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3321 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3323 $summary = wfMsgReplaceArgs( $summary, $args );
3326 $flags = EDIT_UPDATE
;
3328 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3329 $flags |
= EDIT_MINOR
;
3332 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3333 $flags |
= EDIT_FORCE_BOT
;
3336 # Actually store the edit
3337 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3338 if ( !empty( $status->value
['revision'] ) ) {
3339 $revId = $status->value
['revision']->getId();
3344 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3346 $resultDetails = array(
3347 'summary' => $summary,
3348 'current' => $current,
3349 'target' => $target,
3357 * User interface for rollback operations
3359 public function rollback() {
3360 global $wgUser, $wgOut, $wgRequest;
3364 $result = $this->doRollback(
3365 $wgRequest->getVal( 'from' ),
3366 $wgRequest->getText( 'summary' ),
3367 $wgRequest->getVal( 'token' ),
3368 $wgRequest->getBool( 'bot' ),
3372 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3373 $wgOut->rateLimited();
3377 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3378 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3379 $errArray = $result[0];
3380 $errMsg = array_shift( $errArray );
3381 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3383 if ( isset( $details['current'] ) ) {
3384 $current = $details['current'];
3386 if ( $current->getComment() != '' ) {
3387 $wgOut->addWikiMsgArray( 'editcomment', array(
3388 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3395 # Display permissions errors before read-only message -- there's no
3396 # point in misleading the user into thinking the inability to rollback
3397 # is only temporary.
3398 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3399 # array_diff is completely broken for arrays of arrays, sigh.
3400 # Remove any 'readonlytext' error manually.
3402 foreach ( $result as $error ) {
3403 if ( $error != array( 'readonlytext' ) ) {
3407 $wgOut->showPermissionsErrorPage( $out );
3412 if ( $result == array( array( 'readonlytext' ) ) ) {
3413 $wgOut->readOnlyPage();
3418 $current = $details['current'];
3419 $target = $details['target'];
3420 $newId = $details['newid'];
3421 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3422 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3424 if ( $current->getUserText() === '' ) {
3425 $old = wfMsg( 'rev-deleted-user' );
3427 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
3428 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
3431 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
3432 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
3433 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3434 $wgOut->returnToMain( false, $this->mTitle
);
3436 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3437 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3438 $de->showDiff( '', '' );
3443 * Do standard deferred updates after page view
3445 public function viewUpdates() {
3446 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3447 if ( wfReadOnly() ) {
3451 # Don't update page view counters on views from bot users (bug 14044)
3452 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3453 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3454 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3457 # Update newtalk / watchlist notification status
3458 $wgUser->clearNotification( $this->mTitle
);
3462 * Prepare text which is about to be saved.
3463 * Returns a stdclass with source, pst and output members
3465 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3466 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3468 return $this->mPreparedEdit
;
3473 if( $user === null ) {
3477 $popts = ParserOptions
::newFromUser( $user );
3478 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3480 $edit = (object)array();
3481 $edit->revid
= $revid;
3482 $edit->newText
= $text;
3483 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3484 $edit->popts
= $this->getParserOptions( true );
3485 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3486 $edit->oldText
= $this->getRawText();
3488 $this->mPreparedEdit
= $edit;
3494 * Do standard deferred updates after page edit.
3495 * Update links tables, site stats, search index and message cache.
3496 * Purges pages that include this page if the text was changed here.
3497 * Every 100th edit, prune the recent changes table.
3500 * @param $text String: New text of the article
3501 * @param $summary String: Edit summary
3502 * @param $minoredit Boolean: Minor edit
3503 * @param $timestamp_of_pagechange String timestamp associated with the page change
3504 * @param $newid Integer: rev_id value of the new revision
3505 * @param $changed Boolean: Whether or not the content actually changed
3506 * @param $user User object: User doing the edit
3507 * @param $created Boolean: Whether the edit created the page
3509 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
3510 $changed = true, User
$user = null, $created = false )
3512 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3514 wfProfileIn( __METHOD__
);
3517 # Be careful not to double-PST: $text is usually already PST-ed once
3518 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3519 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3520 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3522 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3523 $editInfo = $this->mPreparedEdit
;
3526 # Save it to the parser cache
3527 if ( $wgEnableParserCache ) {
3528 $parserCache = ParserCache
::singleton();
3529 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3532 # Update the links tables
3533 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3536 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3538 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3539 if ( 0 == mt_rand( 0, 99 ) ) {
3540 // Flush old entries from the `recentchanges` table; we do this on
3541 // random requests so as to avoid an increase in writes for no good reason
3544 $dbw = wfGetDB( DB_MASTER
);
3545 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3548 array( "rc_timestamp < '$cutoff'" ),
3554 $id = $this->getID();
3555 $title = $this->mTitle
->getPrefixedDBkey();
3556 $shortTitle = $this->mTitle
->getDBkey();
3559 wfProfileOut( __METHOD__
);
3566 } elseif ( $created ) {
3567 $good = (int)$this->isCountable( $editInfo );
3570 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
3574 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
3575 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
3577 # If this is another user's talk page, update newtalk
3578 # Don't do this if $changed = false otherwise some idiot can null-edit a
3579 # load of user talk pages and piss people off, nor if it's a minor edit
3580 # by a properly-flagged bot.
3581 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3582 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3584 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3585 $other = User
::newFromName( $shortTitle, false );
3587 wfDebug( __METHOD__
. ": invalid username\n" );
3588 } elseif ( User
::isIP( $shortTitle ) ) {
3589 // An anonymous user
3590 $other->setNewtalk( true );
3591 } elseif ( $other->isLoggedIn() ) {
3592 $other->setNewtalk( true );
3594 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3599 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3600 MessageCache
::singleton()->replace( $shortTitle, $text );
3603 wfProfileOut( __METHOD__
);
3607 * Perform article updates on a special page creation.
3609 * @param $rev Revision object
3611 * @todo This is a shitty interface function. Kill it and replace the
3612 * other shitty functions like editUpdates and such so it's not needed
3615 public function createUpdates( $rev ) {
3616 $this->editUpdates( $rev->getText(), $rev->getComment(),
3617 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
3621 * Generate the navigation links when browsing through an article revisions
3622 * It shows the information as:
3623 * Revision as of \<date\>; view current revision
3624 * \<- Previous version | Next Version -\>
3626 * @param $oldid String: revision ID of this article revision
3628 public function setOldSubtitle( $oldid = 0 ) {
3629 global $wgLang, $wgOut, $wgUser, $wgRequest;
3631 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3635 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3637 # Cascade unhide param in links for easy deletion browsing
3638 $extraParams = array();
3639 if ( $wgRequest->getVal( 'unhide' ) ) {
3640 $extraParams['unhide'] = 1;
3643 $revision = Revision
::newFromId( $oldid );
3644 $timestamp = $revision->getTimestamp();
3646 $current = ( $oldid == $this->mLatest
);
3647 $td = $wgLang->timeanddate( $timestamp, true );
3648 $tddate = $wgLang->date( $timestamp, true );
3649 $tdtime = $wgLang->time( $timestamp, true );
3652 ?
wfMsgHtml( 'currentrevisionlink' )
3655 wfMsgHtml( 'currentrevisionlink' ),
3658 array( 'known', 'noclasses' )
3661 ?
wfMsgHtml( 'diff' )
3664 wfMsgHtml( 'diff' ),
3670 array( 'known', 'noclasses' )
3672 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3676 wfMsgHtml( 'previousrevision' ),
3679 'direction' => 'prev',
3682 array( 'known', 'noclasses' )
3684 : wfMsgHtml( 'previousrevision' );
3688 wfMsgHtml( 'diff' ),
3694 array( 'known', 'noclasses' )
3696 : wfMsgHtml( 'diff' );
3697 $nextlink = $current
3698 ?
wfMsgHtml( 'nextrevision' )
3701 wfMsgHtml( 'nextrevision' ),
3704 'direction' => 'next',
3707 array( 'known', 'noclasses' )
3709 $nextdiff = $current
3710 ?
wfMsgHtml( 'diff' )
3713 wfMsgHtml( 'diff' ),
3719 array( 'known', 'noclasses' )
3724 // User can delete revisions or view deleted revisions...
3725 $canHide = $wgUser->isAllowed( 'deleterevision' );
3726 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3727 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3728 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3731 'type' => 'revision',
3732 'target' => $this->mTitle
->getPrefixedDbkey(),
3735 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3740 # Show user links if allowed to see them. If hidden, then show them only if requested...
3741 $userlinks = Linker
::revUserTools( $revision, !$unhide );
3743 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3744 ?
'revision-info-current'
3747 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3750 array( 'parseinline', 'replaceafter' ),
3756 $revision->getUser()
3759 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3760 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3762 $wgOut->addHTML( $r );
3766 * This function is called right before saving the wikitext,
3767 * so we can do things like signatures and links-in-context.
3769 * @param $text String article contents
3770 * @param $user User object: user doing the edit, $wgUser will be used if
3772 * @param $popts ParserOptions object: parser options, default options for
3773 * the user loaded if null given
3774 * @return string article contents with altered wikitext markup (signatures
3775 * converted, {{subst:}}, templates, etc.)
3777 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3780 if ( $user === null ) {
3785 if ( $popts === null ) {
3786 $popts = ParserOptions
::newFromUser( $user );
3789 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3792 /* Caching functions */
3795 * checkLastModified returns true if it has taken care of all
3796 * output to the client that is necessary for this request.
3797 * (that is, it has sent a cached version of the page)
3799 * @return boolean true if cached version send, false otherwise
3801 protected function tryFileCache() {
3802 static $called = false;
3805 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3810 if ( $this->isFileCacheable() ) {
3811 $cache = new HTMLFileCache( $this->mTitle
);
3812 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3813 wfDebug( "Article::tryFileCache(): about to load file\n" );
3814 $cache->loadFromFileCache();
3817 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3818 ob_start( array( &$cache, 'saveToFileCache' ) );
3821 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3828 * Check if the page can be cached
3831 public function isFileCacheable() {
3834 if ( HTMLFileCache
::useFileCache() ) {
3835 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3836 // Extension may have reason to disable file caching on some pages.
3838 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3846 * Loads page_touched and returns a value indicating if it should be used
3847 * @return boolean true if not a redirect
3849 public function checkTouched() {
3850 if ( !$this->mDataLoaded
) {
3851 $this->loadPageData();
3854 return !$this->mIsRedirect
;
3858 * Get the page_touched field
3859 * @return string containing GMT timestamp
3861 public function getTouched() {
3862 if ( !$this->mDataLoaded
) {
3863 $this->loadPageData();
3866 return $this->mTouched
;
3870 * Get the page_latest field
3871 * @return integer rev_id of current revision
3873 public function getLatest() {
3874 if ( !$this->mDataLoaded
) {
3875 $this->loadPageData();
3878 return (int)$this->mLatest
;
3882 * Edit an article without doing all that other stuff
3883 * The article must already exist; link tables etc
3884 * are not updated, caches are not flushed.
3886 * @param $text String: text submitted
3887 * @param $comment String: comment submitted
3888 * @param $minor Boolean: whereas it's a minor modification
3890 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3891 wfProfileIn( __METHOD__
);
3893 $dbw = wfGetDB( DB_MASTER
);
3894 $revision = new Revision( array(
3895 'page' => $this->getId(),
3897 'comment' => $comment,
3898 'minor_edit' => $minor ?
1 : 0,
3900 $revision->insertOn( $dbw );
3901 $this->updateRevisionOn( $dbw, $revision );
3904 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3906 wfProfileOut( __METHOD__
);
3910 * The onArticle*() functions are supposed to be a kind of hooks
3911 * which should be called whenever any of the specified actions
3914 * This is a good place to put code to clear caches, for instance.
3916 * This is called on page move and undelete, as well as edit
3918 * @param $title Title object
3920 public static function onArticleCreate( $title ) {
3921 # Update existence markers on article/talk tabs...
3922 if ( $title->isTalkPage() ) {
3923 $other = $title->getSubjectPage();
3925 $other = $title->getTalkPage();
3928 $other->invalidateCache();
3929 $other->purgeSquid();
3931 $title->touchLinks();
3932 $title->purgeSquid();
3933 $title->deleteTitleProtection();
3937 * Clears caches when article is deleted
3939 * @param $title Title
3941 public static function onArticleDelete( $title ) {
3942 # Update existence markers on article/talk tabs...
3943 if ( $title->isTalkPage() ) {
3944 $other = $title->getSubjectPage();
3946 $other = $title->getTalkPage();
3949 $other->invalidateCache();
3950 $other->purgeSquid();
3952 $title->touchLinks();
3953 $title->purgeSquid();
3956 HTMLFileCache
::clearFileCache( $title );
3959 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3960 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3964 if ( $title->getNamespace() == NS_FILE
) {
3965 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3966 $update->doUpdate();
3970 if ( $title->getNamespace() == NS_USER_TALK
) {
3971 $user = User
::newFromName( $title->getText(), false );
3972 $user->setNewtalk( false );
3976 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3980 * Purge caches on page update etc
3982 * @param $title Title object
3983 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3985 public static function onArticleEdit( $title ) {
3986 global $wgDeferredUpdateList;
3988 // Invalidate caches of articles which include this page
3989 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3991 // Invalidate the caches of all pages which redirect here
3992 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3994 # Purge squid for this page only
3995 $title->purgeSquid();
3997 # Clear file cache for this page only
3998 HTMLFileCache
::clearFileCache( $title );
4004 * Overriden by ImagePage class, only present here to avoid a fatal error
4005 * Called for ?action=revert
4007 public function revert() {
4009 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4013 * Return a list of templates used by this article.
4014 * Uses the templatelinks table
4016 * @return Array of Title objects
4018 public function getUsedTemplates() {
4020 $id = $this->mTitle
->getArticleID();
4026 $dbr = wfGetDB( DB_SLAVE
);
4027 $res = $dbr->select( array( 'templatelinks' ),
4028 array( 'tl_namespace', 'tl_title' ),
4029 array( 'tl_from' => $id ),
4032 if ( $res !== false ) {
4033 foreach ( $res as $row ) {
4034 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4042 * Returns a list of hidden categories this page is a member of.
4043 * Uses the page_props and categorylinks tables.
4045 * @return Array of Title objects
4047 public function getHiddenCategories() {
4049 $id = $this->mTitle
->getArticleID();
4055 $dbr = wfGetDB( DB_SLAVE
);
4056 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4058 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4059 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4062 if ( $res !== false ) {
4063 foreach ( $res as $row ) {
4064 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4072 * Return an applicable autosummary if one exists for the given edit.
4073 * @param $oldtext String: the previous text of the page.
4074 * @param $newtext String: The submitted text of the page.
4075 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4076 * @return string An appropriate autosummary, or an empty string.
4078 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4081 # Decide what kind of autosummary is needed.
4083 # Redirect autosummaries
4084 $ot = Title
::newFromRedirect( $oldtext );
4085 $rt = Title
::newFromRedirect( $newtext );
4087 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4088 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4091 # New page autosummaries
4092 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4093 # If they're making a new article, give its text, truncated, in the summary.
4095 $truncatedtext = $wgContLang->truncate(
4096 str_replace( "\n", ' ', $newtext ),
4097 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4099 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4102 # Blanking autosummaries
4103 if ( $oldtext != '' && $newtext == '' ) {
4104 return wfMsgForContent( 'autosumm-blank' );
4105 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4106 # Removing more than 90% of the article
4108 $truncatedtext = $wgContLang->truncate(
4110 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4112 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4115 # If we reach this point, there's no applicable autosummary for our case, so our
4116 # autosummary is empty.
4121 * Add the primary page-view wikitext to the output buffer
4122 * Saves the text into the parser cache if possible.
4123 * Updates templatelinks if it is out of date.
4125 * @param $text String
4126 * @param $cache Boolean
4127 * @param $parserOptions mixed ParserOptions object, or boolean false
4129 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4132 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4133 $wgOut->addParserOutput( $this->mParserOutput
);
4137 * This does all the heavy lifting for outputWikitext, except it returns the parser
4138 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4139 * say, embedding thread pages within a discussion system (LiquidThreads)
4141 * @param $text string
4142 * @param $cache boolean
4143 * @param $parserOptions parsing options, defaults to false
4144 * @return string containing parsed output
4146 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4147 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4149 if ( !$parserOptions ) {
4150 $parserOptions = $this->getParserOptions();
4154 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4155 $parserOptions, true, true, $this->getRevIdFetched() );
4160 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4161 $this->mTitle
->getPrefixedDBkey() ) );
4164 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4165 $parserCache = ParserCache
::singleton();
4166 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4169 // Make sure file cache is not used on uncacheable content.
4170 // Output that has magic words in it can still use the parser cache
4171 // (if enabled), though it will generally expire sooner.
4172 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4173 $wgUseFileCache = false;
4176 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4178 return $this->mParserOutput
;
4182 * Get parser options suitable for rendering the primary article wikitext
4183 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
4184 * @return mixed ParserOptions object or boolean false
4186 public function getParserOptions( $canonical = false ) {
4187 global $wgUser, $wgLanguageCode;
4189 if ( !$this->mParserOptions ||
$canonical ) {
4190 $user = !$canonical ?
$wgUser : new User
;
4191 $parserOptions = new ParserOptions( $user );
4192 $parserOptions->setTidy( true );
4193 $parserOptions->enableLimitReport();
4196 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
4197 return $parserOptions;
4199 $this->mParserOptions
= $parserOptions;
4201 // Clone to allow modifications of the return value without affecting cache
4202 return clone $this->mParserOptions
;
4206 * Get parser options suitable for rendering the primary article wikitext
4208 * @return ParserOptions
4210 public function makeParserOptions( User
$user ) {
4211 $options = ParserOptions
::newFromUser( $user );
4212 $options->enableLimitReport(); // show inclusion/loop reports
4213 $options->setTidy( true ); // fix bad HTML
4218 * Updates cascading protections
4220 * @param $parserOutput ParserOutput object, or boolean false
4222 protected function doCascadeProtectionUpdates( $parserOutput ) {
4223 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4227 // templatelinks table may have become out of sync,
4228 // especially if using variable-based transclusions.
4229 // For paranoia, check if things have changed and if
4230 // so apply updates to the database. This will ensure
4231 // that cascaded protections apply as soon as the changes
4234 # Get templates from templatelinks
4235 $id = $this->mTitle
->getArticleID();
4237 $tlTemplates = array();
4239 $dbr = wfGetDB( DB_SLAVE
);
4240 $res = $dbr->select( array( 'templatelinks' ),
4241 array( 'tl_namespace', 'tl_title' ),
4242 array( 'tl_from' => $id ),
4246 foreach ( $res as $row ) {
4247 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4250 # Get templates from parser output.
4251 $poTemplates = array();
4252 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4253 foreach ( $templates as $dbk => $id ) {
4254 $poTemplates["$ns:$dbk"] = true;
4259 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4261 if ( count( $templates_diff ) > 0 ) {
4262 # Whee, link updates time.
4263 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4269 * Update all the appropriate counts in the category table, given that
4270 * we've added the categories $added and deleted the categories $deleted.
4272 * @param $added array The names of categories that were added
4273 * @param $deleted array The names of categories that were deleted
4275 public function updateCategoryCounts( $added, $deleted ) {
4276 $ns = $this->mTitle
->getNamespace();
4277 $dbw = wfGetDB( DB_MASTER
);
4279 # First make sure the rows exist. If one of the "deleted" ones didn't
4280 # exist, we might legitimately not create it, but it's simpler to just
4281 # create it and then give it a negative value, since the value is bogus
4284 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4285 $insertCats = array_merge( $added, $deleted );
4286 if ( !$insertCats ) {
4287 # Okay, nothing to do
4291 $insertRows = array();
4293 foreach ( $insertCats as $cat ) {
4294 $insertRows[] = array(
4295 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4299 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4301 $addFields = array( 'cat_pages = cat_pages + 1' );
4302 $removeFields = array( 'cat_pages = cat_pages - 1' );
4304 if ( $ns == NS_CATEGORY
) {
4305 $addFields[] = 'cat_subcats = cat_subcats + 1';
4306 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4307 } elseif ( $ns == NS_FILE
) {
4308 $addFields[] = 'cat_files = cat_files + 1';
4309 $removeFields[] = 'cat_files = cat_files - 1';
4316 array( 'cat_title' => $added ),
4325 array( 'cat_title' => $deleted ),
4332 * Lightweight method to get the parser output for a page, checking the parser cache
4333 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4334 * consider, so it's not appropriate to use there.
4336 * @since 1.16 (r52326) for LiquidThreads
4338 * @param $oldid mixed integer Revision ID or null
4339 * @return ParserOutput or false if the given revsion ID is not found
4341 public function getParserOutput( $oldid = null ) {
4342 global $wgEnableParserCache, $wgUser;
4344 // Should the parser cache be used?
4345 $useParserCache = $wgEnableParserCache &&
4346 $wgUser->getStubThreshold() == 0 &&
4350 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4352 if ( $wgUser->getStubThreshold() ) {
4353 wfIncrStats( 'pcache_miss_stub' );
4356 if ( $useParserCache ) {
4357 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4358 if ( $parserOutput !== false ) {
4359 return $parserOutput;
4363 // Cache miss; parse and output it.
4364 if ( $oldid === null ) {
4365 $text = $this->getRawText();
4367 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4368 if ( $rev === null ) {
4371 $text = $rev->getText();
4374 return $this->getOutputFromWikitext( $text, $useParserCache );
4378 * Sets the context this Article is executed in
4380 * @param $context RequestContext
4383 public function setContext( $context ) {
4384 $this->mContext
= $context;
4388 * Gets the context this Article is executed in
4390 * @return RequestContext
4393 public function getContext() {
4394 if ( $this->mContext
instanceof RequestContext
) {
4395 return $this->mContext
;
4397 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4398 return RequestContext
::getMain();
4404 class PoolWorkArticleView
extends PoolCounterWork
{
4411 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4412 parent
::__construct( 'ArticleView', $key );
4413 $this->mArticle
= $article;
4414 $this->cacheable
= $useParserCache;
4415 $this->parserOptions
= $parserOptions;
4419 return $this->mArticle
->doViewParse();
4422 function getCachedWork() {
4425 $parserCache = ParserCache
::singleton();
4426 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4428 if ( $this->mArticle
->mParserOutput
!== false ) {
4429 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4430 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4431 # Ensure that UI elements requiring revision ID have
4432 # the correct version information.
4433 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4439 function fallback() {
4440 return $this->mArticle
->tryDirtyCache();
4444 * @param $status Status
4446 function error( $status ) {
4449 $wgOut->clearHTML(); // for release() errors
4450 $wgOut->enableClientCache( false );
4451 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4453 $errortext = $status->getWikiText( false, 'view-pool-error' );
4454 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );