8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
14 * @internal documentation reviewed 15 Mar 2010
27 var $mContentLoaded = false; // !<
28 var $mCounter = -1; // !< Not loaded
29 var $mDataLoaded = false; // !<
30 var $mGoodAdjustment = 0; // !<
31 var $mIsRedirect = false; // !<
32 var $mLatest = false; // !<
34 var $mPreparedEdit = false;
39 var $mRedirectedFrom = null;
44 var $mRedirectTarget = null;
49 var $mRedirectUrl = false; // !<
50 var $mRevIdFetched = 0; // !<
55 var $mLastRevision = null;
60 var $mRevision = null;
62 var $mTimestamp = ''; // !<
63 var $mTitle; // !< Title object
64 var $mTotalAdjustment = 0; // !<
65 var $mTouched = '19700101000000'; // !<
80 * Constructor and clear the article
81 * @param $title Reference to a Title object.
82 * @param $oldId Integer revision ID, null to fetch from request, zero for current
84 public function __construct( Title
$title, $oldId = null ) {
85 // FIXME: does the reference play any role here?
86 $this->mTitle
=& $title;
87 $this->mOldId
= $oldId;
91 * Constructor from an page id
92 * @param $id Int article ID to load
94 public static function newFromID( $id ) {
95 $t = Title
::newFromID( $id );
96 # FIXME: doesn't inherit right
97 return $t == null ?
null : new self( $t );
98 # return $t == null ? null : new static( $t ); // PHP 5.3
102 * Tell the page view functions that this view was redirected
103 * from another page on the wiki.
104 * @param $from Title object.
106 public function setRedirectedFrom( Title
$from ) {
107 $this->mRedirectedFrom
= $from;
111 * If this page is a redirect, get its target
113 * The target will be fetched from the redirect table if possible.
114 * If this page doesn't have an entry there, call insertRedirect()
115 * @return mixed Title object, or null if this page is not a redirect
117 public function getRedirectTarget() {
118 if ( !$this->mTitle
->isRedirect() ) {
122 if ( $this->mRedirectTarget
!== null ) {
123 return $this->mRedirectTarget
;
126 # Query the redirect table
127 $dbr = wfGetDB( DB_SLAVE
);
128 $row = $dbr->selectRow( 'redirect',
129 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
130 array( 'rd_from' => $this->getID() ),
134 // rd_fragment and rd_interwiki were added later, populate them if empty
135 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
136 return $this->mRedirectTarget
= Title
::makeTitle(
137 $row->rd_namespace
, $row->rd_title
,
138 $row->rd_fragment
, $row->rd_interwiki
);
141 # This page doesn't have an entry in the redirect table
142 return $this->mRedirectTarget
= $this->insertRedirect();
146 * Insert an entry for this page into the redirect table.
148 * Don't call this function directly unless you know what you're doing.
149 * @return Title object or null if not a redirect
151 public function insertRedirect() {
152 // recurse through to only get the final target
153 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
157 $this->insertRedirectEntry( $retval );
162 * Insert or update the redirect table entry for this page to indicate
163 * it redirects to $rt .
164 * @param $rt Title redirect target
166 public function insertRedirectEntry( $rt ) {
167 $dbw = wfGetDB( DB_MASTER
);
168 $dbw->replace( 'redirect', array( 'rd_from' ),
170 'rd_from' => $this->getID(),
171 'rd_namespace' => $rt->getNamespace(),
172 'rd_title' => $rt->getDBkey(),
173 'rd_fragment' => $rt->getFragment(),
174 'rd_interwiki' => $rt->getInterwiki(),
181 * Get the Title object or URL this page redirects to
183 * @return mixed false, Title of in-wiki target, or string with URL
185 public function followRedirect() {
186 return $this->getRedirectURL( $this->getRedirectTarget() );
190 * Get the Title object this text redirects to
192 * @param $text string article content containing redirect info
193 * @return mixed false, Title of in-wiki target, or string with URL
194 * @deprecated since 1.17
196 public function followRedirectText( $text ) {
197 // recurse through to only get the final target
198 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
202 * Get the Title object or URL to use for a redirect. We use Title
203 * objects for same-wiki, non-special redirects and URLs for everything
205 * @param $rt Title Redirect target
206 * @return mixed false, Title object of local target, or string with URL
208 public function getRedirectURL( $rt ) {
210 if ( $rt->getInterwiki() != '' ) {
211 if ( $rt->isLocal() ) {
212 // Offsite wikis need an HTTP redirect.
214 // This can be hard to reverse and may produce loops,
215 // so they may be disabled in the site configuration.
216 $source = $this->mTitle
->getFullURL( 'redirect=no' );
217 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
220 if ( $rt->getNamespace() == NS_SPECIAL
) {
221 // Gotta handle redirects to special pages differently:
222 // Fill the HTTP response "Location" header and ignore
223 // the rest of the page we're on.
225 // This can be hard to reverse, so they may be disabled.
226 if ( $rt->isSpecial( 'Userlogout' ) ) {
229 return $rt->getFullURL();
237 // No or invalid redirect
242 * Get the title object of the article
243 * @return Title object of this page
245 public function getTitle() {
246 return $this->mTitle
;
251 * FIXME: shouldn't this be public?
254 public function clear() {
255 $this->mDataLoaded
= false;
256 $this->mContentLoaded
= false;
258 $this->mCounter
= -1; # Not loaded
259 $this->mRedirectedFrom
= null; # Title object if set
260 $this->mRedirectTarget
= null; # Title object if set
261 $this->mLastRevision
= null; # Latest revision
262 $this->mTimestamp
= '';
263 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
264 $this->mTouched
= '19700101000000';
265 $this->mIsRedirect
= false;
266 $this->mRevIdFetched
= 0;
267 $this->mRedirectUrl
= false;
268 $this->mLatest
= false;
269 $this->mPreparedEdit
= false;
273 * Note that getContent/loadContent do not follow redirects anymore.
274 * If you need to fetch redirectable content easily, try
275 * the shortcut in Article::followRedirect()
277 * This function has side effects! Do not use this function if you
278 * only want the real revision text if any.
280 * @return Return the text of this revision
282 public function getContent() {
285 wfProfileIn( __METHOD__
);
287 if ( $this->getID() === 0 ) {
288 # If this is a MediaWiki:x message, then load the messages
289 # and return the message value for x.
290 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
291 $text = $this->mTitle
->getDefaultMessageText();
292 if ( $text === false ) {
296 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
298 wfProfileOut( __METHOD__
);
302 $this->loadContent();
303 wfProfileOut( __METHOD__
);
305 return $this->mContent
;
310 * Get the text of the current revision. No side-effects...
312 * @return Return the text of the current revision
314 public function getRawText() {
315 // Check process cache for current revision
316 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
317 return $this->mContent
;
320 $rev = Revision
::newFromTitle( $this->mTitle
);
321 $text = $rev ?
$rev->getRawText() : false;
327 * Get the text that needs to be saved in order to undo all revisions
328 * between $undo and $undoafter. Revisions must belong to the same page,
329 * must exist and must not be deleted
330 * @param $undo Revision
331 * @param $undoafter Revision Must be an earlier revision than $undo
332 * @return mixed string on success, false on failure
334 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
335 $currentRev = Revision
::newFromTitle( $this->mTitle
);
336 if ( !$currentRev ) {
337 return false; // no page
339 $undo_text = $undo->getText();
340 $undoafter_text = $undoafter->getText();
341 $cur_text = $currentRev->getText();
343 if ( $cur_text == $undo_text ) {
344 # No use doing a merge if it's just a straight revert.
345 return $undoafter_text;
350 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
358 * @return int The oldid of the article that is to be shown, 0 for the
361 public function getOldID() {
362 if ( is_null( $this->mOldId
) ) {
363 $this->mOldId
= $this->getOldIDFromRequest();
366 return $this->mOldId
;
370 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
372 * @return int The old id for the request
374 public function getOldIDFromRequest() {
377 $this->mRedirectUrl
= false;
379 $oldid = $wgRequest->getVal( 'oldid' );
381 if ( isset( $oldid ) ) {
382 $oldid = intval( $oldid );
383 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
384 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
388 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
390 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
391 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
406 * Load the revision (including text) into this object
408 function loadContent() {
409 if ( $this->mContentLoaded
) {
413 wfProfileIn( __METHOD__
);
415 $this->fetchContent( $this->getOldID() );
417 wfProfileOut( __METHOD__
);
421 * Return the list of revision fields that should be selected to create
424 public static function selectFields() {
441 * Fetch a page record with the given conditions
442 * @param $dbr DatabaseBase object
443 * @param $conditions Array
444 * @return mixed Database result resource, or false on failure
446 protected function pageData( $dbr, $conditions ) {
447 $fields = self
::selectFields();
449 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
451 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
453 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
459 * Fetch a page record matching the Title object's namespace and title
460 * using a sanitized title string
462 * @param $dbr DatabaseBase object
463 * @param $title Title object
464 * @return mixed Database result resource, or false on failure
466 protected function pageDataFromTitle( $dbr, $title ) {
467 return $this->pageData( $dbr, array(
468 'page_namespace' => $title->getNamespace(),
469 'page_title' => $title->getDBkey() ) );
473 * Fetch a page record matching the requested ID
475 * @param $dbr DatabaseBase
477 * @return mixed Database result resource, or false on failure
479 protected function pageDataFromId( $dbr, $id ) {
480 return $this->pageData( $dbr, array( 'page_id' => $id ) );
484 * Set the general counter, title etc data loaded from
487 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
489 public function loadPageData( $data = 'fromdb' ) {
490 if ( $data === 'fromdb' ) {
491 $dbr = wfGetDB( DB_SLAVE
);
492 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
495 $lc = LinkCache
::singleton();
498 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
500 $this->mTitle
->mArticleID
= intval( $data->page_id
);
502 # Old-fashioned restrictions
503 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
505 $this->mCounter
= intval( $data->page_counter
);
506 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
507 $this->mIsRedirect
= intval( $data->page_is_redirect
);
508 $this->mLatest
= intval( $data->page_latest
);
510 $lc->addBadLinkObj( $this->mTitle
);
511 $this->mTitle
->mArticleID
= 0;
514 $this->mDataLoaded
= true;
518 * Get text of an article from database
519 * Does *NOT* follow redirects.
521 * @param $oldid Int: 0 for whatever the latest revision is
522 * @return mixed string containing article contents, or false if null
524 function fetchContent( $oldid = 0 ) {
525 if ( $this->mContentLoaded
) {
526 return $this->mContent
;
529 # Pre-fill content with error message so that if something
530 # fails we'll have something telling us what we intended.
531 $t = $this->mTitle
->getPrefixedText();
532 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
533 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
536 $revision = Revision
::newFromId( $oldid );
537 if ( $revision === null ) {
538 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
542 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
543 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
546 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
550 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
551 $this->loadPageData( $data );
554 if ( !$this->mDataLoaded
) {
555 $this->loadPageData();
558 if ( $this->mLatest
=== false ) {
559 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
563 $revision = Revision
::newFromId( $this->mLatest
);
564 if ( $revision === null ) {
565 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
570 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
571 // We should instead work with the Revision object when we need it...
572 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
574 if ( $revision->getId() == $this->mLatest
) {
575 $this->setLastEdit( $revision );
578 $this->mRevIdFetched
= $revision->getId();
579 $this->mContentLoaded
= true;
580 $this->mRevision
=& $revision;
582 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
584 return $this->mContent
;
589 * @deprecated since 1.18
591 public function forUpdate() {
592 wfDeprecated( __METHOD__
);
596 * @return int Page ID
598 public function getID() {
599 return $this->mTitle
->getArticleID();
603 * @return bool Whether or not the page exists in the database
605 public function exists() {
606 return $this->getId() > 0;
610 * Check if this page is something we're going to be showing
611 * some sort of sensible content for. If we return false, page
612 * views (plain action=view) will return an HTTP 404 response,
613 * so spiders and robots can know they're following a bad link.
617 public function hasViewableContent() {
618 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
622 * @return int The view count for the page
624 public function getCount() {
625 if ( -1 == $this->mCounter
) {
626 $id = $this->getID();
631 $dbr = wfGetDB( DB_SLAVE
);
632 $this->mCounter
= $dbr->selectField( 'page',
634 array( 'page_id' => $id ),
640 return $this->mCounter
;
644 * Determine whether a page would be suitable for being counted as an
645 * article in the site_stats table based on the title & its content
647 * @param $text String: text to analyze
650 public function isCountable( $text ) {
651 global $wgUseCommaCount;
653 $token = $wgUseCommaCount ?
',' : '[[';
655 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
659 * Tests if the article text represents a redirect
661 * @param $text mixed string containing article contents, or boolean
664 public function isRedirect( $text = false ) {
665 if ( $text === false ) {
666 if ( !$this->mDataLoaded
) {
667 $this->loadPageData();
670 return (bool)$this->mIsRedirect
;
672 return Title
::newFromRedirect( $text ) !== null;
677 * Returns true if the currently-referenced revision is the current edit
678 * to this page (and it exists).
681 public function isCurrent() {
682 # If no oldid, this is the current version.
683 if ( $this->getOldID() == 0 ) {
687 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
691 * Loads everything except the text
692 * This isn't necessary for all uses, so it's only done if needed.
694 protected function loadLastEdit() {
695 if ( $this->mLastRevision
!== null ) {
696 return; // already loaded
699 # New or non-existent articles have no user information
700 $id = $this->getID();
705 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
707 $this->setLastEdit( $revision );
712 * Set the latest revision
714 protected function setLastEdit( Revision
$revision ) {
715 $this->mLastRevision
= $revision;
716 $this->mTimestamp
= $revision->getTimestamp();
720 * @return string GMT timestamp of last article revision
722 public function getTimestamp() {
723 // Check if the field has been filled by ParserCache::get()
724 if ( !$this->mTimestamp
) {
725 $this->loadLastEdit();
727 return wfTimestamp( TS_MW
, $this->mTimestamp
);
731 * @param $audience Integer: one of:
732 * Revision::FOR_PUBLIC to be displayed to all users
733 * Revision::FOR_THIS_USER to be displayed to $wgUser
734 * Revision::RAW get the text regardless of permissions
735 * @return int user ID for the user that made the last article revision
737 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
738 $this->loadLastEdit();
739 if ( $this->mLastRevision
) {
740 return $this->mLastRevision
->getUser( $audience );
747 * @param $audience Integer: one of:
748 * Revision::FOR_PUBLIC to be displayed to all users
749 * Revision::FOR_THIS_USER to be displayed to $wgUser
750 * Revision::RAW get the text regardless of permissions
751 * @return string username of the user that made the last article revision
753 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
754 $this->loadLastEdit();
755 if ( $this->mLastRevision
) {
756 return $this->mLastRevision
->getUserText( $audience );
763 * @param $audience Integer: one of:
764 * Revision::FOR_PUBLIC to be displayed to all users
765 * Revision::FOR_THIS_USER to be displayed to $wgUser
766 * Revision::RAW get the text regardless of permissions
767 * @return string Comment stored for the last article revision
769 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
770 $this->loadLastEdit();
771 if ( $this->mLastRevision
) {
772 return $this->mLastRevision
->getComment( $audience );
779 * Returns true if last revision was marked as "minor edit"
781 * @return boolean Minor edit indicator for the last article revision.
783 public function getMinorEdit() {
784 $this->loadLastEdit();
785 if ( $this->mLastRevision
) {
786 return $this->mLastRevision
->isMinor();
793 * Use this to fetch the rev ID used on page views
795 * @return int revision ID of last article revision
797 public function getRevIdFetched() {
798 if ( $this->mRevIdFetched
) {
799 return $this->mRevIdFetched
;
801 return $this->getLatest();
806 * Get a list of users who have edited this article, not including the user who made
807 * the most recent revision, which you can get from $article->getUser() if you want it
810 public function getContributors() {
811 # FIXME: this is expensive; cache this info somewhere.
813 $dbr = wfGetDB( DB_SLAVE
);
814 $userTable = $dbr->tableName( 'user' );
816 if ( $dbr->implicitGroupby() ) {
817 $realNameField = 'user_real_name';
819 $realNameField = 'FIRST(user_real_name) AS user_real_name';
822 $tables = array( 'revision', 'user' );
825 'rev_user as user_id',
826 'rev_user_text AS user_name',
828 'MAX(rev_timestamp) AS timestamp',
831 $conds = array( 'rev_page' => $this->getId() );
833 // The user who made the top revision gets credited as "this page was last edited by
834 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
835 $user = $this->getUser();
837 $conds[] = "rev_user != $user";
839 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
842 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
845 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
849 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
850 'ORDER BY' => 'timestamp DESC',
853 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
854 return new UserArrayFromResult( $res );
858 * This is the default action of the index.php entry point: just view the
859 * page of the given title.
861 public function view() {
862 global $wgUser, $wgOut, $wgRequest, $wgParser;
863 global $wgUseFileCache, $wgUseETag;
865 wfProfileIn( __METHOD__
);
867 # Get variables from query string
868 $oldid = $this->getOldID();
870 # getOldID may want us to redirect somewhere else
871 if ( $this->mRedirectUrl
) {
872 $wgOut->redirect( $this->mRedirectUrl
);
873 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
874 wfProfileOut( __METHOD__
);
879 $wgOut->setArticleFlag( true );
880 # Set page title (may be overridden by DISPLAYTITLE)
881 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
883 # If we got diff in the query, we want to see a diff page instead of the article.
884 if ( $wgRequest->getCheck( 'diff' ) ) {
885 wfDebug( __METHOD__
. ": showing diff page\n" );
886 $this->showDiffPage();
887 wfProfileOut( __METHOD__
);
892 # Allow frames by default
893 $wgOut->allowClickjacking();
895 $parserCache = ParserCache
::singleton();
897 $parserOptions = $this->getParserOptions();
898 # Render printable version, use printable version cache
899 if ( $wgOut->isPrintable() ) {
900 $parserOptions->setIsPrintable( true );
901 $parserOptions->setEditSection( false );
902 } else if ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
903 $parserOptions->setEditSection( false );
906 # Try client and file cache
907 if ( $oldid === 0 && $this->checkTouched() ) {
909 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
912 # Is it client cached?
913 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
914 wfDebug( __METHOD__
. ": done 304\n" );
915 wfProfileOut( __METHOD__
);
919 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
920 wfDebug( __METHOD__
. ": done file cache\n" );
921 # tell wgOut that output is taken care of
923 $this->viewUpdates();
924 wfProfileOut( __METHOD__
);
930 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
931 $parserOptions->setEditSection( false );
934 # Should the parser cache be used?
935 $useParserCache = $this->useParserCache( $oldid );
936 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
937 if ( $wgUser->getStubThreshold() ) {
938 wfIncrStats( 'pcache_miss_stub' );
941 $wasRedirected = $this->showRedirectedFromHeader();
942 $this->showNamespaceHeader();
944 # Iterate through the possible ways of constructing the output text.
945 # Keep going until $outputDone is set, or we run out of things to do.
948 $this->mParserOutput
= false;
950 while ( !$outputDone && ++
$pass ) {
953 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
956 # Try the parser cache
957 if ( $useParserCache ) {
958 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
960 if ( $this->mParserOutput
!== false ) {
961 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
962 $wgOut->addParserOutput( $this->mParserOutput
);
963 # Ensure that UI elements requiring revision ID have
964 # the correct version information.
965 $wgOut->setRevisionId( $this->mLatest
);
971 $text = $this->getContent();
972 if ( $text === false ||
$this->getID() == 0 ) {
973 wfDebug( __METHOD__
. ": showing missing article\n" );
974 $this->showMissingArticle();
975 wfProfileOut( __METHOD__
);
979 # Another whitelist check in case oldid is altering the title
980 if ( !$this->mTitle
->userCanRead() ) {
981 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
982 $wgOut->loginToUse();
985 wfProfileOut( __METHOD__
);
989 # Are we looking at an old revision
990 if ( $oldid && !is_null( $this->mRevision
) ) {
991 $this->setOldSubtitle( $oldid );
993 if ( !$this->showDeletedRevisionHeader() ) {
994 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
995 wfProfileOut( __METHOD__
);
999 # If this "old" version is the current, then try the parser cache...
1000 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
1001 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
1002 if ( $this->mParserOutput
) {
1003 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
1004 $wgOut->addParserOutput( $this->mParserOutput
);
1005 $wgOut->setRevisionId( $this->mLatest
);
1012 # Ensure that UI elements requiring revision ID have
1013 # the correct version information.
1014 $wgOut->setRevisionId( $this->getRevIdFetched() );
1016 # Pages containing custom CSS or JavaScript get special treatment
1017 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1018 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1019 $this->showCssOrJsPage();
1022 $rt = Title
::newFromRedirectArray( $text );
1024 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1025 # Viewing a redirect page (e.g. with parameter redirect=no)
1026 # Don't append the subtitle if this was an old revision
1027 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1028 # Parse just to get categories, displaytitle, etc.
1029 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1030 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1036 # Run the parse, protected by a pool counter
1037 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1039 $key = $parserCache->getKey( $this, $parserOptions );
1040 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1042 if ( !$poolArticleView->execute() ) {
1043 # Connection or timeout error
1044 wfProfileOut( __METHOD__
);
1050 # Should be unreachable, but just in case...
1056 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1057 if ( $this->mParserOutput
) {
1058 $titleText = $this->mParserOutput
->getTitleText();
1060 if ( strval( $titleText ) !== '' ) {
1061 $wgOut->setPageTitle( $titleText );
1065 # For the main page, overwrite the <title> element with the con-
1066 # tents of 'pagetitle-view-mainpage' instead of the default (if
1067 # that's not empty).
1068 # This message always exists because it is in the i18n files
1069 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1070 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1071 if ( !$msg->isDisabled() ) {
1072 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1076 # Now that we've filled $this->mParserOutput, we know whether
1077 # there are any __NOINDEX__ tags on the page
1078 $policy = $this->getRobotPolicy( 'view' );
1079 $wgOut->setIndexPolicy( $policy['index'] );
1080 $wgOut->setFollowPolicy( $policy['follow'] );
1082 $this->showViewFooter();
1083 $this->viewUpdates();
1084 wfProfileOut( __METHOD__
);
1088 * Show a diff page according to current request variables. For use within
1089 * Article::view() only, other callers should use the DifferenceEngine class.
1091 public function showDiffPage() {
1092 global $wgRequest, $wgUser;
1094 $diff = $wgRequest->getVal( 'diff' );
1095 $rcid = $wgRequest->getVal( 'rcid' );
1096 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1097 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1098 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1099 $oldid = $this->getOldID();
1101 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1102 // DifferenceEngine directly fetched the revision:
1103 $this->mRevIdFetched
= $de->mNewid
;
1104 $de->showDiffPage( $diffOnly );
1106 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1107 # Run view updates for current revision only
1108 $this->viewUpdates();
1113 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1114 * Article::view() only.
1116 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1119 protected function showCssOrJsPage() {
1122 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1124 // Give hooks a chance to customise the output
1125 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1126 // Wrap the whole lot in a <pre> and don't parse
1128 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1129 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1130 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1131 $wgOut->addHTML( "\n</pre>\n" );
1136 * Get the robot policy to be used for the current view
1137 * @param $action String the action= GET parameter
1138 * @return Array the policy that should be set
1139 * TODO: actions other than 'view'
1141 public function getRobotPolicy( $action ) {
1142 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1143 global $wgDefaultRobotPolicy, $wgRequest;
1145 $ns = $this->mTitle
->getNamespace();
1147 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1148 # Don't index user and user talk pages for blocked users (bug 11443)
1149 if ( !$this->mTitle
->isSubpage() ) {
1150 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1152 'index' => 'noindex',
1153 'follow' => 'nofollow'
1159 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1160 # Non-articles (special pages etc), and old revisions
1162 'index' => 'noindex',
1163 'follow' => 'nofollow'
1165 } elseif ( $wgOut->isPrintable() ) {
1166 # Discourage indexing of printable versions, but encourage following
1168 'index' => 'noindex',
1169 'follow' => 'follow'
1171 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1172 # For ?curid=x urls, disallow indexing
1174 'index' => 'noindex',
1175 'follow' => 'follow'
1179 # Otherwise, construct the policy based on the various config variables.
1180 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1182 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1183 # Honour customised robot policies for this namespace
1184 $policy = array_merge(
1186 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1189 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1190 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1191 # a final sanity check that we have really got the parser output.
1192 $policy = array_merge(
1194 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1198 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1199 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1200 $policy = array_merge(
1202 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1210 * Converts a String robot policy into an associative array, to allow
1211 * merging of several policies using array_merge().
1212 * @param $policy Mixed, returns empty array on null/false/'', transparent
1213 * to already-converted arrays, converts String.
1214 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1216 public static function formatRobotPolicy( $policy ) {
1217 if ( is_array( $policy ) ) {
1219 } elseif ( !$policy ) {
1223 $policy = explode( ',', $policy );
1224 $policy = array_map( 'trim', $policy );
1227 foreach ( $policy as $var ) {
1228 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1229 $arr['index'] = $var;
1230 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1231 $arr['follow'] = $var;
1239 * If this request is a redirect view, send "redirected from" subtitle to
1240 * $wgOut. Returns true if the header was needed, false if this is not a
1241 * redirect view. Handles both local and remote redirects.
1245 public function showRedirectedFromHeader() {
1246 global $wgOut, $wgRequest, $wgRedirectSources;
1248 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1250 if ( isset( $this->mRedirectedFrom
) ) {
1251 // This is an internally redirected page view.
1252 // We'll need a backlink to the source page for navigation.
1253 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1254 $redir = Linker
::link(
1255 $this->mRedirectedFrom
,
1258 array( 'redirect' => 'no' ),
1259 array( 'known', 'noclasses' )
1262 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1263 $wgOut->setSubtitle( $s );
1265 // Set the fragment if one was specified in the redirect
1266 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1267 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1268 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1271 // Add a <link rel="canonical"> tag
1272 $wgOut->addLink( array( 'rel' => 'canonical',
1273 'href' => $this->mTitle
->getLocalURL() )
1278 } elseif ( $rdfrom ) {
1279 // This is an externally redirected view, from some other wiki.
1280 // If it was reported from a trusted site, supply a backlink.
1281 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1282 $redir = Linker
::makeExternalLink( $rdfrom, $rdfrom );
1283 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1284 $wgOut->setSubtitle( $s );
1294 * Show a header specific to the namespace currently being viewed, like
1295 * [[MediaWiki:Talkpagetext]]. For Article::view().
1297 public function showNamespaceHeader() {
1300 if ( $this->mTitle
->isTalkPage() ) {
1301 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1302 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1308 * Show the footer section of an ordinary page view
1310 public function showViewFooter() {
1311 global $wgOut, $wgUseTrackbacks;
1313 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1314 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1315 $wgOut->addWikiMsg( 'anontalkpagetext' );
1318 # If we have been passed an &rcid= parameter, we want to give the user a
1319 # chance to mark this new article as patrolled.
1320 $this->showPatrolFooter();
1323 if ( $wgUseTrackbacks ) {
1324 $this->addTrackbacks();
1327 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1332 * If patrol is possible, output a patrol UI box. This is called from the
1333 * footer section of ordinary page views. If patrol is not possible or not
1334 * desired, does nothing.
1336 public function showPatrolFooter() {
1337 global $wgOut, $wgRequest, $wgUser;
1339 $rcid = $wgRequest->getVal( 'rcid' );
1341 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1345 $token = $wgUser->editToken( $rcid );
1346 $wgOut->preventClickjacking();
1349 "<div class='patrollink'>" .
1351 'markaspatrolledlink',
1354 wfMsgHtml( 'markaspatrolledtext' ),
1357 'action' => 'markpatrolled',
1361 array( 'known', 'noclasses' )
1369 * Show the error text for a missing article. For articles in the MediaWiki
1370 * namespace, show the default message text. To be called from Article::view().
1372 public function showMissingArticle() {
1373 global $wgOut, $wgRequest, $wgUser;
1375 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1376 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1377 $parts = explode( '/', $this->mTitle
->getText() );
1378 $rootPart = $parts[0];
1379 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1380 $ip = User
::isIP( $rootPart );
1382 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1383 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1384 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1385 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1386 LogEventsList
::showLogExtract(
1389 $user->getUserPage()->getPrefixedText(),
1393 'showIfEmpty' => false,
1395 'blocked-notice-logextract',
1396 $user->getName() # Support GENDER in notice
1403 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1405 # Show delete and move logs
1406 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1408 'conds' => array( "log_action != 'revision'" ),
1409 'showIfEmpty' => false,
1410 'msgKey' => array( 'moveddeleted-notice' ) )
1413 # Show error message
1414 $oldid = $this->getOldID();
1416 $text = wfMsgNoTrans( 'missing-article',
1417 $this->mTitle
->getPrefixedText(),
1418 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1419 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1420 // Use the default message text
1421 $text = $this->mTitle
->getDefaultMessageText();
1423 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1424 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1425 $errors = array_merge( $createErrors, $editErrors );
1427 if ( !count( $errors ) ) {
1428 $text = wfMsgNoTrans( 'noarticletext' );
1430 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1433 $text = "<div class='noarticletext'>\n$text\n</div>";
1435 if ( !$this->hasViewableContent() ) {
1436 // If there's no backing content, send a 404 Not Found
1437 // for better machine handling of broken links.
1438 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1441 $wgOut->addWikiText( $text );
1445 * If the revision requested for view is deleted, check permissions.
1446 * Send either an error message or a warning header to $wgOut.
1448 * @return boolean true if the view is allowed, false if not.
1450 public function showDeletedRevisionHeader() {
1451 global $wgOut, $wgRequest;
1453 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1458 // If the user is not allowed to see it...
1459 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1460 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1461 'rev-deleted-text-permission' );
1464 // If the user needs to confirm that they want to see it...
1465 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1466 # Give explanation and add a link to view the revision...
1467 $oldid = intval( $this->getOldID() );
1468 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1469 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1470 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1471 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1472 array( $msg, $link ) );
1475 // We are allowed to see...
1477 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1478 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1479 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1486 * Should the parser cache be used?
1490 public function useParserCache( $oldid ) {
1491 global $wgUser, $wgEnableParserCache;
1493 return $wgEnableParserCache
1494 && $wgUser->getStubThreshold() == 0
1497 && !$this->mTitle
->isCssOrJsPage()
1498 && !$this->mTitle
->isCssJsSubpage();
1502 * Execute the uncached parse for action=view
1504 public function doViewParse() {
1507 $oldid = $this->getOldID();
1508 $parserOptions = $this->getParserOptions();
1510 # Render printable version, use printable version cache
1511 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1513 # Don't show section-edit links on old revisions... this way lies madness.
1514 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1515 $parserOptions->setEditSection( false );
1518 $useParserCache = $this->useParserCache( $oldid );
1519 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1525 * Try to fetch an expired entry from the parser cache. If it is present,
1526 * output it and return true. If it is not present, output nothing and
1527 * return false. This is used as a callback function for
1528 * PoolCounter::executeProtected().
1532 public function tryDirtyCache() {
1534 $parserCache = ParserCache
::singleton();
1535 $options = $this->getParserOptions();
1537 if ( $wgOut->isPrintable() ) {
1538 $options->setIsPrintable( true );
1539 $options->setEditSection( false );
1542 $output = $parserCache->getDirty( $this, $options );
1545 wfDebug( __METHOD__
. ": sending dirty output\n" );
1546 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1547 $wgOut->setSquidMaxage( 0 );
1548 $this->mParserOutput
= $output;
1549 $wgOut->addParserOutput( $output );
1550 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1554 wfDebugLog( 'dirty', "dirty missing\n" );
1555 wfDebug( __METHOD__
. ": no dirty cache\n" );
1564 * @param $target Title|Array of destination(s) to redirect
1565 * @param $appendSubtitle Boolean [optional]
1566 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1567 * @return string containing HMTL with redirect link
1569 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1570 global $wgOut, $wgContLang, $wgStylePath;
1572 if ( !is_array( $target ) ) {
1573 $target = array( $target );
1576 $imageDir = $wgContLang->getDir();
1578 if ( $appendSubtitle ) {
1579 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1582 // the loop prepends the arrow image before the link, so the first case needs to be outside
1583 $title = array_shift( $target );
1585 if ( $forceKnown ) {
1586 $link = Linker
::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1588 $link = Linker
::link( $title, htmlspecialchars( $title->getFullText() ) );
1591 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1592 $alt = $wgContLang->isRTL() ?
'←' : '→';
1593 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1594 foreach ( $target as $rt ) {
1595 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1596 if ( $forceKnown ) {
1597 $link .= Linker
::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1599 $link .= Linker
::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1603 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1604 return '<div class="redirectMsg">' .
1605 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1606 '<span class="redirectText">' . $link . '</span></div>';
1610 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1612 public function addTrackbacks() {
1615 $dbr = wfGetDB( DB_SLAVE
);
1616 $tbs = $dbr->select( 'trackbacks',
1617 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1618 array( 'tb_page' => $this->getID() )
1621 if ( !$dbr->numRows( $tbs ) ) {
1625 $wgOut->preventClickjacking();
1628 foreach ( $tbs as $o ) {
1631 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1632 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1633 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1634 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1638 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1646 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1650 * Removes trackback record for current article from trackbacks table
1652 public function deletetrackback() {
1653 global $wgRequest, $wgOut;
1655 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1656 $wgOut->addWikiMsg( 'sessionfailure' );
1661 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
1663 if ( count( $permission_errors ) ) {
1664 $wgOut->showPermissionsErrorPage( $permission_errors );
1669 $db = wfGetDB( DB_MASTER
);
1670 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1672 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1673 $this->mTitle
->invalidateCache();
1677 * Handle action=render
1680 public function render() {
1683 $wgOut->setArticleBodyOnly( true );
1688 * Handle action=purge
1690 public function purge() {
1691 return Action
::factory( 'purge', $this )->show();
1695 * Perform the actions of a page purging
1697 public function doPurge() {
1700 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1704 // Invalidate the cache
1705 $this->mTitle
->invalidateCache();
1708 if ( $wgUseSquid ) {
1709 // Commit the transaction before the purge is sent
1710 $dbw = wfGetDB( DB_MASTER
);
1714 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1715 $update->doUpdate();
1718 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1719 if ( $this->getID() == 0 ) {
1722 $text = $this->getRawText();
1725 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1730 * Insert a new empty page record for this article.
1731 * This *must* be followed up by creating a revision
1732 * and running $this->updateRevisionOn( ... );
1733 * or else the record will be left in a funky state.
1734 * Best if all done inside a transaction.
1736 * @param $dbw DatabaseBase
1737 * @return int The newly created page_id key, or false if the title already existed
1740 public function insertOn( $dbw ) {
1741 wfProfileIn( __METHOD__
);
1743 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1744 $dbw->insert( 'page', array(
1745 'page_id' => $page_id,
1746 'page_namespace' => $this->mTitle
->getNamespace(),
1747 'page_title' => $this->mTitle
->getDBkey(),
1748 'page_counter' => 0,
1749 'page_restrictions' => '',
1750 'page_is_redirect' => 0, # Will set this shortly...
1752 'page_random' => wfRandom(),
1753 'page_touched' => $dbw->timestamp(),
1754 'page_latest' => 0, # Fill this in shortly...
1755 'page_len' => 0, # Fill this in shortly...
1756 ), __METHOD__
, 'IGNORE' );
1758 $affected = $dbw->affectedRows();
1761 $newid = $dbw->insertId();
1762 $this->mTitle
->resetArticleID( $newid );
1764 wfProfileOut( __METHOD__
);
1766 return $affected ?
$newid : false;
1770 * Update the page record to point to a newly saved revision.
1772 * @param $dbw DatabaseBase: object
1773 * @param $revision Revision: For ID number, and text used to set
1774 length and redirect status fields
1775 * @param $lastRevision Integer: if given, will not overwrite the page field
1776 * when different from the currently set value.
1777 * Giving 0 indicates the new page flag should be set
1779 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1780 * removing rows in redirect table.
1781 * @return bool true on success, false on failure
1784 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1785 wfProfileIn( __METHOD__
);
1787 $text = $revision->getText();
1788 $rt = Title
::newFromRedirectRecurse( $text );
1790 $conditions = array( 'page_id' => $this->getId() );
1792 if ( !is_null( $lastRevision ) ) {
1793 # An extra check against threads stepping on each other
1794 $conditions['page_latest'] = $lastRevision;
1797 $dbw->update( 'page',
1799 'page_latest' => $revision->getId(),
1800 'page_touched' => $dbw->timestamp(),
1801 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1802 'page_is_redirect' => $rt !== null ?
1 : 0,
1803 'page_len' => strlen( $text ),
1808 $result = $dbw->affectedRows() != 0;
1810 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1813 wfProfileOut( __METHOD__
);
1818 * Add row to the redirect table if this is a redirect, remove otherwise.
1820 * @param $dbw DatabaseBase
1821 * @param $redirectTitle Title object pointing to the redirect target,
1822 * or NULL if this is not a redirect
1823 * @param $lastRevIsRedirect If given, will optimize adding and
1824 * removing rows in redirect table.
1825 * @return bool true on success, false on failure
1828 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1829 // Always update redirects (target link might have changed)
1830 // Update/Insert if we don't know if the last revision was a redirect or not
1831 // Delete if changing from redirect to non-redirect
1832 $isRedirect = !is_null( $redirectTitle );
1834 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1838 wfProfileIn( __METHOD__
);
1839 if ( $isRedirect ) {
1840 $this->insertRedirectEntry( $redirectTitle );
1842 // This is not a redirect, remove row from redirect table
1843 $where = array( 'rd_from' => $this->getId() );
1844 $dbw->delete( 'redirect', $where, __METHOD__
);
1847 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1848 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1850 wfProfileOut( __METHOD__
);
1852 return ( $dbw->affectedRows() != 0 );
1856 * If the given revision is newer than the currently set page_latest,
1857 * update the page record. Otherwise, do nothing.
1859 * @param $dbw Database object
1860 * @param $revision Revision object
1863 public function updateIfNewerOn( &$dbw, $revision ) {
1864 wfProfileIn( __METHOD__
);
1866 $row = $dbw->selectRow(
1867 array( 'revision', 'page' ),
1868 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1870 'page_id' => $this->getId(),
1871 'page_latest=rev_id' ),
1875 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1876 wfProfileOut( __METHOD__
);
1879 $prev = $row->rev_id
;
1880 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1882 # No or missing previous revision; mark the page as new
1884 $lastRevIsRedirect = null;
1887 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1889 wfProfileOut( __METHOD__
);
1894 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1895 * @param $text String: new text of the section
1896 * @param $summary String: new section's subject, only if $section is 'new'
1897 * @param $edittime String: revision timestamp or null to use the current revision
1898 * @return string Complete article text, or null if error
1900 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1901 wfProfileIn( __METHOD__
);
1903 if ( strval( $section ) == '' ) {
1904 // Whole-page edit; let the whole text through
1906 if ( is_null( $edittime ) ) {
1907 $rev = Revision
::newFromTitle( $this->mTitle
);
1909 $dbw = wfGetDB( DB_MASTER
);
1910 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1914 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1915 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1916 wfProfileOut( __METHOD__
);
1920 $oldtext = $rev->getText();
1922 if ( $section == 'new' ) {
1923 # Inserting a new section
1924 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1925 $text = strlen( trim( $oldtext ) ) > 0
1926 ?
"{$oldtext}\n\n{$subject}{$text}"
1927 : "{$subject}{$text}";
1929 # Replacing an existing section; roll out the big guns
1932 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1936 wfProfileOut( __METHOD__
);
1941 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1943 * @return Int updated $flags
1945 function checkFlags( $flags ) {
1946 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1947 if ( $this->mTitle
->getArticleID() ) {
1948 $flags |
= EDIT_UPDATE
;
1960 * Change an existing article or create a new article. Updates RC and all necessary caches,
1961 * optionally via the deferred update array.
1963 * $wgUser must be set before calling this function.
1965 * @param $text String: new text
1966 * @param $summary String: edit summary
1967 * @param $flags Integer bitfield:
1969 * Article is known or assumed to be non-existent, create a new one
1971 * Article is known or assumed to be pre-existing, update it
1973 * Mark this edit minor, if the user is allowed to do so
1975 * Do not log the change in recentchanges
1977 * Mark the edit a "bot" edit regardless of user rights
1978 * EDIT_DEFER_UPDATES
1979 * Defer some of the updates until the end of index.php
1981 * Fill in blank summaries with generated text where possible
1983 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1984 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1985 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1986 * edit-already-exists error will be returned. These two conditions are also possible with
1987 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1989 * @param $baseRevId the revision ID this edit was based off, if any
1990 * @param $user User (optional), $wgUser will be used if not passed
1992 * @return Status object. Possible errors:
1993 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1994 * edit-gone-missing: In update mode, but the article didn't exist
1995 * edit-conflict: In update mode, the article changed unexpectedly
1996 * edit-no-change: Warning that the text was the same as before
1997 * edit-already-exists: In creation mode, but the article already exists
1999 * Extensions may define additional errors.
2001 * $return->value will contain an associative array with members as follows:
2002 * new: Boolean indicating if the function attempted to create a new article
2003 * revision: The revision object for the inserted revision, or null
2005 * Compatibility note: this function previously returned a boolean value indicating success/failure
2007 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2008 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2010 # Low-level sanity check
2011 if ( $this->mTitle
->getText() === '' ) {
2012 throw new MWException( 'Something is trying to edit an article with an empty title' );
2015 wfProfileIn( __METHOD__
);
2017 $user = is_null( $user ) ?
$wgUser : $user;
2018 $status = Status
::newGood( array() );
2020 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2021 $this->loadPageData();
2023 $flags = $this->checkFlags( $flags );
2025 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2026 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2028 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2030 if ( $status->isOK() ) {
2031 $status->fatal( 'edit-hook-aborted' );
2034 wfProfileOut( __METHOD__
);
2038 # Silently ignore EDIT_MINOR if not allowed
2039 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2040 $bot = $flags & EDIT_FORCE_BOT
;
2042 $oldtext = $this->getRawText(); // current revision
2043 $oldsize = strlen( $oldtext );
2045 # Provide autosummaries if one is not provided and autosummaries are enabled.
2046 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2047 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2050 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2051 $text = $editInfo->pst
;
2052 $newsize = strlen( $text );
2054 $dbw = wfGetDB( DB_MASTER
);
2055 $now = wfTimestampNow();
2056 $this->mTimestamp
= $now;
2058 if ( $flags & EDIT_UPDATE
) {
2059 # Update article, but only if changed.
2060 $status->value
['new'] = false;
2062 # Make sure the revision is either completely inserted or not inserted at all
2063 if ( !$wgDBtransactions ) {
2064 $userAbort = ignore_user_abort( true );
2067 $changed = ( strcmp( $text, $oldtext ) != 0 );
2070 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
2071 - (int)$this->isCountable( $oldtext );
2072 $this->mTotalAdjustment
= 0;
2074 if ( !$this->mLatest
) {
2075 # Article gone missing
2076 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2077 $status->fatal( 'edit-gone-missing' );
2079 wfProfileOut( __METHOD__
);
2083 $revision = new Revision( array(
2084 'page' => $this->getId(),
2085 'comment' => $summary,
2086 'minor_edit' => $isminor,
2088 'parent_id' => $this->mLatest
,
2089 'user' => $user->getId(),
2090 'user_text' => $user->getName(),
2095 $revisionId = $revision->insertOn( $dbw );
2099 # Note that we use $this->mLatest instead of fetching a value from the master DB
2100 # during the course of this function. This makes sure that EditPage can detect
2101 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2102 # before this function is called. A previous function used a separate query, this
2103 # creates a window where concurrent edits can cause an ignored edit conflict.
2104 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2107 /* Belated edit conflict! Run away!! */
2108 $status->fatal( 'edit-conflict' );
2110 # Delete the invalid revision if the DB is not transactional
2111 if ( !$wgDBtransactions ) {
2112 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2118 global $wgUseRCPatrol;
2119 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2120 # Update recentchanges
2121 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2122 # Mark as patrolled if the user can do so
2123 $patrolled = $wgUseRCPatrol && !count(
2124 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2125 # Add RC row to the DB
2126 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2127 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2128 $revisionId, $patrolled
2131 # Log auto-patrolled edits
2133 PatrolLog
::record( $rc, true );
2136 $user->incEditCount();
2140 $status->warning( 'edit-no-change' );
2142 // Keep the same revision ID, but do some updates on it
2143 $revisionId = $this->getLatest();
2144 // Update page_touched, this is usually implicit in the page update
2145 // Other cache updates are done in onArticleEdit()
2146 $this->mTitle
->invalidateCache();
2149 if ( !$wgDBtransactions ) {
2150 ignore_user_abort( $userAbort );
2153 // Now that ignore_user_abort is restored, we can respond to fatal errors
2154 if ( !$status->isOK() ) {
2155 wfProfileOut( __METHOD__
);
2159 # Invalidate cache of this article and all pages using this article
2160 # as a template. Partly deferred.
2161 Article
::onArticleEdit( $this->mTitle
);
2162 # Update links tables, site stats, etc.
2163 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2165 # Create new article
2166 $status->value
['new'] = true;
2168 # Set statistics members
2169 # We work out if it's countable after PST to avoid counter drift
2170 # when articles are created with {{subst:}}
2171 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2172 $this->mTotalAdjustment
= 1;
2176 # Add the page record; stake our claim on this title!
2177 # This will return false if the article already exists
2178 $newid = $this->insertOn( $dbw );
2180 if ( $newid === false ) {
2182 $status->fatal( 'edit-already-exists' );
2184 wfProfileOut( __METHOD__
);
2188 # Save the revision text...
2189 $revision = new Revision( array(
2191 'comment' => $summary,
2192 'minor_edit' => $isminor,
2194 'user' => $user->getId(),
2195 'user_text' => $user->getName(),
2198 $revisionId = $revision->insertOn( $dbw );
2200 $this->mTitle
->resetArticleID( $newid );
2201 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached (FIXME?)
2202 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2204 # Update the page record with revision data
2205 $this->updateRevisionOn( $dbw, $revision, 0 );
2207 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2209 # Update recentchanges
2210 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2211 global $wgUseRCPatrol, $wgUseNPPatrol;
2213 # Mark as patrolled if the user can do so
2214 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2215 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2216 # Add RC row to the DB
2217 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2218 '', strlen( $text ), $revisionId, $patrolled );
2220 # Log auto-patrolled edits
2222 PatrolLog
::record( $rc, true );
2225 $user->incEditCount();
2228 # Update links, etc.
2229 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user );
2232 Article
::onArticleCreate( $this->mTitle
);
2234 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2235 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2238 # Do updates right now unless deferral was requested
2239 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2243 // Return the new revision (or null) to the caller
2244 $status->value
['revision'] = $revision;
2246 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2247 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2249 wfProfileOut( __METHOD__
);
2254 * Output a redirect back to the article.
2255 * This is typically used after an edit.
2257 * @param $noRedir Boolean: add redirect=no
2258 * @param $sectionAnchor String: section to redirect to, including "#"
2259 * @param $extraQuery String: extra query params
2261 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2265 $query = 'redirect=no';
2267 $query .= "&$extraQuery";
2269 $query = $extraQuery;
2272 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2276 * Mark this particular edit/page as patrolled
2278 public function markpatrolled() {
2279 global $wgOut, $wgRequest;
2281 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2283 # If we haven't been given an rc_id value, we can't do anything
2284 $rcid = (int) $wgRequest->getVal( 'rcid' );
2286 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2287 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2291 $rc = RecentChange
::newFromId( $rcid );
2293 if ( is_null( $rc ) ) {
2294 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2298 # It would be nice to see where the user had actually come from, but for now just guess
2299 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2300 $return = SpecialPage
::getTitleFor( $returnto );
2302 $errors = $rc->doMarkPatrolled();
2304 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2305 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2310 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2311 // The hook itself has handled any output
2315 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2316 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2317 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2318 $wgOut->returnToMain( null, $return );
2323 if ( !empty( $errors ) ) {
2324 $wgOut->showPermissionsErrorPage( $errors );
2330 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2331 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2332 $wgOut->returnToMain( null, $return );
2336 * User-interface handler for the "watch" action
2337 * @deprecated since 1.18
2339 public function watch() {
2340 Action
::factory( 'watch', $this )->show();
2344 * Add this page to $wgUser's watchlist
2346 * This is safe to be called multiple times
2348 * @return bool true on successful watch operation
2349 * @deprecated since 1.18
2351 public function doWatch() {
2352 return Action
::factory( 'watch', $this )->execute();
2356 * User interface handler for the "unwatch" action.
2357 * @deprecated since 1.18
2359 public function unwatch() {
2360 Action
::factory( 'unwatch', $this )->show();
2364 * Stop watching a page
2365 * @return bool true on successful unwatch
2366 * @deprecated since 1.18
2368 public function doUnwatch() {
2369 return Action
::factory( 'unwatch', $this )->execute();
2373 * action=protect handler
2375 public function protect() {
2376 $form = new ProtectionForm( $this );
2381 * action=unprotect handler (alias)
2383 public function unprotect() {
2388 * Update the article's restriction field, and leave a log entry.
2390 * @param $limit Array: set of restriction keys
2391 * @param $reason String
2392 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2393 * @param $expiry Array: per restriction type expiration
2394 * @return bool true on success
2396 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2397 global $wgUser, $wgContLang;
2399 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2401 $id = $this->mTitle
->getArticleID();
2404 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2408 if ( wfReadOnly() ) {
2409 wfDebug( "updateRestrictions failed: read-only\n" );
2413 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2414 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2422 // Take this opportunity to purge out expired restrictions
2423 Title
::purgeExpiredRestrictions();
2425 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2426 # we expect a single selection, but the schema allows otherwise.
2428 $updated = Article
::flattenRestrictions( $limit );
2431 foreach ( $restrictionTypes as $action ) {
2432 if ( isset( $expiry[$action] ) ) {
2433 # Get current restrictions on $action
2434 $aLimits = $this->mTitle
->getRestrictions( $action );
2435 $current[$action] = implode( '', $aLimits );
2436 # Are any actual restrictions being dealt with here?
2437 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2439 # If something changed, we need to log it. Checking $aRChanged
2440 # assures that "unprotecting" a page that is not protected does
2441 # not log just because the expiry was "changed".
2442 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2448 $current = Article
::flattenRestrictions( $current );
2450 $changed = ( $changed ||
$current != $updated );
2451 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2452 $protect = ( $updated != '' );
2454 # If nothing's changed, do nothing
2456 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2457 $dbw = wfGetDB( DB_MASTER
);
2459 # Prepare a null revision to be added to the history
2460 $modified = $current != '' && $protect;
2463 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2465 $comment_type = 'unprotectedarticle';
2468 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2470 # Only restrictions with the 'protect' right can cascade...
2471 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2472 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2474 # The schema allows multiple restrictions
2475 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2479 $cascade_description = '';
2482 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2486 $comment .= ": $reason";
2489 $editComment = $comment;
2490 $encodedExpiry = array();
2491 $protect_description = '';
2492 foreach ( $limit as $action => $restrictions ) {
2493 if ( !isset( $expiry[$action] ) )
2494 $expiry[$action] = $dbw->getInfinity();
2496 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2497 if ( $restrictions != '' ) {
2498 $protect_description .= "[$action=$restrictions] (";
2499 if ( $encodedExpiry[$action] != 'infinity' ) {
2500 $protect_description .= wfMsgForContent( 'protect-expiring',
2501 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2502 $wgContLang->date( $expiry[$action], false, false ) ,
2503 $wgContLang->time( $expiry[$action], false, false ) );
2505 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2508 $protect_description .= ') ';
2511 $protect_description = trim( $protect_description );
2513 if ( $protect_description && $protect ) {
2514 $editComment .= " ($protect_description)";
2518 $editComment .= "$cascade_description";
2521 # Update restrictions table
2522 foreach ( $limit as $action => $restrictions ) {
2523 if ( $restrictions != '' ) {
2524 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2525 array( 'pr_page' => $id,
2526 'pr_type' => $action,
2527 'pr_level' => $restrictions,
2528 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2529 'pr_expiry' => $encodedExpiry[$action]
2534 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2535 'pr_type' => $action ), __METHOD__
);
2539 # Insert a null revision
2540 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2541 $nullRevId = $nullRevision->insertOn( $dbw );
2543 $latest = $this->getLatest();
2544 # Update page record
2545 $dbw->update( 'page',
2547 'page_touched' => $dbw->timestamp(),
2548 'page_restrictions' => '',
2549 'page_latest' => $nullRevId
2550 ), array( /* WHERE */
2552 ), 'Article::protect'
2555 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2556 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2558 # Update the protection log
2559 $log = new LogPage( 'protect' );
2561 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2562 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2564 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2567 } # End "changed" check
2573 * Take an array of page restrictions and flatten it to a string
2574 * suitable for insertion into the page_restrictions field.
2575 * @param $limit Array
2578 protected static function flattenRestrictions( $limit ) {
2579 if ( !is_array( $limit ) ) {
2580 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2586 foreach ( $limit as $action => $restrictions ) {
2587 if ( $restrictions != '' ) {
2588 $bits[] = "$action=$restrictions";
2592 return implode( ':', $bits );
2596 * Auto-generates a deletion reason
2598 * @param &$hasHistory Boolean: whether the page has a history
2599 * @return mixed String containing deletion reason or empty string, or boolean false
2600 * if no revision occurred
2602 public function generateReason( &$hasHistory ) {
2605 $dbw = wfGetDB( DB_MASTER
);
2606 // Get the last revision
2607 $rev = Revision
::newFromTitle( $this->mTitle
);
2609 if ( is_null( $rev ) ) {
2613 // Get the article's contents
2614 $contents = $rev->getText();
2617 // If the page is blank, use the text from the previous revision,
2618 // which can only be blank if there's a move/import/protect dummy revision involved
2619 if ( $contents == '' ) {
2620 $prev = $rev->getPrevious();
2623 $contents = $prev->getText();
2628 // Find out if there was only one contributor
2629 // Only scan the last 20 revisions
2630 $res = $dbw->select( 'revision', 'rev_user_text',
2631 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2633 array( 'LIMIT' => 20 )
2636 if ( $res === false ) {
2637 // This page has no revisions, which is very weird
2641 $hasHistory = ( $res->numRows() > 1 );
2642 $row = $dbw->fetchObject( $res );
2644 if ( $row ) { // $row is false if the only contributor is hidden
2645 $onlyAuthor = $row->rev_user_text
;
2646 // Try to find a second contributor
2647 foreach ( $res as $row ) {
2648 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2649 $onlyAuthor = false;
2654 $onlyAuthor = false;
2657 // Generate the summary with a '$1' placeholder
2659 // The current revision is blank and the one before is also
2660 // blank. It's just not our lucky day
2661 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2663 if ( $onlyAuthor ) {
2664 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2666 $reason = wfMsgForContent( 'excontent', '$1' );
2670 if ( $reason == '-' ) {
2671 // Allow these UI messages to be blanked out cleanly
2675 // Replace newlines with spaces to prevent uglyness
2676 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2677 // Calculate the maximum amount of chars to get
2678 // Max content length = max comment length - length of the comment (excl. $1)
2679 $maxLength = 255 - ( strlen( $reason ) - 2 );
2680 $contents = $wgContLang->truncate( $contents, $maxLength );
2681 // Remove possible unfinished links
2682 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2683 // Now replace the '$1' placeholder
2684 $reason = str_replace( '$1', $contents, $reason );
2691 * UI entry point for page deletion
2693 public function delete() {
2694 global $wgOut, $wgRequest;
2696 $confirm = $wgRequest->wasPosted() &&
2697 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2699 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2700 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2702 $reason = $this->DeleteReasonList
;
2704 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2705 // Entry from drop down menu + additional comment
2706 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2707 } elseif ( $reason == 'other' ) {
2708 $reason = $this->DeleteReason
;
2711 # Flag to hide all contents of the archived revisions
2712 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2714 # This code desperately needs to be totally rewritten
2716 # Read-only check...
2717 if ( wfReadOnly() ) {
2718 $wgOut->readOnlyPage();
2724 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2726 if ( count( $permission_errors ) > 0 ) {
2727 $wgOut->showPermissionsErrorPage( $permission_errors );
2732 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2734 # Better double-check that it hasn't been deleted yet!
2735 $dbw = wfGetDB( DB_MASTER
);
2736 $conds = $this->mTitle
->pageCond();
2737 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2738 if ( $latest === false ) {
2739 $wgOut->showFatalError(
2742 array( 'class' => 'error mw-error-cannotdelete' ),
2743 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2746 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2747 LogEventsList
::showLogExtract(
2750 $this->mTitle
->getPrefixedText()
2756 # Hack for big sites
2757 $bigHistory = $this->isBigDeletion();
2758 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2759 global $wgLang, $wgDeleteRevisionsLimit;
2761 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2762 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2768 $this->doDelete( $reason, $suppress );
2770 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2772 } elseif ( $this->mTitle
->userIsWatching() ) {
2779 // Generate deletion reason
2780 $hasHistory = false;
2782 $reason = $this->generateReason( $hasHistory );
2785 // If the page has a history, insert a warning
2786 if ( $hasHistory && !$confirm ) {
2789 $revisions = $this->estimateRevisionCount();
2791 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2792 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2793 wfMsgHtml( 'word-separator' ) . Linker
::link( $this->mTitle
,
2794 wfMsgHtml( 'history' ),
2795 array( 'rel' => 'archives' ),
2796 array( 'action' => 'history' ) ) .
2800 if ( $bigHistory ) {
2801 global $wgDeleteRevisionsLimit;
2802 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2803 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2807 return $this->confirmDelete( $reason );
2811 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2813 public function isBigDeletion() {
2814 global $wgDeleteRevisionsLimit;
2816 if ( $wgDeleteRevisionsLimit ) {
2817 $revCount = $this->estimateRevisionCount();
2819 return $revCount > $wgDeleteRevisionsLimit;
2826 * @return int approximate revision count
2828 public function estimateRevisionCount() {
2829 $dbr = wfGetDB( DB_SLAVE
);
2831 // For an exact count...
2832 // return $dbr->selectField( 'revision', 'COUNT(*)',
2833 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2834 return $dbr->estimateRowCount( 'revision', '*',
2835 array( 'rev_page' => $this->getId() ), __METHOD__
);
2839 * Get the last N authors
2840 * @param $num Integer: number of revisions to get
2841 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2842 * @return array Array of authors, duplicates not removed
2844 public function getLastNAuthors( $num, $revLatest = 0 ) {
2845 wfProfileIn( __METHOD__
);
2846 // First try the slave
2847 // If that doesn't have the latest revision, try the master
2849 $db = wfGetDB( DB_SLAVE
);
2852 $res = $db->select( array( 'page', 'revision' ),
2853 array( 'rev_id', 'rev_user_text' ),
2855 'page_namespace' => $this->mTitle
->getNamespace(),
2856 'page_title' => $this->mTitle
->getDBkey(),
2857 'rev_page = page_id'
2860 'ORDER BY' => 'rev_timestamp DESC',
2866 wfProfileOut( __METHOD__
);
2870 $row = $db->fetchObject( $res );
2872 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2873 $db = wfGetDB( DB_MASTER
);
2878 } while ( $continue );
2880 $authors = array( $row->rev_user_text
);
2882 foreach ( $res as $row ) {
2883 $authors[] = $row->rev_user_text
;
2886 wfProfileOut( __METHOD__
);
2891 * Output deletion confirmation dialog
2892 * FIXME: Move to another file?
2893 * @param $reason String: prefilled reason
2895 public function confirmDelete( $reason ) {
2898 wfDebug( "Article::confirmDelete\n" );
2900 $deleteBackLink = Linker
::linkKnown( $this->mTitle
);
2901 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2902 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2903 $wgOut->addWikiMsg( 'confirmdeletetext' );
2905 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2907 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2908 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2910 <td class='mw-input'><strong>" .
2911 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2912 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2918 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2920 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2921 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2922 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2923 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2924 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2925 "<tr id=\"wpDeleteReasonListRow\">
2926 <td class='mw-label'>" .
2927 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2929 <td class='mw-input'>" .
2930 Xml
::listDropDown( 'wpDeleteReasonList',
2931 wfMsgForContent( 'deletereason-dropdown' ),
2932 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2935 <tr id=\"wpDeleteReasonRow\">
2936 <td class='mw-label'>" .
2937 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2939 <td class='mw-input'>" .
2940 Html
::input( 'wpReason', $reason, 'text', array(
2942 'maxlength' => '255',
2950 # Disallow watching if user is not logged in
2951 if ( $wgOut->getUser()->isLoggedIn() ) {
2955 <td class='mw-input'>" .
2956 Xml
::checkLabel( wfMsg( 'watchthis' ),
2957 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2966 <td class='mw-submit'>" .
2967 Xml
::submitButton( wfMsg( 'deletepage' ),
2968 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2971 Xml
::closeElement( 'table' ) .
2972 Xml
::closeElement( 'fieldset' ) .
2973 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2974 Xml
::closeElement( 'form' );
2976 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2977 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2978 $link = Linker
::link(
2980 wfMsgHtml( 'delete-edit-reasonlist' ),
2982 array( 'action' => 'edit' )
2984 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2987 $wgOut->addHTML( $form );
2988 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2989 LogEventsList
::showLogExtract( $wgOut, 'delete',
2990 $this->mTitle
->getPrefixedText()
2995 * Perform a deletion and output success or failure messages
2997 public function doDelete( $reason, $suppress = false ) {
3000 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3003 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
3004 $deleted = $this->mTitle
->getPrefixedText();
3006 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3007 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3009 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3011 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3012 $wgOut->returnToMain( false );
3014 if ( $error == '' ) {
3015 $wgOut->showFatalError(
3018 array( 'class' => 'error mw-error-cannotdelete' ),
3019 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3023 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3025 LogEventsList
::showLogExtract(
3028 $this->mTitle
->getPrefixedText()
3031 $wgOut->showFatalError( $error );
3037 * Back-end article deletion
3038 * Deletes the article with database consistency, writes logs, purges caches
3040 * @param $reason string delete reason for deletion log
3041 * @param suppress bitfield
3042 * Revision::DELETED_TEXT
3043 * Revision::DELETED_COMMENT
3044 * Revision::DELETED_USER
3045 * Revision::DELETED_RESTRICTED
3046 * @param $id int article ID
3047 * @param $commit boolean defaults to true, triggers transaction end
3048 * @return boolean true if successful
3050 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3051 global $wgDeferredUpdateList, $wgUseTrackbacks;
3054 wfDebug( __METHOD__
. "\n" );
3056 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3059 $dbw = wfGetDB( DB_MASTER
);
3060 $t = $this->mTitle
->getDBkey();
3061 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3063 if ( $t === '' ||
$id == 0 ) {
3067 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3068 array_push( $wgDeferredUpdateList, $u );
3070 // Bitfields to further suppress the content
3073 // This should be 15...
3074 $bitfield |
= Revision
::DELETED_TEXT
;
3075 $bitfield |
= Revision
::DELETED_COMMENT
;
3076 $bitfield |
= Revision
::DELETED_USER
;
3077 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3079 $bitfield = 'rev_deleted';
3083 // For now, shunt the revision data into the archive table.
3084 // Text is *not* removed from the text table; bulk storage
3085 // is left intact to avoid breaking block-compression or
3086 // immutable storage schemes.
3088 // For backwards compatibility, note that some older archive
3089 // table entries will have ar_text and ar_flags fields still.
3091 // In the future, we may keep revisions and mark them with
3092 // the rev_deleted field, which is reserved for this purpose.
3093 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3095 'ar_namespace' => 'page_namespace',
3096 'ar_title' => 'page_title',
3097 'ar_comment' => 'rev_comment',
3098 'ar_user' => 'rev_user',
3099 'ar_user_text' => 'rev_user_text',
3100 'ar_timestamp' => 'rev_timestamp',
3101 'ar_minor_edit' => 'rev_minor_edit',
3102 'ar_rev_id' => 'rev_id',
3103 'ar_text_id' => 'rev_text_id',
3104 'ar_text' => '\'\'', // Be explicit to appease
3105 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3106 'ar_len' => 'rev_len',
3107 'ar_page_id' => 'page_id',
3108 'ar_deleted' => $bitfield
3111 'page_id = rev_page'
3115 # Delete restrictions for it
3116 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3118 # Now that it's safely backed up, delete it
3119 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3120 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3127 # Fix category table counts
3129 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3131 foreach ( $res as $row ) {
3132 $cats [] = $row->cl_to
;
3135 $this->updateCategoryCounts( array(), $cats );
3137 # If using cascading deletes, we can skip some explicit deletes
3138 if ( !$dbw->cascadingDeletes() ) {
3139 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3141 if ( $wgUseTrackbacks )
3142 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3144 # Delete outgoing links
3145 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3146 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3147 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3148 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3149 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3150 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3151 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3152 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3155 # If using cleanup triggers, we can skip some manual deletes
3156 if ( !$dbw->cleanupTriggers() ) {
3157 # Clean up recentchanges entries...
3158 $dbw->delete( 'recentchanges',
3159 array( 'rc_type != ' . RC_LOG
,
3160 'rc_namespace' => $this->mTitle
->getNamespace(),
3161 'rc_title' => $this->mTitle
->getDBkey() ),
3163 $dbw->delete( 'recentchanges',
3164 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3169 Article
::onArticleDelete( $this->mTitle
);
3171 # Clear the cached article id so the interface doesn't act like we exist
3172 $this->mTitle
->resetArticleID( 0 );
3174 # Log the deletion, if the page was suppressed, log it at Oversight instead
3175 $logtype = $suppress ?
'suppress' : 'delete';
3176 $log = new LogPage( $logtype );
3178 # Make sure logging got through
3179 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3185 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3190 * Roll back the most recent consecutive set of edits to a page
3191 * from the same user; fails if there are no eligible edits to
3192 * roll back to, e.g. user is the sole contributor. This function
3193 * performs permissions checks on $wgUser, then calls commitRollback()
3194 * to do the dirty work
3196 * @param $fromP String: Name of the user whose edits to rollback.
3197 * @param $summary String: Custom summary. Set to default summary if empty.
3198 * @param $token String: Rollback token.
3199 * @param $bot Boolean: If true, mark all reverted edits as bot.
3201 * @param $resultDetails Array: contains result-specific array of additional values
3202 * 'alreadyrolled' : 'current' (rev)
3203 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3205 * @return array of errors, each error formatted as
3206 * array(messagekey, param1, param2, ...).
3207 * On success, the array is empty. This array can also be passed to
3208 * OutputPage::showPermissionsErrorPage().
3210 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3213 $resultDetails = null;
3216 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3217 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3218 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3220 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3221 $errors[] = array( 'sessionfailure' );
3224 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3225 $errors[] = array( 'actionthrottledtext' );
3228 # If there were errors, bail out now
3229 if ( !empty( $errors ) ) {
3233 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3237 * Backend implementation of doRollback(), please refer there for parameter
3238 * and return value documentation
3240 * NOTE: This function does NOT check ANY permissions, it just commits the
3241 * rollback to the DB Therefore, you should only call this function direct-
3242 * ly if you want to use custom permissions checks. If you don't, use
3243 * doRollback() instead.
3245 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3246 global $wgUseRCPatrol, $wgUser, $wgLang;
3248 $dbw = wfGetDB( DB_MASTER
);
3250 if ( wfReadOnly() ) {
3251 return array( array( 'readonlytext' ) );
3254 # Get the last editor
3255 $current = Revision
::newFromTitle( $this->mTitle
);
3256 if ( is_null( $current ) ) {
3257 # Something wrong... no page?
3258 return array( array( 'notanarticle' ) );
3261 $from = str_replace( '_', ' ', $fromP );
3262 # User name given should match up with the top revision.
3263 # If the user was deleted then $from should be empty.
3264 if ( $from != $current->getUserText() ) {
3265 $resultDetails = array( 'current' => $current );
3266 return array( array( 'alreadyrolled',
3267 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3268 htmlspecialchars( $fromP ),
3269 htmlspecialchars( $current->getUserText() )
3273 # Get the last edit not by this guy...
3274 # Note: these may not be public values
3275 $user = intval( $current->getRawUser() );
3276 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3277 $s = $dbw->selectRow( 'revision',
3278 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3279 array( 'rev_page' => $current->getPage(),
3280 "rev_user != {$user} OR rev_user_text != {$user_text}"
3282 array( 'USE INDEX' => 'page_timestamp',
3283 'ORDER BY' => 'rev_timestamp DESC' )
3285 if ( $s === false ) {
3286 # No one else ever edited this page
3287 return array( array( 'cantrollback' ) );
3288 } else if ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3289 # Only admins can see this text
3290 return array( array( 'notvisiblerev' ) );
3294 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3295 # Mark all reverted edits as bot
3299 if ( $wgUseRCPatrol ) {
3300 # Mark all reverted edits as patrolled
3301 $set['rc_patrolled'] = 1;
3304 if ( count( $set ) ) {
3305 $dbw->update( 'recentchanges', $set,
3307 'rc_cur_id' => $current->getPage(),
3308 'rc_user_text' => $current->getUserText(),
3309 "rc_timestamp > '{$s->rev_timestamp}'",
3314 # Generate the edit summary if necessary
3315 $target = Revision
::newFromId( $s->rev_id
);
3316 if ( empty( $summary ) ) {
3317 if ( $from == '' ) { // no public user name
3318 $summary = wfMsgForContent( 'revertpage-nouser' );
3320 $summary = wfMsgForContent( 'revertpage' );
3324 # Allow the custom summary to use the same args as the default message
3326 $target->getUserText(), $from, $s->rev_id
,
3327 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3328 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3330 $summary = wfMsgReplaceArgs( $summary, $args );
3333 $flags = EDIT_UPDATE
;
3335 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3336 $flags |
= EDIT_MINOR
;
3339 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3340 $flags |
= EDIT_FORCE_BOT
;
3343 # Actually store the edit
3344 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3345 if ( !empty( $status->value
['revision'] ) ) {
3346 $revId = $status->value
['revision']->getId();
3351 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3353 $resultDetails = array(
3354 'summary' => $summary,
3355 'current' => $current,
3356 'target' => $target,
3364 * User interface for rollback operations
3366 public function rollback() {
3367 global $wgUser, $wgOut, $wgRequest;
3371 $result = $this->doRollback(
3372 $wgRequest->getVal( 'from' ),
3373 $wgRequest->getText( 'summary' ),
3374 $wgRequest->getVal( 'token' ),
3375 $wgRequest->getBool( 'bot' ),
3379 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3380 $wgOut->rateLimited();
3384 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3385 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3386 $errArray = $result[0];
3387 $errMsg = array_shift( $errArray );
3388 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3390 if ( isset( $details['current'] ) ) {
3391 $current = $details['current'];
3393 if ( $current->getComment() != '' ) {
3394 $wgOut->addWikiMsgArray( 'editcomment', array(
3395 Linker
::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3402 # Display permissions errors before read-only message -- there's no
3403 # point in misleading the user into thinking the inability to rollback
3404 # is only temporary.
3405 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3406 # array_diff is completely broken for arrays of arrays, sigh.
3407 # Remove any 'readonlytext' error manually.
3409 foreach ( $result as $error ) {
3410 if ( $error != array( 'readonlytext' ) ) {
3414 $wgOut->showPermissionsErrorPage( $out );
3419 if ( $result == array( array( 'readonlytext' ) ) ) {
3420 $wgOut->readOnlyPage();
3425 $current = $details['current'];
3426 $target = $details['target'];
3427 $newId = $details['newid'];
3428 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3429 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3431 if ( $current->getUserText() === '' ) {
3432 $old = wfMsg( 'rev-deleted-user' );
3434 $old = Linker
::userLink( $current->getUser(), $current->getUserText() )
3435 . Linker
::userToolLinks( $current->getUser(), $current->getUserText() );
3438 $new = Linker
::userLink( $target->getUser(), $target->getUserText() )
3439 . Linker
::userToolLinks( $target->getUser(), $target->getUserText() );
3440 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3441 $wgOut->returnToMain( false, $this->mTitle
);
3443 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3444 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3445 $de->showDiff( '', '' );
3450 * Do standard deferred updates after page view
3452 public function viewUpdates() {
3453 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3454 if ( wfReadOnly() ) {
3458 # Don't update page view counters on views from bot users (bug 14044)
3459 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3460 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3461 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3464 # Update newtalk / watchlist notification status
3465 $wgUser->clearNotification( $this->mTitle
);
3469 * Prepare text which is about to be saved.
3470 * Returns a stdclass with source, pst and output members
3472 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3473 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3475 return $this->mPreparedEdit
;
3480 if( $user === null ) {
3484 $popts = ParserOptions
::newFromUser( $user );
3485 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3487 $edit = (object)array();
3488 $edit->revid
= $revid;
3489 $edit->newText
= $text;
3490 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3491 $edit->popts
= $this->getParserOptions();
3492 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3493 $edit->oldText
= $this->getRawText();
3495 $this->mPreparedEdit
= $edit;
3501 * Do standard deferred updates after page edit.
3502 * Update links tables, site stats, search index and message cache.
3503 * Purges pages that include this page if the text was changed here.
3504 * Every 100th edit, prune the recent changes table.
3507 * @param $text String: New text of the article
3508 * @param $summary String: Edit summary
3509 * @param $minoredit Boolean: Minor edit
3510 * @param $timestamp_of_pagechange String timestamp associated with the page change
3511 * @param $newid Integer: rev_id value of the new revision
3512 * @param $changed Boolean: Whether or not the content actually changed
3513 * @param $user User object: User doing the edit
3515 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User
$user = null ) {
3516 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3518 wfProfileIn( __METHOD__
);
3521 # Be careful not to double-PST: $text is usually already PST-ed once
3522 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3523 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3524 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3526 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3527 $editInfo = $this->mPreparedEdit
;
3530 # Save it to the parser cache
3531 if ( $wgEnableParserCache ) {
3532 $parserCache = ParserCache
::singleton();
3533 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3536 # Update the links tables
3537 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3540 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3542 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3543 if ( 0 == mt_rand( 0, 99 ) ) {
3544 // Flush old entries from the `recentchanges` table; we do this on
3545 // random requests so as to avoid an increase in writes for no good reason
3548 $dbw = wfGetDB( DB_MASTER
);
3549 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3552 array( "rc_timestamp < '$cutoff'" ),
3558 $id = $this->getID();
3559 $title = $this->mTitle
->getPrefixedDBkey();
3560 $shortTitle = $this->mTitle
->getDBkey();
3563 wfProfileOut( __METHOD__
);
3567 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3568 array_push( $wgDeferredUpdateList, $u );
3569 $u = new SearchUpdate( $id, $title, $text );
3570 array_push( $wgDeferredUpdateList, $u );
3572 # If this is another user's talk page, update newtalk
3573 # Don't do this if $changed = false otherwise some idiot can null-edit a
3574 # load of user talk pages and piss people off, nor if it's a minor edit
3575 # by a properly-flagged bot.
3576 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3577 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3579 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3580 $other = User
::newFromName( $shortTitle, false );
3582 wfDebug( __METHOD__
. ": invalid username\n" );
3583 } elseif ( User
::isIP( $shortTitle ) ) {
3584 // An anonymous user
3585 $other->setNewtalk( true );
3586 } elseif ( $other->isLoggedIn() ) {
3587 $other->setNewtalk( true );
3589 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3594 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3595 MessageCache
::singleton()->replace( $shortTitle, $text );
3598 wfProfileOut( __METHOD__
);
3602 * Perform article updates on a special page creation.
3604 * @param $rev Revision object
3606 * @todo This is a shitty interface function. Kill it and replace the
3607 * other shitty functions like editUpdates and such so it's not needed
3610 public function createUpdates( $rev ) {
3611 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3612 $this->mTotalAdjustment
= 1;
3613 $this->editUpdates( $rev->getText(), $rev->getComment(),
3614 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3618 * Generate the navigation links when browsing through an article revisions
3619 * It shows the information as:
3620 * Revision as of \<date\>; view current revision
3621 * \<- Previous version | Next Version -\>
3623 * @param $oldid String: revision ID of this article revision
3625 public function setOldSubtitle( $oldid = 0 ) {
3626 global $wgLang, $wgOut, $wgUser, $wgRequest;
3628 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3632 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3634 # Cascade unhide param in links for easy deletion browsing
3635 $extraParams = array();
3636 if ( $wgRequest->getVal( 'unhide' ) ) {
3637 $extraParams['unhide'] = 1;
3640 $revision = Revision
::newFromId( $oldid );
3641 $timestamp = $revision->getTimestamp();
3643 $current = ( $oldid == $this->mLatest
);
3644 $td = $wgLang->timeanddate( $timestamp, true );
3645 $tddate = $wgLang->date( $timestamp, true );
3646 $tdtime = $wgLang->time( $timestamp, true );
3649 ?
wfMsgHtml( 'currentrevisionlink' )
3652 wfMsgHtml( 'currentrevisionlink' ),
3655 array( 'known', 'noclasses' )
3658 ?
wfMsgHtml( 'diff' )
3661 wfMsgHtml( 'diff' ),
3667 array( 'known', 'noclasses' )
3669 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3673 wfMsgHtml( 'previousrevision' ),
3676 'direction' => 'prev',
3679 array( 'known', 'noclasses' )
3681 : wfMsgHtml( 'previousrevision' );
3685 wfMsgHtml( 'diff' ),
3691 array( 'known', 'noclasses' )
3693 : wfMsgHtml( 'diff' );
3694 $nextlink = $current
3695 ?
wfMsgHtml( 'nextrevision' )
3698 wfMsgHtml( 'nextrevision' ),
3701 'direction' => 'next',
3704 array( 'known', 'noclasses' )
3706 $nextdiff = $current
3707 ?
wfMsgHtml( 'diff' )
3710 wfMsgHtml( 'diff' ),
3716 array( 'known', 'noclasses' )
3721 // User can delete revisions or view deleted revisions...
3722 $canHide = $wgUser->isAllowed( 'deleterevision' );
3723 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3724 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3725 $cdel = Linker
::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3728 'type' => 'revision',
3729 'target' => $this->mTitle
->getPrefixedDbkey(),
3732 $cdel = Linker
::revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3737 # Show user links if allowed to see them. If hidden, then show them only if requested...
3738 $userlinks = Linker
::revUserTools( $revision, !$unhide );
3740 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3741 ?
'revision-info-current'
3744 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3747 array( 'parseinline', 'replaceafter' ),
3753 $revision->getUser()
3756 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3757 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3759 $wgOut->addHTML( $r );
3763 * This function is called right before saving the wikitext,
3764 * so we can do things like signatures and links-in-context.
3766 * @param $text String article contents
3767 * @param $user User object: user doing the edit, $wgUser will be used if
3769 * @param $popts ParserOptions object: parser options, default options for
3770 * the user loaded if null given
3771 * @return string article contents with altered wikitext markup (signatures
3772 * converted, {{subst:}}, templates, etc.)
3774 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3777 if ( $user === null ) {
3782 if ( $popts === null ) {
3783 $popts = ParserOptions
::newFromUser( $user );
3786 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3789 /* Caching functions */
3792 * checkLastModified returns true if it has taken care of all
3793 * output to the client that is necessary for this request.
3794 * (that is, it has sent a cached version of the page)
3796 * @return boolean true if cached version send, false otherwise
3798 protected function tryFileCache() {
3799 static $called = false;
3802 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3807 if ( $this->isFileCacheable() ) {
3808 $cache = new HTMLFileCache( $this->mTitle
);
3809 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3810 wfDebug( "Article::tryFileCache(): about to load file\n" );
3811 $cache->loadFromFileCache();
3814 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3815 ob_start( array( &$cache, 'saveToFileCache' ) );
3818 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3825 * Check if the page can be cached
3828 public function isFileCacheable() {
3831 if ( HTMLFileCache
::useFileCache() ) {
3832 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3833 // Extension may have reason to disable file caching on some pages.
3835 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3843 * Loads page_touched and returns a value indicating if it should be used
3844 * @return boolean true if not a redirect
3846 public function checkTouched() {
3847 if ( !$this->mDataLoaded
) {
3848 $this->loadPageData();
3851 return !$this->mIsRedirect
;
3855 * Get the page_touched field
3856 * @return string containing GMT timestamp
3858 public function getTouched() {
3859 if ( !$this->mDataLoaded
) {
3860 $this->loadPageData();
3863 return $this->mTouched
;
3867 * Get the page_latest field
3868 * @return integer rev_id of current revision
3870 public function getLatest() {
3871 if ( !$this->mDataLoaded
) {
3872 $this->loadPageData();
3875 return (int)$this->mLatest
;
3879 * Edit an article without doing all that other stuff
3880 * The article must already exist; link tables etc
3881 * are not updated, caches are not flushed.
3883 * @param $text String: text submitted
3884 * @param $comment String: comment submitted
3885 * @param $minor Boolean: whereas it's a minor modification
3887 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3888 wfProfileIn( __METHOD__
);
3890 $dbw = wfGetDB( DB_MASTER
);
3891 $revision = new Revision( array(
3892 'page' => $this->getId(),
3894 'comment' => $comment,
3895 'minor_edit' => $minor ?
1 : 0,
3897 $revision->insertOn( $dbw );
3898 $this->updateRevisionOn( $dbw, $revision );
3901 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3903 wfProfileOut( __METHOD__
);
3907 * The onArticle*() functions are supposed to be a kind of hooks
3908 * which should be called whenever any of the specified actions
3911 * This is a good place to put code to clear caches, for instance.
3913 * This is called on page move and undelete, as well as edit
3915 * @param $title Title object
3917 public static function onArticleCreate( $title ) {
3918 # Update existence markers on article/talk tabs...
3919 if ( $title->isTalkPage() ) {
3920 $other = $title->getSubjectPage();
3922 $other = $title->getTalkPage();
3925 $other->invalidateCache();
3926 $other->purgeSquid();
3928 $title->touchLinks();
3929 $title->purgeSquid();
3930 $title->deleteTitleProtection();
3934 * Clears caches when article is deleted
3936 * @param $title Title
3938 public static function onArticleDelete( $title ) {
3939 # Update existence markers on article/talk tabs...
3940 if ( $title->isTalkPage() ) {
3941 $other = $title->getSubjectPage();
3943 $other = $title->getTalkPage();
3946 $other->invalidateCache();
3947 $other->purgeSquid();
3949 $title->touchLinks();
3950 $title->purgeSquid();
3953 HTMLFileCache
::clearFileCache( $title );
3956 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3957 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3961 if ( $title->getNamespace() == NS_FILE
) {
3962 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3963 $update->doUpdate();
3967 if ( $title->getNamespace() == NS_USER_TALK
) {
3968 $user = User
::newFromName( $title->getText(), false );
3969 $user->setNewtalk( false );
3973 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3977 * Purge caches on page update etc
3979 * @param $title Title object
3980 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3982 public static function onArticleEdit( $title ) {
3983 global $wgDeferredUpdateList;
3985 // Invalidate caches of articles which include this page
3986 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3988 // Invalidate the caches of all pages which redirect here
3989 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3991 # Purge squid for this page only
3992 $title->purgeSquid();
3994 # Clear file cache for this page only
3995 HTMLFileCache
::clearFileCache( $title );
4001 * Overriden by ImagePage class, only present here to avoid a fatal error
4002 * Called for ?action=revert
4004 public function revert() {
4006 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4010 * Info about this page
4011 * Called for ?action=info when $wgAllowPageInfo is on.
4013 public function info() {
4014 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4016 if ( !$wgAllowPageInfo ) {
4017 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4021 $page = $this->mTitle
->getSubjectPage();
4023 $wgOut->setPagetitle( $page->getPrefixedText() );
4024 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4025 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4027 if ( !$this->mTitle
->exists() ) {
4028 $wgOut->addHTML( '<div class="noarticletext">' );
4029 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
4030 // This doesn't quite make sense; the user is asking for
4031 // information about the _page_, not the message... -- RC
4032 $wgOut->addHTML( htmlspecialchars( $this->mTitle
->getDefaultMessageText() ) );
4034 $msg = $wgUser->isLoggedIn()
4036 : 'noarticletextanon';
4037 $wgOut->addWikiMsg( $msg );
4040 $wgOut->addHTML( '</div>' );
4042 $dbr = wfGetDB( DB_SLAVE
);
4044 'wl_title' => $page->getDBkey(),
4045 'wl_namespace' => $page->getNamespace() );
4046 $numwatchers = $dbr->selectField(
4052 $pageInfo = $this->pageCountInfo( $page );
4053 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4056 //FIXME: unescaped messages
4057 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4058 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4061 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4064 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4067 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4070 $wgOut->addHTML( '</ul>' );
4075 * Return the total number of edits and number of unique editors
4076 * on a given page. If page does not exist, returns false.
4078 * @param $title Title object
4079 * @return mixed array or boolean false
4081 public function pageCountInfo( $title ) {
4082 $id = $title->getArticleId();
4088 $dbr = wfGetDB( DB_SLAVE
);
4089 $rev_clause = array( 'rev_page' => $id );
4090 $edits = $dbr->selectField(
4096 $authors = $dbr->selectField(
4098 'COUNT(DISTINCT rev_user_text)',
4103 return array( 'edits' => $edits, 'authors' => $authors );
4107 * Return a list of templates used by this article.
4108 * Uses the templatelinks table
4110 * @return Array of Title objects
4112 public function getUsedTemplates() {
4114 $id = $this->mTitle
->getArticleID();
4120 $dbr = wfGetDB( DB_SLAVE
);
4121 $res = $dbr->select( array( 'templatelinks' ),
4122 array( 'tl_namespace', 'tl_title' ),
4123 array( 'tl_from' => $id ),
4126 if ( $res !== false ) {
4127 foreach ( $res as $row ) {
4128 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4136 * Returns a list of hidden categories this page is a member of.
4137 * Uses the page_props and categorylinks tables.
4139 * @return Array of Title objects
4141 public function getHiddenCategories() {
4143 $id = $this->mTitle
->getArticleID();
4149 $dbr = wfGetDB( DB_SLAVE
);
4150 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4152 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4153 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4156 if ( $res !== false ) {
4157 foreach ( $res as $row ) {
4158 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4166 * Return an applicable autosummary if one exists for the given edit.
4167 * @param $oldtext String: the previous text of the page.
4168 * @param $newtext String: The submitted text of the page.
4169 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4170 * @return string An appropriate autosummary, or an empty string.
4172 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4175 # Decide what kind of autosummary is needed.
4177 # Redirect autosummaries
4178 $ot = Title
::newFromRedirect( $oldtext );
4179 $rt = Title
::newFromRedirect( $newtext );
4181 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4182 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4185 # New page autosummaries
4186 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4187 # If they're making a new article, give its text, truncated, in the summary.
4189 $truncatedtext = $wgContLang->truncate(
4190 str_replace( "\n", ' ', $newtext ),
4191 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4193 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4196 # Blanking autosummaries
4197 if ( $oldtext != '' && $newtext == '' ) {
4198 return wfMsgForContent( 'autosumm-blank' );
4199 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4200 # Removing more than 90% of the article
4202 $truncatedtext = $wgContLang->truncate(
4204 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4206 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4209 # If we reach this point, there's no applicable autosummary for our case, so our
4210 # autosummary is empty.
4215 * Add the primary page-view wikitext to the output buffer
4216 * Saves the text into the parser cache if possible.
4217 * Updates templatelinks if it is out of date.
4219 * @param $text String
4220 * @param $cache Boolean
4221 * @param $parserOptions mixed ParserOptions object, or boolean false
4223 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4226 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4227 $wgOut->addParserOutput( $this->mParserOutput
);
4231 * This does all the heavy lifting for outputWikitext, except it returns the parser
4232 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4233 * say, embedding thread pages within a discussion system (LiquidThreads)
4235 * @param $text string
4236 * @param $cache boolean
4237 * @param $parserOptions parsing options, defaults to false
4238 * @return string containing parsed output
4240 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4241 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4243 if ( !$parserOptions ) {
4244 $parserOptions = $this->getParserOptions();
4248 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4249 $parserOptions, true, true, $this->getRevIdFetched() );
4254 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4255 $this->mTitle
->getPrefixedDBkey() ) );
4258 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4259 $parserCache = ParserCache
::singleton();
4260 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4263 // Make sure file cache is not used on uncacheable content.
4264 // Output that has magic words in it can still use the parser cache
4265 // (if enabled), though it will generally expire sooner.
4266 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4267 $wgUseFileCache = false;
4270 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4272 return $this->mParserOutput
;
4276 * Get parser options suitable for rendering the primary article wikitext
4277 * @return ParserOptions object
4279 public function getParserOptions() {
4281 if ( !$this->mParserOptions
) {
4282 $this->mParserOptions
= $this->makeParserOptions( $wgUser );
4284 // Clone to allow modifications of the return value without affecting cache
4285 return clone $this->mParserOptions
;
4289 * Get parser options suitable for rendering the primary article wikitext
4291 * @return ParserOptions
4293 public function makeParserOptions( User
$user ) {
4294 $options = ParserOptions
::newFromUser( $user );
4295 $options->enableLimitReport(); // show inclusion/loop reports
4296 $options->setTidy( true ); // fix bad HTML
4301 * Updates cascading protections
4303 * @param $parserOutput ParserOutput object, or boolean false
4305 protected function doCascadeProtectionUpdates( $parserOutput ) {
4306 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4310 // templatelinks table may have become out of sync,
4311 // especially if using variable-based transclusions.
4312 // For paranoia, check if things have changed and if
4313 // so apply updates to the database. This will ensure
4314 // that cascaded protections apply as soon as the changes
4317 # Get templates from templatelinks
4318 $id = $this->mTitle
->getArticleID();
4320 $tlTemplates = array();
4322 $dbr = wfGetDB( DB_SLAVE
);
4323 $res = $dbr->select( array( 'templatelinks' ),
4324 array( 'tl_namespace', 'tl_title' ),
4325 array( 'tl_from' => $id ),
4329 foreach ( $res as $row ) {
4330 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4333 # Get templates from parser output.
4334 $poTemplates = array();
4335 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4336 foreach ( $templates as $dbk => $id ) {
4337 $poTemplates["$ns:$dbk"] = true;
4342 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4344 if ( count( $templates_diff ) > 0 ) {
4345 # Whee, link updates time.
4346 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4352 * Update all the appropriate counts in the category table, given that
4353 * we've added the categories $added and deleted the categories $deleted.
4355 * @param $added array The names of categories that were added
4356 * @param $deleted array The names of categories that were deleted
4358 public function updateCategoryCounts( $added, $deleted ) {
4359 $ns = $this->mTitle
->getNamespace();
4360 $dbw = wfGetDB( DB_MASTER
);
4362 # First make sure the rows exist. If one of the "deleted" ones didn't
4363 # exist, we might legitimately not create it, but it's simpler to just
4364 # create it and then give it a negative value, since the value is bogus
4367 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4368 $insertCats = array_merge( $added, $deleted );
4369 if ( !$insertCats ) {
4370 # Okay, nothing to do
4374 $insertRows = array();
4376 foreach ( $insertCats as $cat ) {
4377 $insertRows[] = array(
4378 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4382 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4384 $addFields = array( 'cat_pages = cat_pages + 1' );
4385 $removeFields = array( 'cat_pages = cat_pages - 1' );
4387 if ( $ns == NS_CATEGORY
) {
4388 $addFields[] = 'cat_subcats = cat_subcats + 1';
4389 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4390 } elseif ( $ns == NS_FILE
) {
4391 $addFields[] = 'cat_files = cat_files + 1';
4392 $removeFields[] = 'cat_files = cat_files - 1';
4399 array( 'cat_title' => $added ),
4408 array( 'cat_title' => $deleted ),
4415 * Lightweight method to get the parser output for a page, checking the parser cache
4416 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4417 * consider, so it's not appropriate to use there.
4419 * @since 1.16 (r52326) for LiquidThreads
4421 * @param $oldid mixed integer Revision ID or null
4422 * @return ParserOutput or false if the given revsion ID is not found
4424 public function getParserOutput( $oldid = null ) {
4425 global $wgEnableParserCache, $wgUser;
4427 // Should the parser cache be used?
4428 $useParserCache = $wgEnableParserCache &&
4429 $wgUser->getStubThreshold() == 0 &&
4433 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4435 if ( $wgUser->getStubThreshold() ) {
4436 wfIncrStats( 'pcache_miss_stub' );
4439 if ( $useParserCache ) {
4440 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4441 if ( $parserOutput !== false ) {
4442 return $parserOutput;
4446 // Cache miss; parse and output it.
4447 if ( $oldid === null ) {
4448 $text = $this->getRawText();
4450 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4451 if ( $rev === null ) {
4454 $text = $rev->getText();
4457 return $this->getOutputFromWikitext( $text, $useParserCache );
4461 * Sets the context this Article is executed in
4463 * @param $context RequestContext
4466 public function setContext( $context ) {
4467 $this->mContext
= $context;
4471 * Gets the context this Article is executed in
4473 * @return RequestContext
4476 public function getContext() {
4477 if ( $this->mContext
instanceof RequestContext
) {
4478 return $this->mContext
;
4480 wfDebug( __METHOD__
. " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4481 return RequestContext
::getMain();
4487 class PoolWorkArticleView
extends PoolCounterWork
{
4494 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4495 parent
::__construct( 'ArticleView', $key );
4496 $this->mArticle
= $article;
4497 $this->cacheable
= $useParserCache;
4498 $this->parserOptions
= $parserOptions;
4502 return $this->mArticle
->doViewParse();
4505 function getCachedWork() {
4508 $parserCache = ParserCache
::singleton();
4509 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4511 if ( $this->mArticle
->mParserOutput
!== false ) {
4512 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4513 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4514 # Ensure that UI elements requiring revision ID have
4515 # the correct version information.
4516 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4522 function fallback() {
4523 return $this->mArticle
->tryDirtyCache();
4527 * @param $status Status
4529 function error( $status ) {
4532 $wgOut->clearHTML(); // for release() errors
4533 $wgOut->enableClientCache( false );
4534 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4536 $errortext = $status->getWikiText( false, 'view-pool-error' );
4537 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );