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
20 protected $mContext; // !< RequestContext
23 var $mContentLoaded = false; // !<
24 var $mCounter = -1; // !< Not loaded
25 var $mDataLoaded = false; // !<
26 var $mForUpdate = false; // !<
27 var $mGoodAdjustment = 0; // !<
28 var $mIsRedirect = false; // !<
29 var $mLatest = false; // !<
31 var $mPreparedEdit = false; // !< Title object if set
32 var $mRedirectedFrom = null; // !< Title object if set
33 var $mRedirectTarget = null; // !< Title object if set
34 var $mRedirectUrl = false; // !<
35 var $mRevIdFetched = 0; // !<
36 var $mLastRevision = null; // !< Latest revision if set
37 var $mRevision = null; // !< Loaded revision object if set
38 var $mTimestamp = ''; // !<
39 var $mTitle; // !< Title object
40 var $mTotalAdjustment = 0; // !<
41 var $mTouched = '19700101000000'; // !<
42 var $mParserOptions; // !< ParserOptions object
43 var $mParserOutput; // !< ParserCache object if set
47 * Constructor and clear the article
48 * @param $title Reference to a Title object.
49 * @param $oldId Integer revision ID, null to fetch from request, zero for current
51 public function __construct( Title
$title, $oldId = null ) {
52 // FIXME: does the reference play any role here?
53 $this->mTitle
=& $title;
54 $this->mOldId
= $oldId;
58 * Constructor from an page id
59 * @param $id Int article ID to load
61 public static function newFromID( $id ) {
62 $t = Title
::newFromID( $id );
63 # FIXME: doesn't inherit right
64 return $t == null ?
null : new self( $t );
65 # return $t == null ? null : new static( $t ); // PHP 5.3
69 * Tell the page view functions that this view was redirected
70 * from another page on the wiki.
71 * @param $from Title object.
73 public function setRedirectedFrom( Title
$from ) {
74 $this->mRedirectedFrom
= $from;
78 * If this page is a redirect, get its target
80 * The target will be fetched from the redirect table if possible.
81 * If this page doesn't have an entry there, call insertRedirect()
82 * @return mixed Title object, or null if this page is not a redirect
84 public function getRedirectTarget() {
85 if ( !$this->mTitle
->isRedirect() ) {
89 if ( $this->mRedirectTarget
!== null ) {
90 return $this->mRedirectTarget
;
93 # Query the redirect table
94 $dbr = wfGetDB( DB_SLAVE
);
95 $row = $dbr->selectRow( 'redirect',
96 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
97 array( 'rd_from' => $this->getID() ),
101 // rd_fragment and rd_interwiki were added later, populate them if empty
102 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
103 return $this->mRedirectTarget
= Title
::makeTitle(
104 $row->rd_namespace
, $row->rd_title
,
105 $row->rd_fragment
, $row->rd_interwiki
);
108 # This page doesn't have an entry in the redirect table
109 return $this->mRedirectTarget
= $this->insertRedirect();
113 * Insert an entry for this page into the redirect table.
115 * Don't call this function directly unless you know what you're doing.
116 * @return Title object or null if not a redirect
118 public function insertRedirect() {
119 // recurse through to only get the final target
120 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
124 $this->insertRedirectEntry( $retval );
129 * Insert or update the redirect table entry for this page to indicate
130 * it redirects to $rt .
131 * @param $rt Title redirect target
133 public function insertRedirectEntry( $rt ) {
134 $dbw = wfGetDB( DB_MASTER
);
135 $dbw->replace( 'redirect', array( 'rd_from' ),
137 'rd_from' => $this->getID(),
138 'rd_namespace' => $rt->getNamespace(),
139 'rd_title' => $rt->getDBkey(),
140 'rd_fragment' => $rt->getFragment(),
141 'rd_interwiki' => $rt->getInterwiki(),
148 * Get the Title object or URL this page redirects to
150 * @return mixed false, Title of in-wiki target, or string with URL
152 public function followRedirect() {
153 return $this->getRedirectURL( $this->getRedirectTarget() );
157 * Get the Title object this text redirects to
159 * @param $text string article content containing redirect info
160 * @return mixed false, Title of in-wiki target, or string with URL
161 * @deprecated since 1.17
163 public function followRedirectText( $text ) {
164 // recurse through to only get the final target
165 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
169 * Get the Title object or URL to use for a redirect. We use Title
170 * objects for same-wiki, non-special redirects and URLs for everything
172 * @param $rt Title Redirect target
173 * @return mixed false, Title object of local target, or string with URL
175 public function getRedirectURL( $rt ) {
177 if ( $rt->getInterwiki() != '' ) {
178 if ( $rt->isLocal() ) {
179 // Offsite wikis need an HTTP redirect.
181 // This can be hard to reverse and may produce loops,
182 // so they may be disabled in the site configuration.
183 $source = $this->mTitle
->getFullURL( 'redirect=no' );
184 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
187 if ( $rt->getNamespace() == NS_SPECIAL
) {
188 // Gotta handle redirects to special pages differently:
189 // Fill the HTTP response "Location" header and ignore
190 // the rest of the page we're on.
192 // This can be hard to reverse, so they may be disabled.
193 if ( $rt->isSpecial( 'Userlogout' ) ) {
196 return $rt->getFullURL();
204 // No or invalid redirect
209 * Get the title object of the article
210 * @return Title object of this page
212 public function getTitle() {
213 return $this->mTitle
;
218 * FIXME: shouldn't this be public?
221 public function clear() {
222 $this->mDataLoaded
= false;
223 $this->mContentLoaded
= false;
225 $this->mCounter
= -1; # Not loaded
226 $this->mRedirectedFrom
= null; # Title object if set
227 $this->mRedirectTarget
= null; # Title object if set
228 $this->mLastRevision
= null; # Latest revision
229 $this->mTimestamp
= '';
230 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
231 $this->mTouched
= '19700101000000';
232 $this->mForUpdate
= false;
233 $this->mIsRedirect
= false;
234 $this->mRevIdFetched
= 0;
235 $this->mRedirectUrl
= false;
236 $this->mLatest
= false;
237 $this->mPreparedEdit
= false;
241 * Note that getContent/loadContent do not follow redirects anymore.
242 * If you need to fetch redirectable content easily, try
243 * the shortcut in Article::followRedirect()
245 * This function has side effects! Do not use this function if you
246 * only want the real revision text if any.
248 * @return Return the text of this revision
250 public function getContent() {
253 wfProfileIn( __METHOD__
);
255 if ( $this->getID() === 0 ) {
256 # If this is a MediaWiki:x message, then load the messages
257 # and return the message value for x.
258 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
259 $text = $this->mTitle
->getDefaultMessageText();
260 if ( $text === false ) {
264 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
266 wfProfileOut( __METHOD__
);
270 $this->loadContent();
271 wfProfileOut( __METHOD__
);
273 return $this->mContent
;
278 * Get the text of the current revision. No side-effects...
280 * @return Return the text of the current revision
282 public function getRawText() {
283 // Check process cache for current revision
284 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
285 return $this->mContent
;
288 $rev = Revision
::newFromTitle( $this->mTitle
);
289 $text = $rev ?
$rev->getRawText() : false;
295 * This function returns the text of a section, specified by a number ($section).
296 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
297 * the first section before any such heading (section 0).
299 * If a section contains subsections, these are also returned.
301 * @param $text String: text to look in
302 * @param $section Integer: section number
303 * @return string text of the requested section
306 public function getSection( $text, $section ) {
308 return $wgParser->getSection( $text, $section );
312 * Get the text that needs to be saved in order to undo all revisions
313 * between $undo and $undoafter. Revisions must belong to the same page,
314 * must exist and must not be deleted
315 * @param $undo Revision
316 * @param $undoafter Revision Must be an earlier revision than $undo
317 * @return mixed string on success, false on failure
319 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
320 $currentRev = Revision
::newFromTitle( $this->mTitle
);
321 if ( !$currentRev ) {
322 return false; // no page
324 $undo_text = $undo->getText();
325 $undoafter_text = $undoafter->getText();
326 $cur_text = $currentRev->getText();
328 if ( $cur_text == $undo_text ) {
329 # No use doing a merge if it's just a straight revert.
330 return $undoafter_text;
335 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
343 * @return int The oldid of the article that is to be shown, 0 for the
346 public function getOldID() {
347 if ( is_null( $this->mOldId
) ) {
348 $this->mOldId
= $this->getOldIDFromRequest();
351 return $this->mOldId
;
355 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
357 * @return int The old id for the request
359 public function getOldIDFromRequest() {
362 $this->mRedirectUrl
= false;
364 $oldid = $wgRequest->getVal( 'oldid' );
366 if ( isset( $oldid ) ) {
367 $oldid = intval( $oldid );
368 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
369 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
373 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
375 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
376 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
391 * Load the revision (including text) into this object
393 function loadContent() {
394 if ( $this->mContentLoaded
) {
398 wfProfileIn( __METHOD__
);
400 $this->fetchContent( $this->getOldID() );
402 wfProfileOut( __METHOD__
);
406 * Return the list of revision fields that should be selected to create
409 public static function selectFields() {
426 * Fetch a page record with the given conditions
427 * @param $dbr Database object
428 * @param $conditions Array
429 * @return mixed Database result resource, or false on failure
431 protected function pageData( $dbr, $conditions ) {
432 $fields = self
::selectFields();
434 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
436 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
438 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
444 * Fetch a page record matching the Title object's namespace and title
445 * using a sanitized title string
447 * @param $dbr Database object
448 * @param $title Title object
449 * @return mixed Database result resource, or false on failure
451 protected function pageDataFromTitle( $dbr, $title ) {
452 return $this->pageData( $dbr, array(
453 'page_namespace' => $title->getNamespace(),
454 'page_title' => $title->getDBkey() ) );
458 * Fetch a page record matching the requested ID
460 * @param $dbr Database
462 * @return mixed Database result resource, or false on failure
464 protected function pageDataFromId( $dbr, $id ) {
465 return $this->pageData( $dbr, array( 'page_id' => $id ) );
469 * Set the general counter, title etc data loaded from
472 * @param $data Database row object or "fromdb"
474 public function loadPageData( $data = 'fromdb' ) {
475 if ( $data === 'fromdb' ) {
476 $dbr = wfGetDB( DB_SLAVE
);
477 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
480 $lc = LinkCache
::singleton();
483 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
485 $this->mTitle
->mArticleID
= intval( $data->page_id
);
487 # Old-fashioned restrictions
488 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
490 $this->mCounter
= intval( $data->page_counter
);
491 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
492 $this->mIsRedirect
= intval( $data->page_is_redirect
);
493 $this->mLatest
= intval( $data->page_latest
);
495 $lc->addBadLinkObj( $this->mTitle
);
496 $this->mTitle
->mArticleID
= 0;
499 $this->mDataLoaded
= true;
503 * Get text of an article from database
504 * Does *NOT* follow redirects.
506 * @param $oldid Int: 0 for whatever the latest revision is
507 * @return mixed string containing article contents, or false if null
509 function fetchContent( $oldid = 0 ) {
510 if ( $this->mContentLoaded
) {
511 return $this->mContent
;
514 # Pre-fill content with error message so that if something
515 # fails we'll have something telling us what we intended.
516 $t = $this->mTitle
->getPrefixedText();
517 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
518 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
521 $revision = Revision
::newFromId( $oldid );
522 if ( $revision === null ) {
523 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
527 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
528 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
531 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
535 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
536 $this->loadPageData( $data );
539 if ( !$this->mDataLoaded
) {
540 $this->loadPageData();
543 if ( $this->mLatest
=== false ) {
544 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
548 $revision = Revision
::newFromId( $this->mLatest
);
549 if ( $revision === null ) {
550 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
555 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
556 // We should instead work with the Revision object when we need it...
557 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
559 if ( $revision->getId() == $this->mLatest
) {
560 $this->setLastEdit( $revision );
563 $this->mRevIdFetched
= $revision->getId();
564 $this->mContentLoaded
= true;
565 $this->mRevision
=& $revision;
567 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
569 return $this->mContent
;
573 * Read/write accessor to select FOR UPDATE
574 * @FIXME: remove, does nothing
576 * @param $x Mixed: FIXME
577 * @return mixed value of $x, or value stored in Article::mForUpdate
579 public function forUpdate( $x = null ) {
581 return wfSetVar( $this->mForUpdate
, $x );
585 * @return int Page ID
587 public function getID() {
588 return $this->mTitle
->getArticleID();
592 * @return bool Whether or not the page exists in the database
594 public function exists() {
595 return $this->getId() > 0;
599 * Check if this page is something we're going to be showing
600 * some sort of sensible content for. If we return false, page
601 * views (plain action=view) will return an HTTP 404 response,
602 * so spiders and robots can know they're following a bad link.
606 public function hasViewableContent() {
607 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
611 * @return int The view count for the page
613 public function getCount() {
614 if ( -1 == $this->mCounter
) {
615 $id = $this->getID();
620 $dbr = wfGetDB( DB_SLAVE
);
621 $this->mCounter
= $dbr->selectField( 'page',
623 array( 'page_id' => $id ),
629 return $this->mCounter
;
633 * Determine whether a page would be suitable for being counted as an
634 * article in the site_stats table based on the title & its content
636 * @param $text String: text to analyze
639 public function isCountable( $text ) {
640 global $wgUseCommaCount;
642 $token = $wgUseCommaCount ?
',' : '[[';
644 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
648 * Tests if the article text represents a redirect
650 * @param $text mixed string containing article contents, or boolean
653 public function isRedirect( $text = false ) {
654 if ( $text === false ) {
655 if ( !$this->mDataLoaded
) {
656 $this->loadPageData();
659 return (bool)$this->mIsRedirect
;
661 return Title
::newFromRedirect( $text ) !== null;
666 * Returns true if the currently-referenced revision is the current edit
667 * to this page (and it exists).
670 public function isCurrent() {
671 # If no oldid, this is the current version.
672 if ( $this->getOldID() == 0 ) {
676 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
680 * Loads everything except the text
681 * This isn't necessary for all uses, so it's only done if needed.
683 protected function loadLastEdit() {
684 if ( $this->mLastRevision
!== null ) {
685 return; // already loaded
688 # New or non-existent articles have no user information
689 $id = $this->getID();
694 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
696 $this->setLastEdit( $revision );
701 * Set the latest revision
703 protected function setLastEdit( Revision
$revision ) {
704 $this->mLastRevision
= $revision;
705 $this->mTimestamp
= $revision->getTimestamp();
709 * @return string GMT timestamp of last article revision
711 public function getTimestamp() {
712 // Check if the field has been filled by ParserCache::get()
713 if ( !$this->mTimestamp
) {
714 $this->loadLastEdit();
716 return wfTimestamp( TS_MW
, $this->mTimestamp
);
720 * @param $audience Integer: one of:
721 * Revision::FOR_PUBLIC to be displayed to all users
722 * Revision::FOR_THIS_USER to be displayed to $wgUser
723 * Revision::RAW get the text regardless of permissions
724 * @return int user ID for the user that made the last article revision
726 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
727 $this->loadLastEdit();
728 if ( $this->mLastRevision
) {
729 return $this->mLastRevision
->getUser( $audience );
736 * @param $audience Integer: one of:
737 * Revision::FOR_PUBLIC to be displayed to all users
738 * Revision::FOR_THIS_USER to be displayed to $wgUser
739 * Revision::RAW get the text regardless of permissions
740 * @return string username of the user that made the last article revision
742 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
743 $this->loadLastEdit();
744 if ( $this->mLastRevision
) {
745 return $this->mLastRevision
->getUserText( $audience );
752 * @param $audience Integer: one of:
753 * Revision::FOR_PUBLIC to be displayed to all users
754 * Revision::FOR_THIS_USER to be displayed to $wgUser
755 * Revision::RAW get the text regardless of permissions
756 * @return string Comment stored for the last article revision
758 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
759 $this->loadLastEdit();
760 if ( $this->mLastRevision
) {
761 return $this->mLastRevision
->getComment( $audience );
768 * Returns true if last revision was marked as "minor edit"
770 * @return boolean Minor edit indicator for the last article revision.
772 public function getMinorEdit() {
773 $this->loadLastEdit();
774 if ( $this->mLastRevision
) {
775 return $this->mLastRevision
->isMinor();
782 * Use this to fetch the rev ID used on page views
784 * @return int revision ID of last article revision
786 public function getRevIdFetched() {
787 if ( $this->mRevIdFetched
) {
788 return $this->mRevIdFetched
;
790 return $this->getLatest();
795 * Get a list of users who have edited this article, not including the user who made
796 * the most recent revision, which you can get from $article->getUser() if you want it
799 public function getContributors() {
800 # FIXME: this is expensive; cache this info somewhere.
802 $dbr = wfGetDB( DB_SLAVE
);
803 $userTable = $dbr->tableName( 'user' );
805 $tables = array( 'revision', 'user' );
809 'rev_user_text AS user_name',
810 'MAX(rev_timestamp) AS timestamp',
813 $conds = array( 'rev_page' => $this->getId() );
815 // The user who made the top revision gets credited as "this page was last edited by
816 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
817 $user = $this->getUser();
819 $conds[] = "rev_user != $user";
821 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
824 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
827 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
831 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
832 'ORDER BY' => 'timestamp DESC',
835 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
836 return new UserArrayFromResult( $res );
840 * This is the default action of the index.php entry point: just view the
841 * page of the given title.
843 public function view() {
844 global $wgUser, $wgOut, $wgRequest, $wgParser;
845 global $wgUseFileCache, $wgUseETag;
847 wfProfileIn( __METHOD__
);
849 # Get variables from query string
850 $oldid = $this->getOldID();
852 # getOldID may want us to redirect somewhere else
853 if ( $this->mRedirectUrl
) {
854 $wgOut->redirect( $this->mRedirectUrl
);
855 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
856 wfProfileOut( __METHOD__
);
861 $wgOut->setArticleFlag( true );
862 # Set page title (may be overridden by DISPLAYTITLE)
863 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
865 # If we got diff in the query, we want to see a diff page instead of the article.
866 if ( $wgRequest->getCheck( 'diff' ) ) {
867 wfDebug( __METHOD__
. ": showing diff page\n" );
868 $this->showDiffPage();
869 wfProfileOut( __METHOD__
);
874 # Allow frames by default
875 $wgOut->allowClickjacking();
877 $parserCache = ParserCache
::singleton();
879 $parserOptions = $this->getParserOptions();
880 # Render printable version, use printable version cache
881 if ( $wgOut->isPrintable() ) {
882 $parserOptions->setIsPrintable( true );
883 $parserOptions->setEditSection( false );
884 } else if ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
885 $parserOptions->setEditSection( false );
888 # Try client and file cache
889 if ( $oldid === 0 && $this->checkTouched() ) {
891 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
894 # Is it client cached?
895 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
896 wfDebug( __METHOD__
. ": done 304\n" );
897 wfProfileOut( __METHOD__
);
901 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
902 wfDebug( __METHOD__
. ": done file cache\n" );
903 # tell wgOut that output is taken care of
905 $this->viewUpdates();
906 wfProfileOut( __METHOD__
);
912 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
913 $parserOptions->setEditSection( false );
916 # Should the parser cache be used?
917 $useParserCache = $this->useParserCache( $oldid );
918 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
919 if ( $wgUser->getStubThreshold() ) {
920 wfIncrStats( 'pcache_miss_stub' );
923 $wasRedirected = $this->showRedirectedFromHeader();
924 $this->showNamespaceHeader();
926 # Iterate through the possible ways of constructing the output text.
927 # Keep going until $outputDone is set, or we run out of things to do.
930 $this->mParserOutput
= false;
932 while ( !$outputDone && ++
$pass ) {
935 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
938 # Try the parser cache
939 if ( $useParserCache ) {
940 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
942 if ( $this->mParserOutput
!== false ) {
943 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
944 $wgOut->addParserOutput( $this->mParserOutput
);
945 # Ensure that UI elements requiring revision ID have
946 # the correct version information.
947 $wgOut->setRevisionId( $this->mLatest
);
953 $text = $this->getContent();
954 if ( $text === false ||
$this->getID() == 0 ) {
955 wfDebug( __METHOD__
. ": showing missing article\n" );
956 $this->showMissingArticle();
957 wfProfileOut( __METHOD__
);
961 # Another whitelist check in case oldid is altering the title
962 if ( !$this->mTitle
->userCanRead() ) {
963 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
964 $wgOut->loginToUse();
967 wfProfileOut( __METHOD__
);
971 # Are we looking at an old revision
972 if ( $oldid && !is_null( $this->mRevision
) ) {
973 $this->setOldSubtitle( $oldid );
975 if ( !$this->showDeletedRevisionHeader() ) {
976 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
977 wfProfileOut( __METHOD__
);
981 # If this "old" version is the current, then try the parser cache...
982 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
983 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
984 if ( $this->mParserOutput
) {
985 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
986 $wgOut->addParserOutput( $this->mParserOutput
);
987 $wgOut->setRevisionId( $this->mLatest
);
994 # Ensure that UI elements requiring revision ID have
995 # the correct version information.
996 $wgOut->setRevisionId( $this->getRevIdFetched() );
998 # Pages containing custom CSS or JavaScript get special treatment
999 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1000 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1001 $this->showCssOrJsPage();
1004 $rt = Title
::newFromRedirectArray( $text );
1006 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1007 # Viewing a redirect page (e.g. with parameter redirect=no)
1008 # Don't append the subtitle if this was an old revision
1009 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1010 # Parse just to get categories, displaytitle, etc.
1011 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1012 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1018 # Run the parse, protected by a pool counter
1019 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1021 $key = $parserCache->getKey( $this, $parserOptions );
1022 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1024 if ( !$poolArticleView->execute() ) {
1025 # Connection or timeout error
1026 wfProfileOut( __METHOD__
);
1032 # Should be unreachable, but just in case...
1038 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1039 if ( $this->mParserOutput
) {
1040 $titleText = $this->mParserOutput
->getTitleText();
1042 if ( strval( $titleText ) !== '' ) {
1043 $wgOut->setPageTitle( $titleText );
1047 # For the main page, overwrite the <title> element with the con-
1048 # tents of 'pagetitle-view-mainpage' instead of the default (if
1049 # that's not empty).
1050 # This message always exists because it is in the i18n files
1051 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1052 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1053 if ( !$msg->isDisabled() ) {
1054 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1058 # Now that we've filled $this->mParserOutput, we know whether
1059 # there are any __NOINDEX__ tags on the page
1060 $policy = $this->getRobotPolicy( 'view' );
1061 $wgOut->setIndexPolicy( $policy['index'] );
1062 $wgOut->setFollowPolicy( $policy['follow'] );
1064 $this->showViewFooter();
1065 $this->viewUpdates();
1066 wfProfileOut( __METHOD__
);
1070 * Show a diff page according to current request variables. For use within
1071 * Article::view() only, other callers should use the DifferenceEngine class.
1073 public function showDiffPage() {
1074 global $wgRequest, $wgUser;
1076 $diff = $wgRequest->getVal( 'diff' );
1077 $rcid = $wgRequest->getVal( 'rcid' );
1078 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1079 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1080 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1081 $oldid = $this->getOldID();
1083 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1084 // DifferenceEngine directly fetched the revision:
1085 $this->mRevIdFetched
= $de->mNewid
;
1086 $de->showDiffPage( $diffOnly );
1088 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1089 # Run view updates for current revision only
1090 $this->viewUpdates();
1095 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1096 * Article::view() only.
1098 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1101 protected function showCssOrJsPage() {
1104 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1106 // Give hooks a chance to customise the output
1107 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1108 // Wrap the whole lot in a <pre> and don't parse
1110 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1111 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1112 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1113 $wgOut->addHTML( "\n</pre>\n" );
1118 * Get the robot policy to be used for the current view
1119 * @param $action String the action= GET parameter
1120 * @return Array the policy that should be set
1121 * TODO: actions other than 'view'
1123 public function getRobotPolicy( $action ) {
1124 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1125 global $wgDefaultRobotPolicy, $wgRequest;
1127 $ns = $this->mTitle
->getNamespace();
1129 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1130 # Don't index user and user talk pages for blocked users (bug 11443)
1131 if ( !$this->mTitle
->isSubpage() ) {
1132 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1134 'index' => 'noindex',
1135 'follow' => 'nofollow'
1141 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1142 # Non-articles (special pages etc), and old revisions
1144 'index' => 'noindex',
1145 'follow' => 'nofollow'
1147 } elseif ( $wgOut->isPrintable() ) {
1148 # Discourage indexing of printable versions, but encourage following
1150 'index' => 'noindex',
1151 'follow' => 'follow'
1153 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1154 # For ?curid=x urls, disallow indexing
1156 'index' => 'noindex',
1157 'follow' => 'follow'
1161 # Otherwise, construct the policy based on the various config variables.
1162 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1164 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1165 # Honour customised robot policies for this namespace
1166 $policy = array_merge(
1168 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1171 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1172 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1173 # a final sanity check that we have really got the parser output.
1174 $policy = array_merge(
1176 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1180 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1181 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1182 $policy = array_merge(
1184 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1192 * Converts a String robot policy into an associative array, to allow
1193 * merging of several policies using array_merge().
1194 * @param $policy Mixed, returns empty array on null/false/'', transparent
1195 * to already-converted arrays, converts String.
1196 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1198 public static function formatRobotPolicy( $policy ) {
1199 if ( is_array( $policy ) ) {
1201 } elseif ( !$policy ) {
1205 $policy = explode( ',', $policy );
1206 $policy = array_map( 'trim', $policy );
1209 foreach ( $policy as $var ) {
1210 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1211 $arr['index'] = $var;
1212 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1213 $arr['follow'] = $var;
1221 * If this request is a redirect view, send "redirected from" subtitle to
1222 * $wgOut. Returns true if the header was needed, false if this is not a
1223 * redirect view. Handles both local and remote redirects.
1227 public function showRedirectedFromHeader() {
1228 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1230 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1232 if ( isset( $this->mRedirectedFrom
) ) {
1233 // This is an internally redirected page view.
1234 // We'll need a backlink to the source page for navigation.
1235 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1236 $redir = $wgUser->getSkin()->link(
1237 $this->mRedirectedFrom
,
1240 array( 'redirect' => 'no' ),
1241 array( 'known', 'noclasses' )
1244 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1245 $wgOut->setSubtitle( $s );
1247 // Set the fragment if one was specified in the redirect
1248 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1249 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1250 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1253 // Add a <link rel="canonical"> tag
1254 $wgOut->addLink( array( 'rel' => 'canonical',
1255 'href' => $this->mTitle
->getLocalURL() )
1260 } elseif ( $rdfrom ) {
1261 // This is an externally redirected view, from some other wiki.
1262 // If it was reported from a trusted site, supply a backlink.
1263 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1264 $redir = $wgUser->getSkin()->makeExternalLink( $rdfrom, $rdfrom );
1265 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1266 $wgOut->setSubtitle( $s );
1276 * Show a header specific to the namespace currently being viewed, like
1277 * [[MediaWiki:Talkpagetext]]. For Article::view().
1279 public function showNamespaceHeader() {
1282 if ( $this->mTitle
->isTalkPage() ) {
1283 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1284 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1290 * Show the footer section of an ordinary page view
1292 public function showViewFooter() {
1293 global $wgOut, $wgUseTrackbacks;
1295 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1296 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1297 $wgOut->addWikiMsg( 'anontalkpagetext' );
1300 # If we have been passed an &rcid= parameter, we want to give the user a
1301 # chance to mark this new article as patrolled.
1302 $this->showPatrolFooter();
1305 if ( $wgUseTrackbacks ) {
1306 $this->addTrackbacks();
1309 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1314 * If patrol is possible, output a patrol UI box. This is called from the
1315 * footer section of ordinary page views. If patrol is not possible or not
1316 * desired, does nothing.
1318 public function showPatrolFooter() {
1319 global $wgOut, $wgRequest, $wgUser;
1321 $rcid = $wgRequest->getVal( 'rcid' );
1323 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1327 $sk = $wgUser->getSkin();
1328 $token = $wgUser->editToken( $rcid );
1329 $wgOut->preventClickjacking();
1332 "<div class='patrollink'>" .
1334 'markaspatrolledlink',
1337 wfMsgHtml( 'markaspatrolledtext' ),
1340 'action' => 'markpatrolled',
1344 array( 'known', 'noclasses' )
1352 * Show the error text for a missing article. For articles in the MediaWiki
1353 * namespace, show the default message text. To be called from Article::view().
1355 public function showMissingArticle() {
1356 global $wgOut, $wgRequest, $wgUser;
1358 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1359 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1360 $parts = explode( '/', $this->mTitle
->getText() );
1361 $rootPart = $parts[0];
1362 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1363 $ip = User
::isIP( $rootPart );
1365 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1366 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1367 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1368 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1369 LogEventsList
::showLogExtract(
1372 $user->getUserPage()->getPrefixedText(),
1376 'showIfEmpty' => false,
1378 'blocked-notice-logextract',
1379 $user->getName() # Support GENDER in notice
1386 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1388 # Show delete and move logs
1389 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1391 'conds' => array( "log_action != 'revision'" ),
1392 'showIfEmpty' => false,
1393 'msgKey' => array( 'moveddeleted-notice' ) )
1396 # Show error message
1397 $oldid = $this->getOldID();
1399 $text = wfMsgNoTrans( 'missing-article',
1400 $this->mTitle
->getPrefixedText(),
1401 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1402 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1403 // Use the default message text
1404 $text = $this->mTitle
->getDefaultMessageText();
1406 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1407 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1408 $errors = array_merge( $createErrors, $editErrors );
1410 if ( !count( $errors ) ) {
1411 $text = wfMsgNoTrans( 'noarticletext' );
1413 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1416 $text = "<div class='noarticletext'>\n$text\n</div>";
1418 if ( !$this->hasViewableContent() ) {
1419 // If there's no backing content, send a 404 Not Found
1420 // for better machine handling of broken links.
1421 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1424 $wgOut->addWikiText( $text );
1428 * If the revision requested for view is deleted, check permissions.
1429 * Send either an error message or a warning header to $wgOut.
1431 * @return boolean true if the view is allowed, false if not.
1433 public function showDeletedRevisionHeader() {
1434 global $wgOut, $wgRequest;
1436 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1441 // If the user is not allowed to see it...
1442 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1443 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1444 'rev-deleted-text-permission' );
1447 // If the user needs to confirm that they want to see it...
1448 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1449 # Give explanation and add a link to view the revision...
1450 $oldid = intval( $this->getOldID() );
1451 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1452 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1453 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1454 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1455 array( $msg, $link ) );
1458 // We are allowed to see...
1460 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1461 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1462 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1469 * Should the parser cache be used?
1473 public function useParserCache( $oldid ) {
1474 global $wgUser, $wgEnableParserCache;
1476 return $wgEnableParserCache
1477 && $wgUser->getStubThreshold() == 0
1480 && !$this->mTitle
->isCssOrJsPage()
1481 && !$this->mTitle
->isCssJsSubpage();
1485 * Execute the uncached parse for action=view
1487 public function doViewParse() {
1490 $oldid = $this->getOldID();
1491 $parserOptions = $this->getParserOptions();
1493 # Render printable version, use printable version cache
1494 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1496 # Don't show section-edit links on old revisions... this way lies madness.
1497 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1498 $parserOptions->setEditSection( false );
1501 $useParserCache = $this->useParserCache( $oldid );
1502 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1508 * Try to fetch an expired entry from the parser cache. If it is present,
1509 * output it and return true. If it is not present, output nothing and
1510 * return false. This is used as a callback function for
1511 * PoolCounter::executeProtected().
1515 public function tryDirtyCache() {
1517 $parserCache = ParserCache
::singleton();
1518 $options = $this->getParserOptions();
1520 if ( $wgOut->isPrintable() ) {
1521 $options->setIsPrintable( true );
1522 $options->setEditSection( false );
1525 $output = $parserCache->getDirty( $this, $options );
1528 wfDebug( __METHOD__
. ": sending dirty output\n" );
1529 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1530 $wgOut->setSquidMaxage( 0 );
1531 $this->mParserOutput
= $output;
1532 $wgOut->addParserOutput( $output );
1533 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1537 wfDebugLog( 'dirty', "dirty missing\n" );
1538 wfDebug( __METHOD__
. ": no dirty cache\n" );
1547 * @param $target Title|Array of destination(s) to redirect
1548 * @param $appendSubtitle Boolean [optional]
1549 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1550 * @return string containing HMTL with redirect link
1552 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1553 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1555 if ( !is_array( $target ) ) {
1556 $target = array( $target );
1559 $imageDir = $wgContLang->getDir();
1561 if ( $appendSubtitle ) {
1562 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1565 $sk = $wgUser->getSkin();
1566 // the loop prepends the arrow image before the link, so the first case needs to be outside
1567 $title = array_shift( $target );
1569 if ( $forceKnown ) {
1570 $link = $sk->linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1572 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1575 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1576 $alt = $wgContLang->isRTL() ?
'←' : '→';
1577 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1578 foreach ( $target as $rt ) {
1579 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1580 if ( $forceKnown ) {
1581 $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1583 $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1587 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1588 return '<div class="redirectMsg">' .
1589 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1590 '<span class="redirectText">' . $link . '</span></div>';
1594 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1596 public function addTrackbacks() {
1599 $dbr = wfGetDB( DB_SLAVE
);
1600 $tbs = $dbr->select( 'trackbacks',
1601 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1602 array( 'tb_page' => $this->getID() )
1605 if ( !$dbr->numRows( $tbs ) ) {
1609 $wgOut->preventClickjacking();
1612 foreach ( $tbs as $o ) {
1615 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1616 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1617 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1618 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1622 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1630 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1634 * Removes trackback record for current article from trackbacks table
1636 public function deletetrackback() {
1637 global $wgRequest, $wgOut;
1639 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1640 $wgOut->addWikiMsg( 'sessionfailure' );
1645 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
1647 if ( count( $permission_errors ) ) {
1648 $wgOut->showPermissionsErrorPage( $permission_errors );
1653 $db = wfGetDB( DB_MASTER
);
1654 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1656 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1657 $this->mTitle
->invalidateCache();
1661 * Handle action=render
1664 public function render() {
1667 $wgOut->setArticleBodyOnly( true );
1672 * Handle action=purge
1674 public function purge() {
1675 return Action
::factory( 'purge', $this )->show();
1679 * Perform the actions of a page purging
1681 public function doPurge() {
1684 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1688 // Invalidate the cache
1689 $this->mTitle
->invalidateCache();
1692 if ( $wgUseSquid ) {
1693 // Commit the transaction before the purge is sent
1694 $dbw = wfGetDB( DB_MASTER
);
1698 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1699 $update->doUpdate();
1702 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1703 if ( $this->getID() == 0 ) {
1706 $text = $this->getRawText();
1709 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1714 * Insert a new empty page record for this article.
1715 * This *must* be followed up by creating a revision
1716 * and running $this->updateRevisionOn( ... );
1717 * or else the record will be left in a funky state.
1718 * Best if all done inside a transaction.
1720 * @param $dbw Database
1721 * @return int The newly created page_id key, or false if the title already existed
1724 public function insertOn( $dbw ) {
1725 wfProfileIn( __METHOD__
);
1727 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1728 $dbw->insert( 'page', array(
1729 'page_id' => $page_id,
1730 'page_namespace' => $this->mTitle
->getNamespace(),
1731 'page_title' => $this->mTitle
->getDBkey(),
1732 'page_counter' => 0,
1733 'page_restrictions' => '',
1734 'page_is_redirect' => 0, # Will set this shortly...
1736 'page_random' => wfRandom(),
1737 'page_touched' => $dbw->timestamp(),
1738 'page_latest' => 0, # Fill this in shortly...
1739 'page_len' => 0, # Fill this in shortly...
1740 ), __METHOD__
, 'IGNORE' );
1742 $affected = $dbw->affectedRows();
1745 $newid = $dbw->insertId();
1746 $this->mTitle
->resetArticleID( $newid );
1748 wfProfileOut( __METHOD__
);
1750 return $affected ?
$newid : false;
1754 * Update the page record to point to a newly saved revision.
1756 * @param $dbw DatabaseBase: object
1757 * @param $revision Revision: For ID number, and text used to set
1758 length and redirect status fields
1759 * @param $lastRevision Integer: if given, will not overwrite the page field
1760 * when different from the currently set value.
1761 * Giving 0 indicates the new page flag should be set
1763 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1764 * removing rows in redirect table.
1765 * @param $setNewFlag Boolean: Set to true if a page flag should be set
1766 * Needed when $lastRevision has to be set to sth. !=0
1767 * @return bool true on success, false on failure
1770 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
1771 wfProfileIn( __METHOD__
);
1773 $text = $revision->getText();
1774 $rt = Title
::newFromRedirectRecurse( $text );
1776 $conditions = array( 'page_id' => $this->getId() );
1778 if ( !is_null( $lastRevision ) ) {
1779 # An extra check against threads stepping on each other
1780 $conditions['page_latest'] = $lastRevision;
1783 if ( !$setNewFlag ) {
1784 $setNewFlag = ( $lastRevision === 0 );
1787 $dbw->update( 'page',
1789 'page_latest' => $revision->getId(),
1790 'page_touched' => $dbw->timestamp(),
1791 'page_is_new' => $setNewFlag,
1792 'page_is_redirect' => $rt !== null ?
1 : 0,
1793 'page_len' => strlen( $text ),
1798 $result = $dbw->affectedRows() != 0;
1800 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1803 wfProfileOut( __METHOD__
);
1808 * Add row to the redirect table if this is a redirect, remove otherwise.
1810 * @param $dbw Database
1811 * @param $redirectTitle Title object pointing to the redirect target,
1812 * or NULL if this is not a redirect
1813 * @param $lastRevIsRedirect If given, will optimize adding and
1814 * removing rows in redirect table.
1815 * @return bool true on success, false on failure
1818 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1819 // Always update redirects (target link might have changed)
1820 // Update/Insert if we don't know if the last revision was a redirect or not
1821 // Delete if changing from redirect to non-redirect
1822 $isRedirect = !is_null( $redirectTitle );
1824 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1828 wfProfileIn( __METHOD__
);
1829 if ( $isRedirect ) {
1830 $this->insertRedirectEntry( $redirectTitle );
1832 // This is not a redirect, remove row from redirect table
1833 $where = array( 'rd_from' => $this->getId() );
1834 $dbw->delete( 'redirect', $where, __METHOD__
);
1837 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1838 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1840 wfProfileOut( __METHOD__
);
1842 return ( $dbw->affectedRows() != 0 );
1846 * If the given revision is newer than the currently set page_latest,
1847 * update the page record. Otherwise, do nothing.
1849 * @param $dbw Database object
1850 * @param $revision Revision object
1853 public function updateIfNewerOn( &$dbw, $revision ) {
1854 wfProfileIn( __METHOD__
);
1856 $row = $dbw->selectRow(
1857 array( 'revision', 'page' ),
1858 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1860 'page_id' => $this->getId(),
1861 'page_latest=rev_id' ),
1865 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1866 wfProfileOut( __METHOD__
);
1869 $prev = $row->rev_id
;
1870 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1872 # No or missing previous revision; mark the page as new
1874 $lastRevIsRedirect = null;
1877 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1879 wfProfileOut( __METHOD__
);
1884 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1885 * @param $text String: new text of the section
1886 * @param $summary String: new section's subject, only if $section is 'new'
1887 * @param $edittime String: revision timestamp or null to use the current revision
1888 * @return string Complete article text, or null if error
1890 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1891 wfProfileIn( __METHOD__
);
1893 if ( strval( $section ) == '' ) {
1894 // Whole-page edit; let the whole text through
1896 if ( is_null( $edittime ) ) {
1897 $rev = Revision
::newFromTitle( $this->mTitle
);
1899 $dbw = wfGetDB( DB_MASTER
);
1900 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1904 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1905 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1906 wfProfileOut( __METHOD__
);
1910 $oldtext = $rev->getText();
1912 if ( $section == 'new' ) {
1913 # Inserting a new section
1914 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1915 $text = strlen( trim( $oldtext ) ) > 0
1916 ?
"{$oldtext}\n\n{$subject}{$text}"
1917 : "{$subject}{$text}";
1919 # Replacing an existing section; roll out the big guns
1922 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1926 wfProfileOut( __METHOD__
);
1931 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1933 * @return Int updated $flags
1935 function checkFlags( $flags ) {
1936 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1937 if ( $this->mTitle
->getArticleID() ) {
1938 $flags |
= EDIT_UPDATE
;
1950 * Change an existing article or create a new article. Updates RC and all necessary caches,
1951 * optionally via the deferred update array.
1953 * $wgUser must be set before calling this function.
1955 * @param $text String: new text
1956 * @param $summary String: edit summary
1957 * @param $flags Integer bitfield:
1959 * Article is known or assumed to be non-existent, create a new one
1961 * Article is known or assumed to be pre-existing, update it
1963 * Mark this edit minor, if the user is allowed to do so
1965 * Do not log the change in recentchanges
1967 * Mark the edit a "bot" edit regardless of user rights
1968 * EDIT_DEFER_UPDATES
1969 * Defer some of the updates until the end of index.php
1971 * Fill in blank summaries with generated text where possible
1973 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1974 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1975 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1976 * edit-already-exists error will be returned. These two conditions are also possible with
1977 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1979 * @param $baseRevId the revision ID this edit was based off, if any
1980 * @param $user User (optional), $wgUser will be used if not passed
1982 * @return Status object. Possible errors:
1983 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1984 * edit-gone-missing: In update mode, but the article didn't exist
1985 * edit-conflict: In update mode, the article changed unexpectedly
1986 * edit-no-change: Warning that the text was the same as before
1987 * edit-already-exists: In creation mode, but the article already exists
1989 * Extensions may define additional errors.
1991 * $return->value will contain an associative array with members as follows:
1992 * new: Boolean indicating if the function attempted to create a new article
1993 * revision: The revision object for the inserted revision, or null
1995 * Compatibility note: this function previously returned a boolean value indicating success/failure
1997 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1998 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2000 # Low-level sanity check
2001 if ( $this->mTitle
->getText() === '' ) {
2002 throw new MWException( 'Something is trying to edit an article with an empty title' );
2005 wfProfileIn( __METHOD__
);
2007 $user = is_null( $user ) ?
$wgUser : $user;
2008 $status = Status
::newGood( array() );
2010 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2011 $this->loadPageData();
2013 $flags = $this->checkFlags( $flags );
2015 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2016 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2018 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2020 if ( $status->isOK() ) {
2021 $status->fatal( 'edit-hook-aborted' );
2024 wfProfileOut( __METHOD__
);
2028 # Silently ignore EDIT_MINOR if not allowed
2029 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2030 $bot = $flags & EDIT_FORCE_BOT
;
2032 $oldtext = $this->getRawText(); // current revision
2033 $oldsize = strlen( $oldtext );
2035 # Provide autosummaries if one is not provided and autosummaries are enabled.
2036 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2037 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2040 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2041 $text = $editInfo->pst
;
2042 $newsize = strlen( $text );
2044 $dbw = wfGetDB( DB_MASTER
);
2045 $now = wfTimestampNow();
2046 $this->mTimestamp
= $now;
2048 if ( $flags & EDIT_UPDATE
) {
2049 # Update article, but only if changed.
2050 $status->value
['new'] = false;
2052 # Make sure the revision is either completely inserted or not inserted at all
2053 if ( !$wgDBtransactions ) {
2054 $userAbort = ignore_user_abort( true );
2057 $changed = ( strcmp( $text, $oldtext ) != 0 );
2060 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
2061 - (int)$this->isCountable( $oldtext );
2062 $this->mTotalAdjustment
= 0;
2064 if ( !$this->mLatest
) {
2065 # Article gone missing
2066 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2067 $status->fatal( 'edit-gone-missing' );
2069 wfProfileOut( __METHOD__
);
2073 $revision = new Revision( array(
2074 'page' => $this->getId(),
2075 'comment' => $summary,
2076 'minor_edit' => $isminor,
2078 'parent_id' => $this->mLatest
,
2079 'user' => $user->getId(),
2080 'user_text' => $user->getName(),
2085 $revisionId = $revision->insertOn( $dbw );
2089 # Note that we use $this->mLatest instead of fetching a value from the master DB
2090 # during the course of this function. This makes sure that EditPage can detect
2091 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2092 # before this function is called. A previous function used a separate query, this
2093 # creates a window where concurrent edits can cause an ignored edit conflict.
2094 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2097 /* Belated edit conflict! Run away!! */
2098 $status->fatal( 'edit-conflict' );
2100 # Delete the invalid revision if the DB is not transactional
2101 if ( !$wgDBtransactions ) {
2102 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2108 global $wgUseRCPatrol;
2109 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2110 # Update recentchanges
2111 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2112 # Mark as patrolled if the user can do so
2113 $patrolled = $wgUseRCPatrol && !count(
2114 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2115 # Add RC row to the DB
2116 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2117 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2118 $revisionId, $patrolled
2121 # Log auto-patrolled edits
2123 PatrolLog
::record( $rc, true );
2126 $user->incEditCount();
2130 $status->warning( 'edit-no-change' );
2132 // Keep the same revision ID, but do some updates on it
2133 $revisionId = $this->getLatest();
2134 // Update page_touched, this is usually implicit in the page update
2135 // Other cache updates are done in onArticleEdit()
2136 $this->mTitle
->invalidateCache();
2139 if ( !$wgDBtransactions ) {
2140 ignore_user_abort( $userAbort );
2143 // Now that ignore_user_abort is restored, we can respond to fatal errors
2144 if ( !$status->isOK() ) {
2145 wfProfileOut( __METHOD__
);
2149 # Invalidate cache of this article and all pages using this article
2150 # as a template. Partly deferred.
2151 Article
::onArticleEdit( $this->mTitle
);
2152 # Update links tables, site stats, etc.
2153 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2155 # Create new article
2156 $status->value
['new'] = true;
2158 # Set statistics members
2159 # We work out if it's countable after PST to avoid counter drift
2160 # when articles are created with {{subst:}}
2161 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2162 $this->mTotalAdjustment
= 1;
2166 # Add the page record; stake our claim on this title!
2167 # This will return false if the article already exists
2168 $newid = $this->insertOn( $dbw );
2170 if ( $newid === false ) {
2172 $status->fatal( 'edit-already-exists' );
2174 wfProfileOut( __METHOD__
);
2178 # Save the revision text...
2179 $revision = new Revision( array(
2181 'comment' => $summary,
2182 'minor_edit' => $isminor,
2184 'user' => $user->getId(),
2185 'user_text' => $user->getName(),
2188 $revisionId = $revision->insertOn( $dbw );
2190 $this->mTitle
->resetArticleID( $newid );
2191 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached (FIXME?)
2192 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2194 # Update the page record with revision data
2195 $this->updateRevisionOn( $dbw, $revision, 0 );
2197 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2199 # Update recentchanges
2200 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2201 global $wgUseRCPatrol, $wgUseNPPatrol;
2203 # Mark as patrolled if the user can do so
2204 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2205 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2206 # Add RC row to the DB
2207 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2208 '', strlen( $text ), $revisionId, $patrolled );
2210 # Log auto-patrolled edits
2212 PatrolLog
::record( $rc, true );
2215 $user->incEditCount();
2218 # Update links, etc.
2219 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user );
2222 Article
::onArticleCreate( $this->mTitle
);
2224 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2225 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2228 # Do updates right now unless deferral was requested
2229 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2233 // Return the new revision (or null) to the caller
2234 $status->value
['revision'] = $revision;
2236 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2237 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2239 wfProfileOut( __METHOD__
);
2244 * Output a redirect back to the article.
2245 * This is typically used after an edit.
2247 * @param $noRedir Boolean: add redirect=no
2248 * @param $sectionAnchor String: section to redirect to, including "#"
2249 * @param $extraQuery String: extra query params
2251 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2255 $query = 'redirect=no';
2257 $query .= "&$extraQuery";
2259 $query = $extraQuery;
2262 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2266 * Mark this particular edit/page as patrolled
2268 public function markpatrolled() {
2269 global $wgOut, $wgRequest;
2271 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2273 # If we haven't been given an rc_id value, we can't do anything
2274 $rcid = (int) $wgRequest->getVal( 'rcid' );
2276 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2277 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2281 $rc = RecentChange
::newFromId( $rcid );
2283 if ( is_null( $rc ) ) {
2284 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2288 # It would be nice to see where the user had actually come from, but for now just guess
2289 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2290 $return = SpecialPage
::getTitleFor( $returnto );
2292 $errors = $rc->doMarkPatrolled();
2294 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2295 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2300 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2301 // The hook itself has handled any output
2305 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2306 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2307 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2308 $wgOut->returnToMain( false, $return );
2313 if ( !empty( $errors ) ) {
2314 $wgOut->showPermissionsErrorPage( $errors );
2320 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2321 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2322 $wgOut->returnToMain( false, $return );
2326 * User-interface handler for the "watch" action
2327 * @deprecated since 1.18
2329 public function watch() {
2330 Action
::factory( 'watch', $this )->show();
2334 * Add this page to $wgUser's watchlist
2336 * This is safe to be called multiple times
2338 * @return bool true on successful watch operation
2339 * @deprecated since 1.18
2341 public function doWatch() {
2342 return Action
::factory( 'watch', $this )->execute();
2346 * User interface handler for the "unwatch" action.
2347 * @deprecated since 1.18
2349 public function unwatch() {
2350 Action
::factory( 'unwatch', $this )->show();
2354 * Stop watching a page
2355 * @return bool true on successful unwatch
2356 * @deprecated since 1.18
2358 public function doUnwatch() {
2359 return Action
::factory( 'unwatch', $this )->execute();
2363 * action=protect handler
2365 public function protect() {
2366 $form = new ProtectionForm( $this );
2371 * action=unprotect handler (alias)
2373 public function unprotect() {
2378 * Update the article's restriction field, and leave a log entry.
2380 * @param $limit Array: set of restriction keys
2381 * @param $reason String
2382 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2383 * @param $expiry Array: per restriction type expiration
2384 * @return bool true on success
2386 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2387 global $wgUser, $wgContLang;
2389 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2391 $id = $this->mTitle
->getArticleID();
2394 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2398 if ( wfReadOnly() ) {
2399 wfDebug( "updateRestrictions failed: read-only\n" );
2403 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2404 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2412 // Take this opportunity to purge out expired restrictions
2413 Title
::purgeExpiredRestrictions();
2415 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2416 # we expect a single selection, but the schema allows otherwise.
2418 $updated = Article
::flattenRestrictions( $limit );
2421 foreach ( $restrictionTypes as $action ) {
2422 if ( isset( $expiry[$action] ) ) {
2423 # Get current restrictions on $action
2424 $aLimits = $this->mTitle
->getRestrictions( $action );
2425 $current[$action] = implode( '', $aLimits );
2426 # Are any actual restrictions being dealt with here?
2427 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2429 # If something changed, we need to log it. Checking $aRChanged
2430 # assures that "unprotecting" a page that is not protected does
2431 # not log just because the expiry was "changed".
2432 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2438 $current = Article
::flattenRestrictions( $current );
2440 $changed = ( $changed ||
$current != $updated );
2441 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2442 $protect = ( $updated != '' );
2444 # If nothing's changed, do nothing
2446 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2447 $dbw = wfGetDB( DB_MASTER
);
2449 # Prepare a null revision to be added to the history
2450 $modified = $current != '' && $protect;
2453 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2455 $comment_type = 'unprotectedarticle';
2458 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2460 # Only restrictions with the 'protect' right can cascade...
2461 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2462 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2464 # The schema allows multiple restrictions
2465 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2469 $cascade_description = '';
2472 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2476 $comment .= ": $reason";
2479 $editComment = $comment;
2480 $encodedExpiry = array();
2481 $protect_description = '';
2482 foreach ( $limit as $action => $restrictions ) {
2483 if ( !isset( $expiry[$action] ) )
2484 $expiry[$action] = $dbw->getInfinity();
2486 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2487 if ( $restrictions != '' ) {
2488 $protect_description .= "[$action=$restrictions] (";
2489 if ( $encodedExpiry[$action] != 'infinity' ) {
2490 $protect_description .= wfMsgForContent( 'protect-expiring',
2491 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2492 $wgContLang->date( $expiry[$action], false, false ) ,
2493 $wgContLang->time( $expiry[$action], false, false ) );
2495 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2498 $protect_description .= ') ';
2501 $protect_description = trim( $protect_description );
2503 if ( $protect_description && $protect ) {
2504 $editComment .= " ($protect_description)";
2508 $editComment .= "$cascade_description";
2511 # Update restrictions table
2512 foreach ( $limit as $action => $restrictions ) {
2513 if ( $restrictions != '' ) {
2514 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2515 array( 'pr_page' => $id,
2516 'pr_type' => $action,
2517 'pr_level' => $restrictions,
2518 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2519 'pr_expiry' => $encodedExpiry[$action]
2524 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2525 'pr_type' => $action ), __METHOD__
);
2529 # Insert a null revision
2530 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2531 $nullRevId = $nullRevision->insertOn( $dbw );
2533 $latest = $this->getLatest();
2534 # Update page record
2535 $dbw->update( 'page',
2537 'page_touched' => $dbw->timestamp(),
2538 'page_restrictions' => '',
2539 'page_latest' => $nullRevId
2540 ), array( /* WHERE */
2542 ), 'Article::protect'
2545 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2546 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2548 # Update the protection log
2549 $log = new LogPage( 'protect' );
2551 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2552 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2554 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2557 } # End "changed" check
2563 * Take an array of page restrictions and flatten it to a string
2564 * suitable for insertion into the page_restrictions field.
2565 * @param $limit Array
2568 protected static function flattenRestrictions( $limit ) {
2569 if ( !is_array( $limit ) ) {
2570 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2576 foreach ( $limit as $action => $restrictions ) {
2577 if ( $restrictions != '' ) {
2578 $bits[] = "$action=$restrictions";
2582 return implode( ':', $bits );
2586 * Auto-generates a deletion reason
2588 * @param &$hasHistory Boolean: whether the page has a history
2589 * @return mixed String containing deletion reason or empty string, or boolean false
2590 * if no revision occurred
2592 public function generateReason( &$hasHistory ) {
2595 $dbw = wfGetDB( DB_MASTER
);
2596 // Get the last revision
2597 $rev = Revision
::newFromTitle( $this->mTitle
);
2599 if ( is_null( $rev ) ) {
2603 // Get the article's contents
2604 $contents = $rev->getText();
2607 // If the page is blank, use the text from the previous revision,
2608 // which can only be blank if there's a move/import/protect dummy revision involved
2609 if ( $contents == '' ) {
2610 $prev = $rev->getPrevious();
2613 $contents = $prev->getText();
2618 // Find out if there was only one contributor
2619 // Only scan the last 20 revisions
2620 $res = $dbw->select( 'revision', 'rev_user_text',
2621 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2623 array( 'LIMIT' => 20 )
2626 if ( $res === false ) {
2627 // This page has no revisions, which is very weird
2631 $hasHistory = ( $res->numRows() > 1 );
2632 $row = $dbw->fetchObject( $res );
2634 if ( $row ) { // $row is false if the only contributor is hidden
2635 $onlyAuthor = $row->rev_user_text
;
2636 // Try to find a second contributor
2637 foreach ( $res as $row ) {
2638 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2639 $onlyAuthor = false;
2644 $onlyAuthor = false;
2647 // Generate the summary with a '$1' placeholder
2649 // The current revision is blank and the one before is also
2650 // blank. It's just not our lucky day
2651 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2653 if ( $onlyAuthor ) {
2654 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2656 $reason = wfMsgForContent( 'excontent', '$1' );
2660 if ( $reason == '-' ) {
2661 // Allow these UI messages to be blanked out cleanly
2665 // Replace newlines with spaces to prevent uglyness
2666 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2667 // Calculate the maximum amount of chars to get
2668 // Max content length = max comment length - length of the comment (excl. $1)
2669 $maxLength = 255 - ( strlen( $reason ) - 2 );
2670 $contents = $wgContLang->truncate( $contents, $maxLength );
2671 // Remove possible unfinished links
2672 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2673 // Now replace the '$1' placeholder
2674 $reason = str_replace( '$1', $contents, $reason );
2681 * UI entry point for page deletion
2683 public function delete() {
2684 global $wgOut, $wgRequest;
2686 $confirm = $wgRequest->wasPosted() &&
2687 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2689 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2690 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2692 $reason = $this->DeleteReasonList
;
2694 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2695 // Entry from drop down menu + additional comment
2696 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2697 } elseif ( $reason == 'other' ) {
2698 $reason = $this->DeleteReason
;
2701 # Flag to hide all contents of the archived revisions
2702 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2704 # This code desperately needs to be totally rewritten
2706 # Read-only check...
2707 if ( wfReadOnly() ) {
2708 $wgOut->readOnlyPage();
2714 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2716 if ( count( $permission_errors ) > 0 ) {
2717 $wgOut->showPermissionsErrorPage( $permission_errors );
2722 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2724 # Better double-check that it hasn't been deleted yet!
2725 $dbw = wfGetDB( DB_MASTER
);
2726 $conds = $this->mTitle
->pageCond();
2727 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2728 if ( $latest === false ) {
2729 $wgOut->showFatalError(
2732 array( 'class' => 'error mw-error-cannotdelete' ),
2733 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2736 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2737 LogEventsList
::showLogExtract(
2740 $this->mTitle
->getPrefixedText()
2746 # Hack for big sites
2747 $bigHistory = $this->isBigDeletion();
2748 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2749 global $wgLang, $wgDeleteRevisionsLimit;
2751 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2752 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2758 $this->doDelete( $reason, $suppress );
2760 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2762 } elseif ( $this->mTitle
->userIsWatching() ) {
2769 // Generate deletion reason
2770 $hasHistory = false;
2772 $reason = $this->generateReason( $hasHistory );
2775 // If the page has a history, insert a warning
2776 if ( $hasHistory && !$confirm ) {
2779 $skin = $wgOut->getSkin();
2780 $revisions = $this->estimateRevisionCount();
2782 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2783 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2784 wfMsgHtml( 'word-separator' ) . $skin->link( $this->mTitle
,
2785 wfMsgHtml( 'history' ),
2786 array( 'rel' => 'archives' ),
2787 array( 'action' => 'history' ) ) .
2791 if ( $bigHistory ) {
2792 global $wgDeleteRevisionsLimit;
2793 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2794 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2798 return $this->confirmDelete( $reason );
2802 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2804 public function isBigDeletion() {
2805 global $wgDeleteRevisionsLimit;
2807 if ( $wgDeleteRevisionsLimit ) {
2808 $revCount = $this->estimateRevisionCount();
2810 return $revCount > $wgDeleteRevisionsLimit;
2817 * @return int approximate revision count
2819 public function estimateRevisionCount() {
2820 $dbr = wfGetDB( DB_SLAVE
);
2822 // For an exact count...
2823 // return $dbr->selectField( 'revision', 'COUNT(*)',
2824 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2825 return $dbr->estimateRowCount( 'revision', '*',
2826 array( 'rev_page' => $this->getId() ), __METHOD__
);
2830 * Get the last N authors
2831 * @param $num Integer: number of revisions to get
2832 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2833 * @return array Array of authors, duplicates not removed
2835 public function getLastNAuthors( $num, $revLatest = 0 ) {
2836 wfProfileIn( __METHOD__
);
2837 // First try the slave
2838 // If that doesn't have the latest revision, try the master
2840 $db = wfGetDB( DB_SLAVE
);
2843 $res = $db->select( array( 'page', 'revision' ),
2844 array( 'rev_id', 'rev_user_text' ),
2846 'page_namespace' => $this->mTitle
->getNamespace(),
2847 'page_title' => $this->mTitle
->getDBkey(),
2848 'rev_page = page_id'
2851 'ORDER BY' => 'rev_timestamp DESC',
2857 wfProfileOut( __METHOD__
);
2861 $row = $db->fetchObject( $res );
2863 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2864 $db = wfGetDB( DB_MASTER
);
2869 } while ( $continue );
2871 $authors = array( $row->rev_user_text
);
2873 foreach ( $res as $row ) {
2874 $authors[] = $row->rev_user_text
;
2877 wfProfileOut( __METHOD__
);
2882 * Output deletion confirmation dialog
2883 * FIXME: Move to another file?
2884 * @param $reason String: prefilled reason
2886 public function confirmDelete( $reason ) {
2889 wfDebug( "Article::confirmDelete\n" );
2891 $deleteBackLink = $wgOut->getSkin()->linkKnown( $this->mTitle
);
2892 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2893 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2894 $wgOut->addWikiMsg( 'confirmdeletetext' );
2896 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2898 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2899 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2901 <td class='mw-input'><strong>" .
2902 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2903 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2909 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2911 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2912 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2913 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2914 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2915 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2916 "<tr id=\"wpDeleteReasonListRow\">
2917 <td class='mw-label'>" .
2918 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2920 <td class='mw-input'>" .
2921 Xml
::listDropDown( 'wpDeleteReasonList',
2922 wfMsgForContent( 'deletereason-dropdown' ),
2923 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2926 <tr id=\"wpDeleteReasonRow\">
2927 <td class='mw-label'>" .
2928 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2930 <td class='mw-input'>" .
2931 Html
::input( 'wpReason', $reason, 'text', array(
2933 'maxlength' => '255',
2941 # Disallow watching if user is not logged in
2942 if ( $wgOut->getUser()->isLoggedIn() ) {
2946 <td class='mw-input'>" .
2947 Xml
::checkLabel( wfMsg( 'watchthis' ),
2948 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2957 <td class='mw-submit'>" .
2958 Xml
::submitButton( wfMsg( 'deletepage' ),
2959 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2962 Xml
::closeElement( 'table' ) .
2963 Xml
::closeElement( 'fieldset' ) .
2964 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2965 Xml
::closeElement( 'form' );
2967 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2968 $skin = $wgOut->getSkin();
2969 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2970 $link = $skin->link(
2972 wfMsgHtml( 'delete-edit-reasonlist' ),
2974 array( 'action' => 'edit' )
2976 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2979 $wgOut->addHTML( $form );
2980 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2981 LogEventsList
::showLogExtract( $wgOut, 'delete',
2982 $this->mTitle
->getPrefixedText()
2987 * Perform a deletion and output success or failure messages
2989 public function doDelete( $reason, $suppress = false ) {
2992 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2995 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
2996 $deleted = $this->mTitle
->getPrefixedText();
2998 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2999 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3001 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3003 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3004 $wgOut->returnToMain( false );
3006 if ( $error == '' ) {
3007 $wgOut->showFatalError(
3010 array( 'class' => 'error mw-error-cannotdelete' ),
3011 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3015 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3017 LogEventsList
::showLogExtract(
3020 $this->mTitle
->getPrefixedText()
3023 $wgOut->showFatalError( $error );
3029 * Back-end article deletion
3030 * Deletes the article with database consistency, writes logs, purges caches
3032 * @param $reason string delete reason for deletion log
3033 * @param suppress bitfield
3034 * Revision::DELETED_TEXT
3035 * Revision::DELETED_COMMENT
3036 * Revision::DELETED_USER
3037 * Revision::DELETED_RESTRICTED
3038 * @param $id int article ID
3039 * @param $commit boolean defaults to true, triggers transaction end
3040 * @return boolean true if successful
3042 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3043 global $wgDeferredUpdateList, $wgUseTrackbacks;
3046 wfDebug( __METHOD__
. "\n" );
3048 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3051 $dbw = wfGetDB( DB_MASTER
);
3052 $t = $this->mTitle
->getDBkey();
3053 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3055 if ( $t === '' ||
$id == 0 ) {
3059 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3060 array_push( $wgDeferredUpdateList, $u );
3062 // Bitfields to further suppress the content
3065 // This should be 15...
3066 $bitfield |
= Revision
::DELETED_TEXT
;
3067 $bitfield |
= Revision
::DELETED_COMMENT
;
3068 $bitfield |
= Revision
::DELETED_USER
;
3069 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3071 $bitfield = 'rev_deleted';
3075 // For now, shunt the revision data into the archive table.
3076 // Text is *not* removed from the text table; bulk storage
3077 // is left intact to avoid breaking block-compression or
3078 // immutable storage schemes.
3080 // For backwards compatibility, note that some older archive
3081 // table entries will have ar_text and ar_flags fields still.
3083 // In the future, we may keep revisions and mark them with
3084 // the rev_deleted field, which is reserved for this purpose.
3085 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3087 'ar_namespace' => 'page_namespace',
3088 'ar_title' => 'page_title',
3089 'ar_comment' => 'rev_comment',
3090 'ar_user' => 'rev_user',
3091 'ar_user_text' => 'rev_user_text',
3092 'ar_timestamp' => 'rev_timestamp',
3093 'ar_minor_edit' => 'rev_minor_edit',
3094 'ar_rev_id' => 'rev_id',
3095 'ar_text_id' => 'rev_text_id',
3096 'ar_text' => '\'\'', // Be explicit to appease
3097 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3098 'ar_len' => 'rev_len',
3099 'ar_page_id' => 'page_id',
3100 'ar_deleted' => $bitfield
3103 'page_id = rev_page'
3107 # Delete restrictions for it
3108 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3110 # Now that it's safely backed up, delete it
3111 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3112 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3119 # Fix category table counts
3121 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3123 foreach ( $res as $row ) {
3124 $cats [] = $row->cl_to
;
3127 $this->updateCategoryCounts( array(), $cats );
3129 # If using cascading deletes, we can skip some explicit deletes
3130 if ( !$dbw->cascadingDeletes() ) {
3131 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3133 if ( $wgUseTrackbacks )
3134 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3136 # Delete outgoing links
3137 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3138 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3139 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3140 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3141 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3142 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3143 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3146 # If using cleanup triggers, we can skip some manual deletes
3147 if ( !$dbw->cleanupTriggers() ) {
3148 # Clean up recentchanges entries...
3149 $dbw->delete( 'recentchanges',
3150 array( 'rc_type != ' . RC_LOG
,
3151 'rc_namespace' => $this->mTitle
->getNamespace(),
3152 'rc_title' => $this->mTitle
->getDBkey() ),
3154 $dbw->delete( 'recentchanges',
3155 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3160 Article
::onArticleDelete( $this->mTitle
);
3162 # Clear the cached article id so the interface doesn't act like we exist
3163 $this->mTitle
->resetArticleID( 0 );
3165 # Log the deletion, if the page was suppressed, log it at Oversight instead
3166 $logtype = $suppress ?
'suppress' : 'delete';
3167 $log = new LogPage( $logtype );
3169 # Make sure logging got through
3170 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3176 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3181 * Roll back the most recent consecutive set of edits to a page
3182 * from the same user; fails if there are no eligible edits to
3183 * roll back to, e.g. user is the sole contributor. This function
3184 * performs permissions checks on $wgUser, then calls commitRollback()
3185 * to do the dirty work
3187 * @param $fromP String: Name of the user whose edits to rollback.
3188 * @param $summary String: Custom summary. Set to default summary if empty.
3189 * @param $token String: Rollback token.
3190 * @param $bot Boolean: If true, mark all reverted edits as bot.
3192 * @param $resultDetails Array: contains result-specific array of additional values
3193 * 'alreadyrolled' : 'current' (rev)
3194 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3196 * @return array of errors, each error formatted as
3197 * array(messagekey, param1, param2, ...).
3198 * On success, the array is empty. This array can also be passed to
3199 * OutputPage::showPermissionsErrorPage().
3201 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3204 $resultDetails = null;
3207 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3208 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3209 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3211 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3212 $errors[] = array( 'sessionfailure' );
3215 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3216 $errors[] = array( 'actionthrottledtext' );
3219 # If there were errors, bail out now
3220 if ( !empty( $errors ) ) {
3224 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3228 * Backend implementation of doRollback(), please refer there for parameter
3229 * and return value documentation
3231 * NOTE: This function does NOT check ANY permissions, it just commits the
3232 * rollback to the DB Therefore, you should only call this function direct-
3233 * ly if you want to use custom permissions checks. If you don't, use
3234 * doRollback() instead.
3236 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3237 global $wgUseRCPatrol, $wgUser, $wgLang;
3239 $dbw = wfGetDB( DB_MASTER
);
3241 if ( wfReadOnly() ) {
3242 return array( array( 'readonlytext' ) );
3245 # Get the last editor
3246 $current = Revision
::newFromTitle( $this->mTitle
);
3247 if ( is_null( $current ) ) {
3248 # Something wrong... no page?
3249 return array( array( 'notanarticle' ) );
3252 $from = str_replace( '_', ' ', $fromP );
3253 # User name given should match up with the top revision.
3254 # If the user was deleted then $from should be empty.
3255 if ( $from != $current->getUserText() ) {
3256 $resultDetails = array( 'current' => $current );
3257 return array( array( 'alreadyrolled',
3258 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3259 htmlspecialchars( $fromP ),
3260 htmlspecialchars( $current->getUserText() )
3264 # Get the last edit not by this guy...
3265 # Note: these may not be public values
3266 $user = intval( $current->getRawUser() );
3267 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3268 $s = $dbw->selectRow( 'revision',
3269 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3270 array( 'rev_page' => $current->getPage(),
3271 "rev_user != {$user} OR rev_user_text != {$user_text}"
3273 array( 'USE INDEX' => 'page_timestamp',
3274 'ORDER BY' => 'rev_timestamp DESC' )
3276 if ( $s === false ) {
3277 # No one else ever edited this page
3278 return array( array( 'cantrollback' ) );
3279 } else if ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3280 # Only admins can see this text
3281 return array( array( 'notvisiblerev' ) );
3285 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3286 # Mark all reverted edits as bot
3290 if ( $wgUseRCPatrol ) {
3291 # Mark all reverted edits as patrolled
3292 $set['rc_patrolled'] = 1;
3295 if ( count( $set ) ) {
3296 $dbw->update( 'recentchanges', $set,
3298 'rc_cur_id' => $current->getPage(),
3299 'rc_user_text' => $current->getUserText(),
3300 "rc_timestamp > '{$s->rev_timestamp}'",
3305 # Generate the edit summary if necessary
3306 $target = Revision
::newFromId( $s->rev_id
);
3307 if ( empty( $summary ) ) {
3308 if ( $from == '' ) { // no public user name
3309 $summary = wfMsgForContent( 'revertpage-nouser' );
3311 $summary = wfMsgForContent( 'revertpage' );
3315 # Allow the custom summary to use the same args as the default message
3317 $target->getUserText(), $from, $s->rev_id
,
3318 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3319 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3321 $summary = wfMsgReplaceArgs( $summary, $args );
3324 $flags = EDIT_UPDATE
;
3326 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3327 $flags |
= EDIT_MINOR
;
3330 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3331 $flags |
= EDIT_FORCE_BOT
;
3334 # Actually store the edit
3335 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3336 if ( !empty( $status->value
['revision'] ) ) {
3337 $revId = $status->value
['revision']->getId();
3342 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3344 $resultDetails = array(
3345 'summary' => $summary,
3346 'current' => $current,
3347 'target' => $target,
3355 * User interface for rollback operations
3357 public function rollback() {
3358 global $wgUser, $wgOut, $wgRequest;
3362 $result = $this->doRollback(
3363 $wgRequest->getVal( 'from' ),
3364 $wgRequest->getText( 'summary' ),
3365 $wgRequest->getVal( 'token' ),
3366 $wgRequest->getBool( 'bot' ),
3370 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3371 $wgOut->rateLimited();
3375 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3376 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3377 $errArray = $result[0];
3378 $errMsg = array_shift( $errArray );
3379 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3381 if ( isset( $details['current'] ) ) {
3382 $current = $details['current'];
3384 if ( $current->getComment() != '' ) {
3385 $wgOut->addWikiMsgArray( 'editcomment', array(
3386 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3393 # Display permissions errors before read-only message -- there's no
3394 # point in misleading the user into thinking the inability to rollback
3395 # is only temporary.
3396 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3397 # array_diff is completely broken for arrays of arrays, sigh.
3398 # Remove any 'readonlytext' error manually.
3400 foreach ( $result as $error ) {
3401 if ( $error != array( 'readonlytext' ) ) {
3405 $wgOut->showPermissionsErrorPage( $out );
3410 if ( $result == array( array( 'readonlytext' ) ) ) {
3411 $wgOut->readOnlyPage();
3416 $current = $details['current'];
3417 $target = $details['target'];
3418 $newId = $details['newid'];
3419 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3420 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3422 if ( $current->getUserText() === '' ) {
3423 $old = wfMsg( 'rev-deleted-user' );
3425 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3426 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3429 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3430 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3431 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3432 $wgOut->returnToMain( false, $this->mTitle
);
3434 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3435 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3436 $de->showDiff( '', '' );
3441 * Do standard deferred updates after page view
3443 public function viewUpdates() {
3444 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3445 if ( wfReadOnly() ) {
3449 # Don't update page view counters on views from bot users (bug 14044)
3450 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3451 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3452 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3455 # Update newtalk / watchlist notification status
3456 $wgUser->clearNotification( $this->mTitle
);
3460 * Prepare text which is about to be saved.
3461 * Returns a stdclass with source, pst and output members
3463 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3464 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3466 return $this->mPreparedEdit
;
3471 if( $user === null ) {
3475 $popts = ParserOptions
::newFromUser( $user );
3476 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3478 $edit = (object)array();
3479 $edit->revid
= $revid;
3480 $edit->newText
= $text;
3481 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3482 $edit->popts
= $this->getParserOptions();
3483 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3484 $edit->oldText
= $this->getRawText();
3486 $this->mPreparedEdit
= $edit;
3492 * Do standard deferred updates after page edit.
3493 * Update links tables, site stats, search index and message cache.
3494 * Purges pages that include this page if the text was changed here.
3495 * Every 100th edit, prune the recent changes table.
3498 * @param $text String: New text of the article
3499 * @param $summary String: Edit summary
3500 * @param $minoredit Boolean: Minor edit
3501 * @param $timestamp_of_pagechange String timestamp associated with the page change
3502 * @param $newid Integer: rev_id value of the new revision
3503 * @param $changed Boolean: Whether or not the content actually changed
3504 * @param $user User object: User doing the edit
3506 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User
$user = null ) {
3507 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3509 wfProfileIn( __METHOD__
);
3512 # Be careful not to double-PST: $text is usually already PST-ed once
3513 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3514 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3515 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3517 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3518 $editInfo = $this->mPreparedEdit
;
3521 # Save it to the parser cache
3522 if ( $wgEnableParserCache ) {
3523 $parserCache = ParserCache
::singleton();
3524 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3527 # Update the links tables
3528 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3531 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3533 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3534 if ( 0 == mt_rand( 0, 99 ) ) {
3535 // Flush old entries from the `recentchanges` table; we do this on
3536 // random requests so as to avoid an increase in writes for no good reason
3539 $dbw = wfGetDB( DB_MASTER
);
3540 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3543 array( "rc_timestamp < '$cutoff'" ),
3549 $id = $this->getID();
3550 $title = $this->mTitle
->getPrefixedDBkey();
3551 $shortTitle = $this->mTitle
->getDBkey();
3554 wfProfileOut( __METHOD__
);
3558 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3559 array_push( $wgDeferredUpdateList, $u );
3560 $u = new SearchUpdate( $id, $title, $text );
3561 array_push( $wgDeferredUpdateList, $u );
3563 # If this is another user's talk page, update newtalk
3564 # Don't do this if $changed = false otherwise some idiot can null-edit a
3565 # load of user talk pages and piss people off, nor if it's a minor edit
3566 # by a properly-flagged bot.
3567 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3568 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3570 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3571 $other = User
::newFromName( $shortTitle, false );
3573 wfDebug( __METHOD__
. ": invalid username\n" );
3574 } elseif ( User
::isIP( $shortTitle ) ) {
3575 // An anonymous user
3576 $other->setNewtalk( true );
3577 } elseif ( $other->isLoggedIn() ) {
3578 $other->setNewtalk( true );
3580 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3585 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3586 MessageCache
::singleton()->replace( $shortTitle, $text );
3589 wfProfileOut( __METHOD__
);
3593 * Perform article updates on a special page creation.
3595 * @param $rev Revision object
3597 * @todo This is a shitty interface function. Kill it and replace the
3598 * other shitty functions like editUpdates and such so it's not needed
3601 public function createUpdates( $rev ) {
3602 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3603 $this->mTotalAdjustment
= 1;
3604 $this->editUpdates( $rev->getText(), $rev->getComment(),
3605 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3609 * Generate the navigation links when browsing through an article revisions
3610 * It shows the information as:
3611 * Revision as of \<date\>; view current revision
3612 * \<- Previous version | Next Version -\>
3614 * @param $oldid String: revision ID of this article revision
3616 public function setOldSubtitle( $oldid = 0 ) {
3617 global $wgLang, $wgOut, $wgUser, $wgRequest;
3619 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3623 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3625 # Cascade unhide param in links for easy deletion browsing
3626 $extraParams = array();
3627 if ( $wgRequest->getVal( 'unhide' ) ) {
3628 $extraParams['unhide'] = 1;
3631 $revision = Revision
::newFromId( $oldid );
3633 $current = ( $oldid == $this->mLatest
);
3634 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3635 $tddate = $wgLang->date( $this->mTimestamp
, true );
3636 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3637 $sk = $wgUser->getSkin();
3639 ?
wfMsgHtml( 'currentrevisionlink' )
3642 wfMsgHtml( 'currentrevisionlink' ),
3645 array( 'known', 'noclasses' )
3648 ?
wfMsgHtml( 'diff' )
3651 wfMsgHtml( 'diff' ),
3657 array( 'known', 'noclasses' )
3659 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3663 wfMsgHtml( 'previousrevision' ),
3666 'direction' => 'prev',
3669 array( 'known', 'noclasses' )
3671 : wfMsgHtml( 'previousrevision' );
3675 wfMsgHtml( 'diff' ),
3681 array( 'known', 'noclasses' )
3683 : wfMsgHtml( 'diff' );
3684 $nextlink = $current
3685 ?
wfMsgHtml( 'nextrevision' )
3688 wfMsgHtml( 'nextrevision' ),
3691 'direction' => 'next',
3694 array( 'known', 'noclasses' )
3696 $nextdiff = $current
3697 ?
wfMsgHtml( 'diff' )
3700 wfMsgHtml( 'diff' ),
3706 array( 'known', 'noclasses' )
3711 // User can delete revisions or view deleted revisions...
3712 $canHide = $wgUser->isAllowed( 'deleterevision' );
3713 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3714 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3715 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3718 'type' => 'revision',
3719 'target' => $this->mTitle
->getPrefixedDbkey(),
3722 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3727 # Show user links if allowed to see them. If hidden, then show them only if requested...
3728 $userlinks = $sk->revUserTools( $revision, !$unhide );
3730 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3731 ?
'revision-info-current'
3734 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3737 array( 'parseinline', 'replaceafter' ),
3743 $revision->getUser()
3746 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3747 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3749 $wgOut->addHTML( $r );
3753 * This function is called right before saving the wikitext,
3754 * so we can do things like signatures and links-in-context.
3756 * @param $text String article contents
3757 * @param $user User object: user doing the edit, $wgUser will be used if
3759 * @param $popts ParserOptions object: parser options, default options for
3760 * the user loaded if null given
3761 * @return string article contents with altered wikitext markup (signatures
3762 * converted, {{subst:}}, templates, etc.)
3764 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3767 if ( $user === null ) {
3772 if ( $popts === null ) {
3773 $popts = ParserOptions
::newFromUser( $user );
3776 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3779 /* Caching functions */
3782 * checkLastModified returns true if it has taken care of all
3783 * output to the client that is necessary for this request.
3784 * (that is, it has sent a cached version of the page)
3786 * @return boolean true if cached version send, false otherwise
3788 protected function tryFileCache() {
3789 static $called = false;
3792 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3797 if ( $this->isFileCacheable() ) {
3798 $cache = new HTMLFileCache( $this->mTitle
);
3799 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3800 wfDebug( "Article::tryFileCache(): about to load file\n" );
3801 $cache->loadFromFileCache();
3804 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3805 ob_start( array( &$cache, 'saveToFileCache' ) );
3808 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3815 * Check if the page can be cached
3818 public function isFileCacheable() {
3821 if ( HTMLFileCache
::useFileCache() ) {
3822 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3823 // Extension may have reason to disable file caching on some pages.
3825 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3833 * Loads page_touched and returns a value indicating if it should be used
3834 * @return boolean true if not a redirect
3836 public function checkTouched() {
3837 if ( !$this->mDataLoaded
) {
3838 $this->loadPageData();
3841 return !$this->mIsRedirect
;
3845 * Get the page_touched field
3846 * @return string containing GMT timestamp
3848 public function getTouched() {
3849 if ( !$this->mDataLoaded
) {
3850 $this->loadPageData();
3853 return $this->mTouched
;
3857 * Get the page_latest field
3858 * @return integer rev_id of current revision
3860 public function getLatest() {
3861 if ( !$this->mDataLoaded
) {
3862 $this->loadPageData();
3865 return (int)$this->mLatest
;
3869 * Edit an article without doing all that other stuff
3870 * The article must already exist; link tables etc
3871 * are not updated, caches are not flushed.
3873 * @param $text String: text submitted
3874 * @param $comment String: comment submitted
3875 * @param $minor Boolean: whereas it's a minor modification
3877 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3878 wfProfileIn( __METHOD__
);
3880 $dbw = wfGetDB( DB_MASTER
);
3881 $revision = new Revision( array(
3882 'page' => $this->getId(),
3884 'comment' => $comment,
3885 'minor_edit' => $minor ?
1 : 0,
3887 $revision->insertOn( $dbw );
3888 $this->updateRevisionOn( $dbw, $revision );
3891 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3893 wfProfileOut( __METHOD__
);
3897 * The onArticle*() functions are supposed to be a kind of hooks
3898 * which should be called whenever any of the specified actions
3901 * This is a good place to put code to clear caches, for instance.
3903 * This is called on page move and undelete, as well as edit
3905 * @param $title Title object
3907 public static function onArticleCreate( $title ) {
3908 # Update existence markers on article/talk tabs...
3909 if ( $title->isTalkPage() ) {
3910 $other = $title->getSubjectPage();
3912 $other = $title->getTalkPage();
3915 $other->invalidateCache();
3916 $other->purgeSquid();
3918 $title->touchLinks();
3919 $title->purgeSquid();
3920 $title->deleteTitleProtection();
3924 * Clears caches when article is deleted
3926 public static function onArticleDelete( $title ) {
3927 # Update existence markers on article/talk tabs...
3928 if ( $title->isTalkPage() ) {
3929 $other = $title->getSubjectPage();
3931 $other = $title->getTalkPage();
3934 $other->invalidateCache();
3935 $other->purgeSquid();
3937 $title->touchLinks();
3938 $title->purgeSquid();
3941 HTMLFileCache
::clearFileCache( $title );
3944 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3945 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3949 if ( $title->getNamespace() == NS_FILE
) {
3950 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3951 $update->doUpdate();
3955 if ( $title->getNamespace() == NS_USER_TALK
) {
3956 $user = User
::newFromName( $title->getText(), false );
3957 $user->setNewtalk( false );
3961 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3965 * Purge caches on page update etc
3967 * @param $title Title object
3968 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3970 public static function onArticleEdit( $title ) {
3971 global $wgDeferredUpdateList;
3973 // Invalidate caches of articles which include this page
3974 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3976 // Invalidate the caches of all pages which redirect here
3977 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3979 # Purge squid for this page only
3980 $title->purgeSquid();
3982 # Clear file cache for this page only
3983 HTMLFileCache
::clearFileCache( $title );
3989 * Overriden by ImagePage class, only present here to avoid a fatal error
3990 * Called for ?action=revert
3992 public function revert() {
3994 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3998 * Info about this page
3999 * Called for ?action=info when $wgAllowPageInfo is on.
4001 public function info() {
4002 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4004 if ( !$wgAllowPageInfo ) {
4005 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4009 $page = $this->mTitle
->getSubjectPage();
4011 $wgOut->setPagetitle( $page->getPrefixedText() );
4012 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4013 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4015 if ( !$this->mTitle
->exists() ) {
4016 $wgOut->addHTML( '<div class="noarticletext">' );
4017 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
4018 // This doesn't quite make sense; the user is asking for
4019 // information about the _page_, not the message... -- RC
4020 $wgOut->addHTML( htmlspecialchars( $this->mTitle
->getDefaultMessageText() ) );
4022 $msg = $wgUser->isLoggedIn()
4024 : 'noarticletextanon';
4025 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4028 $wgOut->addHTML( '</div>' );
4030 $dbr = wfGetDB( DB_SLAVE
);
4032 'wl_title' => $page->getDBkey(),
4033 'wl_namespace' => $page->getNamespace() );
4034 $numwatchers = $dbr->selectField(
4040 $pageInfo = $this->pageCountInfo( $page );
4041 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4044 //FIXME: unescaped messages
4045 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4046 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4049 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4052 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4055 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4058 $wgOut->addHTML( '</ul>' );
4063 * Return the total number of edits and number of unique editors
4064 * on a given page. If page does not exist, returns false.
4066 * @param $title Title object
4067 * @return mixed array or boolean false
4069 public function pageCountInfo( $title ) {
4070 $id = $title->getArticleId();
4076 $dbr = wfGetDB( DB_SLAVE
);
4077 $rev_clause = array( 'rev_page' => $id );
4078 $edits = $dbr->selectField(
4084 $authors = $dbr->selectField(
4086 'COUNT(DISTINCT rev_user_text)',
4091 return array( 'edits' => $edits, 'authors' => $authors );
4095 * Return a list of templates used by this article.
4096 * Uses the templatelinks table
4098 * @return Array of Title objects
4100 public function getUsedTemplates() {
4102 $id = $this->mTitle
->getArticleID();
4108 $dbr = wfGetDB( DB_SLAVE
);
4109 $res = $dbr->select( array( 'templatelinks' ),
4110 array( 'tl_namespace', 'tl_title' ),
4111 array( 'tl_from' => $id ),
4114 if ( $res !== false ) {
4115 foreach ( $res as $row ) {
4116 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4124 * Returns a list of hidden categories this page is a member of.
4125 * Uses the page_props and categorylinks tables.
4127 * @return Array of Title objects
4129 public function getHiddenCategories() {
4131 $id = $this->mTitle
->getArticleID();
4137 $dbr = wfGetDB( DB_SLAVE
);
4138 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4140 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4141 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4144 if ( $res !== false ) {
4145 foreach ( $res as $row ) {
4146 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4154 * Return an applicable autosummary if one exists for the given edit.
4155 * @param $oldtext String: the previous text of the page.
4156 * @param $newtext String: The submitted text of the page.
4157 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4158 * @return string An appropriate autosummary, or an empty string.
4160 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4163 # Decide what kind of autosummary is needed.
4165 # Redirect autosummaries
4166 $ot = Title
::newFromRedirect( $oldtext );
4167 $rt = Title
::newFromRedirect( $newtext );
4169 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4170 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4173 # New page autosummaries
4174 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4175 # If they're making a new article, give its text, truncated, in the summary.
4177 $truncatedtext = $wgContLang->truncate(
4178 str_replace( "\n", ' ', $newtext ),
4179 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4181 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4184 # Blanking autosummaries
4185 if ( $oldtext != '' && $newtext == '' ) {
4186 return wfMsgForContent( 'autosumm-blank' );
4187 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4188 # Removing more than 90% of the article
4190 $truncatedtext = $wgContLang->truncate(
4192 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4194 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4197 # If we reach this point, there's no applicable autosummary for our case, so our
4198 # autosummary is empty.
4203 * Add the primary page-view wikitext to the output buffer
4204 * Saves the text into the parser cache if possible.
4205 * Updates templatelinks if it is out of date.
4207 * @param $text String
4208 * @param $cache Boolean
4209 * @param $parserOptions mixed ParserOptions object, or boolean false
4211 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4214 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4215 $wgOut->addParserOutput( $this->mParserOutput
);
4219 * This does all the heavy lifting for outputWikitext, except it returns the parser
4220 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4221 * say, embedding thread pages within a discussion system (LiquidThreads)
4223 * @param $text string
4224 * @param $cache boolean
4225 * @param $parserOptions parsing options, defaults to false
4226 * @return string containing parsed output
4228 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4229 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4231 if ( !$parserOptions ) {
4232 $parserOptions = $this->getParserOptions();
4236 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4237 $parserOptions, true, true, $this->getRevIdFetched() );
4242 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4243 $this->mTitle
->getPrefixedDBkey() ) );
4246 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4247 $parserCache = ParserCache
::singleton();
4248 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4251 // Make sure file cache is not used on uncacheable content.
4252 // Output that has magic words in it can still use the parser cache
4253 // (if enabled), though it will generally expire sooner.
4254 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4255 $wgUseFileCache = false;
4258 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4260 return $this->mParserOutput
;
4264 * Get parser options suitable for rendering the primary article wikitext
4265 * @return mixed ParserOptions object or boolean false
4267 public function getParserOptions() {
4270 if ( !$this->mParserOptions
) {
4271 $this->mParserOptions
= new ParserOptions( $wgUser );
4272 $this->mParserOptions
->setTidy( true );
4273 $this->mParserOptions
->enableLimitReport();
4276 // Clone to allow modifications of the return value without affecting
4278 return clone $this->mParserOptions
;
4282 * Updates cascading protections
4284 * @param $parserOutput mixed ParserOptions object, or boolean false
4286 protected function doCascadeProtectionUpdates( $parserOutput ) {
4287 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4291 // templatelinks table may have become out of sync,
4292 // especially if using variable-based transclusions.
4293 // For paranoia, check if things have changed and if
4294 // so apply updates to the database. This will ensure
4295 // that cascaded protections apply as soon as the changes
4298 # Get templates from templatelinks
4299 $id = $this->mTitle
->getArticleID();
4301 $tlTemplates = array();
4303 $dbr = wfGetDB( DB_SLAVE
);
4304 $res = $dbr->select( array( 'templatelinks' ),
4305 array( 'tl_namespace', 'tl_title' ),
4306 array( 'tl_from' => $id ),
4310 foreach ( $res as $row ) {
4311 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4314 # Get templates from parser output.
4315 $poTemplates = array();
4316 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4317 foreach ( $templates as $dbk => $id ) {
4318 $poTemplates["$ns:$dbk"] = true;
4323 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4325 if ( count( $templates_diff ) > 0 ) {
4326 # Whee, link updates time.
4327 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4333 * Update all the appropriate counts in the category table, given that
4334 * we've added the categories $added and deleted the categories $deleted.
4336 * @param $added array The names of categories that were added
4337 * @param $deleted array The names of categories that were deleted
4339 public function updateCategoryCounts( $added, $deleted ) {
4340 $ns = $this->mTitle
->getNamespace();
4341 $dbw = wfGetDB( DB_MASTER
);
4343 # First make sure the rows exist. If one of the "deleted" ones didn't
4344 # exist, we might legitimately not create it, but it's simpler to just
4345 # create it and then give it a negative value, since the value is bogus
4348 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4349 $insertCats = array_merge( $added, $deleted );
4350 if ( !$insertCats ) {
4351 # Okay, nothing to do
4355 $insertRows = array();
4357 foreach ( $insertCats as $cat ) {
4358 $insertRows[] = array(
4359 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4363 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4365 $addFields = array( 'cat_pages = cat_pages + 1' );
4366 $removeFields = array( 'cat_pages = cat_pages - 1' );
4368 if ( $ns == NS_CATEGORY
) {
4369 $addFields[] = 'cat_subcats = cat_subcats + 1';
4370 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4371 } elseif ( $ns == NS_FILE
) {
4372 $addFields[] = 'cat_files = cat_files + 1';
4373 $removeFields[] = 'cat_files = cat_files - 1';
4380 array( 'cat_title' => $added ),
4389 array( 'cat_title' => $deleted ),
4396 * Lightweight method to get the parser output for a page, checking the parser cache
4397 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4398 * consider, so it's not appropriate to use there.
4400 * @since 1.16 (r52326) for LiquidThreads
4402 * @param $oldid mixed integer Revision ID or null
4403 * @return ParserOutput or false if the given revsion ID is not found
4405 public function getParserOutput( $oldid = null ) {
4406 global $wgEnableParserCache, $wgUser;
4408 // Should the parser cache be used?
4409 $useParserCache = $wgEnableParserCache &&
4410 $wgUser->getStubThreshold() == 0 &&
4414 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4416 if ( $wgUser->getStubThreshold() ) {
4417 wfIncrStats( 'pcache_miss_stub' );
4420 if ( $useParserCache ) {
4421 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4422 if ( $parserOutput !== false ) {
4423 return $parserOutput;
4427 // Cache miss; parse and output it.
4428 if ( $oldid === null ) {
4429 $text = $this->getRawText();
4431 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4432 if ( $rev === null ) {
4435 $text = $rev->getText();
4438 return $this->getOutputFromWikitext( $text, $useParserCache );
4442 * Sets the context this Article is executed in
4444 * @param $context RequestContext
4447 public function setContext( $context ) {
4448 $this->mContext
= $context;
4452 * Gets the context this Article is executed in
4454 * @return RequestContext
4457 public function getContext() {
4458 if ( $this->mContext
instanceof RequestContext
) {
4459 return $this->mContext
;
4461 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4462 return RequestContext
::getMain();
4468 class PoolWorkArticleView
extends PoolCounterWork
{
4471 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4472 parent
::__construct( 'ArticleView', $key );
4473 $this->mArticle
= $article;
4474 $this->cacheable
= $useParserCache;
4475 $this->parserOptions
= $parserOptions;
4479 return $this->mArticle
->doViewParse();
4482 function getCachedWork() {
4485 $parserCache = ParserCache
::singleton();
4486 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4488 if ( $this->mArticle
->mParserOutput
!== false ) {
4489 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4490 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4491 # Ensure that UI elements requiring revision ID have
4492 # the correct version information.
4493 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4499 function fallback() {
4500 return $this->mArticle
->tryDirtyCache();
4503 function error( $status ) {
4506 $wgOut->clearHTML(); // for release() errors
4507 $wgOut->enableClientCache( false );
4508 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4510 $errortext = $status->getWikiText( false, 'view-pool-error' );
4511 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );