3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
30 * Class representing a MediaWiki article and history.
32 * Some fields are public only for backwards-compatibility. Use accessors.
33 * In the past, this class was part of Article.php and everything was public.
35 class WikiPage
implements Page
, IDBAccessObject
{
36 // Constants for $mDataLoadedFrom and related
41 public $mTitle = null;
46 public $mDataLoaded = false; // !< Boolean
47 public $mIsRedirect = false; // !< Boolean
48 public $mLatest = false; // !< Integer (false means "not loaded")
51 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
52 public $mPreparedEdit = false;
57 protected $mId = null;
60 * @var int One of the READ_* constants
62 protected $mDataLoadedFrom = self
::READ_NONE
;
67 protected $mRedirectTarget = null;
72 protected $mLastRevision = null;
75 * @var string Timestamp of the current revision or empty string if not loaded
77 protected $mTimestamp = '';
82 protected $mTouched = '19700101000000';
87 protected $mLinksUpdated = '19700101000000';
90 * Constructor and clear the article
91 * @param Title $title Reference to a Title object.
93 public function __construct( Title
$title ) {
94 $this->mTitle
= $title;
98 * Create a WikiPage object of the appropriate class for the given title.
100 * @param Title $title
102 * @throws MWException
103 * @return WikiPage Object of the appropriate type
105 public static function factory( Title
$title ) {
106 $ns = $title->getNamespace();
108 if ( $ns == NS_MEDIA
) {
109 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
110 } elseif ( $ns < 0 ) {
111 throw new MWException( "Invalid or virtual namespace $ns given." );
116 $page = new WikiFilePage( $title );
119 $page = new WikiCategoryPage( $title );
122 $page = new WikiPage( $title );
129 * Constructor from a page id
131 * @param int $id Article ID to load
132 * @param string|int $from One of the following values:
133 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
134 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
136 * @return WikiPage|null
138 public static function newFromID( $id, $from = 'fromdb' ) {
139 // page id's are never 0 or negative, see bug 61166
144 $from = self
::convertSelectType( $from );
145 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
146 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
150 return self
::newFromRow( $row, $from );
154 * Constructor from a database row
157 * @param object $row Database row containing at least fields returned by selectFields().
158 * @param string|int $from Source of $data:
159 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
160 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
161 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
164 public static function newFromRow( $row, $from = 'fromdb' ) {
165 $page = self
::factory( Title
::newFromRow( $row ) );
166 $page->loadFromRow( $row, $from );
171 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
173 * @param object|string|int $type
176 private static function convertSelectType( $type ) {
179 return self
::READ_NORMAL
;
181 return self
::READ_LATEST
;
183 return self
::READ_LOCKING
;
185 // It may already be an integer or whatever else
191 * Returns overrides for action handlers.
192 * Classes listed here will be used instead of the default one when
193 * (and only when) $wgActions[$action] === true. This allows subclasses
194 * to override the default behavior.
196 * @todo Move this UI stuff somewhere else
200 public function getActionOverrides() {
201 $content_handler = $this->getContentHandler();
202 return $content_handler->getActionOverrides();
206 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
208 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
210 * @return ContentHandler
214 public function getContentHandler() {
215 return ContentHandler
::getForModelID( $this->getContentModel() );
219 * Get the title object of the article
220 * @return Title Title object of this page
222 public function getTitle() {
223 return $this->mTitle
;
230 public function clear() {
231 $this->mDataLoaded
= false;
232 $this->mDataLoadedFrom
= self
::READ_NONE
;
234 $this->clearCacheFields();
238 * Clear the object cache fields
241 protected function clearCacheFields() {
243 $this->mRedirectTarget
= null; // Title object if set
244 $this->mLastRevision
= null; // Latest revision
245 $this->mTouched
= '19700101000000';
246 $this->mLinksUpdated
= '19700101000000';
247 $this->mTimestamp
= '';
248 $this->mIsRedirect
= false;
249 $this->mLatest
= false;
250 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
251 // the requested rev ID and content against the cached one for equality. For most
252 // content types, the output should not change during the lifetime of this cache.
253 // Clearing it can cause extra parses on edit for no reason.
257 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
261 public function clearPreparedEdit() {
262 $this->mPreparedEdit
= false;
266 * Return the list of revision fields that should be selected to create
271 public static function selectFields() {
272 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
283 'page_links_updated',
288 if ( $wgContentHandlerUseDB ) {
289 $fields[] = 'page_content_model';
292 if ( $wgPageLanguageUseDB ) {
293 $fields[] = 'page_lang';
300 * Fetch a page record with the given conditions
301 * @param DatabaseBase $dbr
302 * @param array $conditions
303 * @param array $options
304 * @return object|bool Database result resource, or false on failure
306 protected function pageData( $dbr, $conditions, $options = array() ) {
307 $fields = self
::selectFields();
309 Hooks
::run( 'ArticlePageDataBefore', array( &$this, &$fields ) );
311 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
313 Hooks
::run( 'ArticlePageDataAfter', array( &$this, &$row ) );
319 * Fetch a page record matching the Title object's namespace and title
320 * using a sanitized title string
322 * @param DatabaseBase $dbr
323 * @param Title $title
324 * @param array $options
325 * @return object|bool Database result resource, or false on failure
327 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
328 return $this->pageData( $dbr, array(
329 'page_namespace' => $title->getNamespace(),
330 'page_title' => $title->getDBkey() ), $options );
334 * Fetch a page record matching the requested ID
336 * @param DatabaseBase $dbr
338 * @param array $options
339 * @return object|bool Database result resource, or false on failure
341 public function pageDataFromId( $dbr, $id, $options = array() ) {
342 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
346 * Load the object from a given source by title
348 * @param object|string|int $from One of the following:
349 * - A DB query result object.
350 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
351 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
352 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
353 * using SELECT FOR UPDATE.
357 public function loadPageData( $from = 'fromdb' ) {
358 $from = self
::convertSelectType( $from );
359 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
360 // We already have the data from the correct location, no need to load it twice.
364 if ( is_int( $from ) ) {
365 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
366 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
369 && $index == DB_SLAVE
370 && wfGetLB()->getServerCount() > 1
371 && wfGetLB()->hasOrMadeRecentMasterChanges()
373 $from = self
::READ_LATEST
;
374 list( $index, $opts ) = DBAccessObjectUtils
::getDBOptions( $from );
375 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle
, $opts );
378 // No idea from where the caller got this data, assume slave database.
380 $from = self
::READ_NORMAL
;
383 $this->loadFromRow( $data, $from );
387 * Load the object from a database row
390 * @param object $data Database row containing at least fields returned by selectFields()
391 * @param string|int $from One of the following:
392 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
393 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
394 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
395 * the master DB using SELECT FOR UPDATE
397 public function loadFromRow( $data, $from ) {
398 $lc = LinkCache
::singleton();
399 $lc->clearLink( $this->mTitle
);
402 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
404 $this->mTitle
->loadFromRow( $data );
406 // Old-fashioned restrictions
407 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
409 $this->mId
= intval( $data->page_id
);
410 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
411 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
412 $this->mIsRedirect
= intval( $data->page_is_redirect
);
413 $this->mLatest
= intval( $data->page_latest
);
414 // Bug 37225: $latest may no longer match the cached latest Revision object.
415 // Double-check the ID of any cached latest Revision object for consistency.
416 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
417 $this->mLastRevision
= null;
418 $this->mTimestamp
= '';
421 $lc->addBadLinkObj( $this->mTitle
);
423 $this->mTitle
->loadFromRow( false );
425 $this->clearCacheFields();
430 $this->mDataLoaded
= true;
431 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
435 * @return int Page ID
437 public function getId() {
438 if ( !$this->mDataLoaded
) {
439 $this->loadPageData();
445 * @return bool Whether or not the page exists in the database
447 public function exists() {
448 if ( !$this->mDataLoaded
) {
449 $this->loadPageData();
451 return $this->mId
> 0;
455 * Check if this page is something we're going to be showing
456 * some sort of sensible content for. If we return false, page
457 * views (plain action=view) will return an HTTP 404 response,
458 * so spiders and robots can know they're following a bad link.
462 public function hasViewableContent() {
463 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
467 * Tests if the article content represents a redirect
471 public function isRedirect() {
472 $content = $this->getContent();
477 return $content->isRedirect();
481 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
483 * Will use the revisions actual content model if the page exists,
484 * and the page's default if the page doesn't exist yet.
490 public function getContentModel() {
491 if ( $this->exists() ) {
492 // look at the revision's actual content model
493 $rev = $this->getRevision();
495 if ( $rev !== null ) {
496 return $rev->getContentModel();
498 $title = $this->mTitle
->getPrefixedDBkey();
499 wfWarn( "Page $title exists but has no (visible) revisions!" );
503 // use the default model for this page
504 return $this->mTitle
->getContentModel();
508 * Loads page_touched and returns a value indicating if it should be used
509 * @return bool True if not a redirect
511 public function checkTouched() {
512 if ( !$this->mDataLoaded
) {
513 $this->loadPageData();
515 return !$this->mIsRedirect
;
519 * Get the page_touched field
520 * @return string Containing GMT timestamp
522 public function getTouched() {
523 if ( !$this->mDataLoaded
) {
524 $this->loadPageData();
526 return $this->mTouched
;
530 * Get the page_links_updated field
531 * @return string|null Containing GMT timestamp
533 public function getLinksTimestamp() {
534 if ( !$this->mDataLoaded
) {
535 $this->loadPageData();
537 return $this->mLinksUpdated
;
541 * Get the page_latest field
542 * @return int The rev_id of current revision
544 public function getLatest() {
545 if ( !$this->mDataLoaded
) {
546 $this->loadPageData();
548 return (int)$this->mLatest
;
552 * Get the Revision object of the oldest revision
553 * @return Revision|null
555 public function getOldestRevision() {
557 // Try using the slave database first, then try the master
559 $db = wfGetDB( DB_SLAVE
);
560 $revSelectFields = Revision
::selectFields();
563 while ( $continue ) {
564 $row = $db->selectRow(
565 array( 'page', 'revision' ),
568 'page_namespace' => $this->mTitle
->getNamespace(),
569 'page_title' => $this->mTitle
->getDBkey(),
574 'ORDER BY' => 'rev_timestamp ASC'
581 $db = wfGetDB( DB_MASTER
);
586 return $row ? Revision
::newFromRow( $row ) : null;
590 * Loads everything except the text
591 * This isn't necessary for all uses, so it's only done if needed.
593 protected function loadLastEdit() {
594 if ( $this->mLastRevision
!== null ) {
595 return; // already loaded
598 $latest = $this->getLatest();
600 return; // page doesn't exist or is missing page_latest info
603 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
604 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
605 // includes the latest changes committed. This is true even within REPEATABLE-READ
606 // transactions, where S1 normally only sees changes committed before the first S1
607 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
608 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
609 // happened after the first S1 SELECT.
610 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
611 $flags = Revision
::READ_LOCKING
;
612 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
613 // Bug T93976: if page_latest was loaded from the master, fetch the
614 // revision from there as well, as it may not exist yet on a slave DB.
615 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
616 $flags = Revision
::READ_LATEST
;
620 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
621 if ( $revision ) { // sanity
622 $this->setLastEdit( $revision );
627 * Set the latest revision
628 * @param Revision $revision
630 protected function setLastEdit( Revision
$revision ) {
631 $this->mLastRevision
= $revision;
632 $this->mTimestamp
= $revision->getTimestamp();
636 * Get the latest revision
637 * @return Revision|null
639 public function getRevision() {
640 $this->loadLastEdit();
641 if ( $this->mLastRevision
) {
642 return $this->mLastRevision
;
648 * Get the content of the current revision. No side-effects...
650 * @param int $audience One of:
651 * Revision::FOR_PUBLIC to be displayed to all users
652 * Revision::FOR_THIS_USER to be displayed to $wgUser
653 * Revision::RAW get the text regardless of permissions
654 * @param User $user User object to check for, only if FOR_THIS_USER is passed
655 * to the $audience parameter
656 * @return Content|null The content of the current revision
660 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
661 $this->loadLastEdit();
662 if ( $this->mLastRevision
) {
663 return $this->mLastRevision
->getContent( $audience, $user );
669 * Get the text of the current revision. No side-effects...
671 * @param int $audience One of:
672 * Revision::FOR_PUBLIC to be displayed to all users
673 * Revision::FOR_THIS_USER to be displayed to the given user
674 * Revision::RAW get the text regardless of permissions
675 * @param User $user User object to check for, only if FOR_THIS_USER is passed
676 * to the $audience parameter
677 * @return string|bool The text of the current revision
678 * @deprecated since 1.21, getContent() should be used instead.
680 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
681 ContentHandler
::deprecated( __METHOD__
, '1.21' );
683 $this->loadLastEdit();
684 if ( $this->mLastRevision
) {
685 return $this->mLastRevision
->getText( $audience, $user );
691 * Get the text of the current revision. No side-effects...
693 * @return string|bool The text of the current revision. False on failure
694 * @deprecated since 1.21, getContent() should be used instead.
696 public function getRawText() {
697 ContentHandler
::deprecated( __METHOD__
, '1.21' );
699 return $this->getText( Revision
::RAW
);
703 * @return string MW timestamp of last article revision
705 public function getTimestamp() {
706 // Check if the field has been filled by WikiPage::setTimestamp()
707 if ( !$this->mTimestamp
) {
708 $this->loadLastEdit();
711 return wfTimestamp( TS_MW
, $this->mTimestamp
);
715 * Set the page timestamp (use only to avoid DB queries)
716 * @param string $ts MW timestamp of last article revision
719 public function setTimestamp( $ts ) {
720 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
724 * @param int $audience One of:
725 * Revision::FOR_PUBLIC to be displayed to all users
726 * Revision::FOR_THIS_USER to be displayed to the given user
727 * Revision::RAW get the text regardless of permissions
728 * @param User $user User object to check for, only if FOR_THIS_USER is passed
729 * to the $audience parameter
730 * @return int User ID for the user that made the last article revision
732 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
733 $this->loadLastEdit();
734 if ( $this->mLastRevision
) {
735 return $this->mLastRevision
->getUser( $audience, $user );
742 * Get the User object of the user who created the page
743 * @param int $audience One of:
744 * Revision::FOR_PUBLIC to be displayed to all users
745 * Revision::FOR_THIS_USER to be displayed to the given user
746 * Revision::RAW get the text regardless of permissions
747 * @param User $user User object to check for, only if FOR_THIS_USER is passed
748 * to the $audience parameter
751 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
752 $revision = $this->getOldestRevision();
754 $userName = $revision->getUserText( $audience, $user );
755 return User
::newFromName( $userName, false );
762 * @param int $audience One of:
763 * Revision::FOR_PUBLIC to be displayed to all users
764 * Revision::FOR_THIS_USER to be displayed to the given user
765 * Revision::RAW get the text regardless of permissions
766 * @param User $user User object to check for, only if FOR_THIS_USER is passed
767 * to the $audience parameter
768 * @return string Username of the user that made the last article revision
770 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
771 $this->loadLastEdit();
772 if ( $this->mLastRevision
) {
773 return $this->mLastRevision
->getUserText( $audience, $user );
780 * @param int $audience One of:
781 * Revision::FOR_PUBLIC to be displayed to all users
782 * Revision::FOR_THIS_USER to be displayed to the given user
783 * Revision::RAW get the text regardless of permissions
784 * @param User $user User object to check for, only if FOR_THIS_USER is passed
785 * to the $audience parameter
786 * @return string Comment stored for the last article revision
788 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
789 $this->loadLastEdit();
790 if ( $this->mLastRevision
) {
791 return $this->mLastRevision
->getComment( $audience, $user );
798 * Returns true if last revision was marked as "minor edit"
800 * @return bool Minor edit indicator for the last article revision.
802 public function getMinorEdit() {
803 $this->loadLastEdit();
804 if ( $this->mLastRevision
) {
805 return $this->mLastRevision
->isMinor();
812 * Determine whether a page would be suitable for being counted as an
813 * article in the site_stats table based on the title & its content
815 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
816 * if false, the current database state will be used
819 public function isCountable( $editInfo = false ) {
820 global $wgArticleCountMethod;
822 if ( !$this->mTitle
->isContentPage() ) {
827 $content = $editInfo->pstContent
;
829 $content = $this->getContent();
832 if ( !$content ||
$content->isRedirect() ) {
838 if ( $wgArticleCountMethod === 'link' ) {
839 // nasty special case to avoid re-parsing to detect links
842 // ParserOutput::getLinks() is a 2D array of page links, so
843 // to be really correct we would need to recurse in the array
844 // but the main array should only have items in it if there are
846 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
848 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
849 array( 'pl_from' => $this->getId() ), __METHOD__
);
853 return $content->isCountable( $hasLinks );
857 * If this page is a redirect, get its target
859 * The target will be fetched from the redirect table if possible.
860 * If this page doesn't have an entry there, call insertRedirect()
861 * @return Title|null Title object, or null if this page is not a redirect
863 public function getRedirectTarget() {
864 if ( !$this->mTitle
->isRedirect() ) {
868 if ( $this->mRedirectTarget
!== null ) {
869 return $this->mRedirectTarget
;
872 // Query the redirect table
873 $dbr = wfGetDB( DB_SLAVE
);
874 $row = $dbr->selectRow( 'redirect',
875 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
876 array( 'rd_from' => $this->getId() ),
880 // rd_fragment and rd_interwiki were added later, populate them if empty
881 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
882 $this->mRedirectTarget
= Title
::makeTitle(
883 $row->rd_namespace
, $row->rd_title
,
884 $row->rd_fragment
, $row->rd_interwiki
);
885 return $this->mRedirectTarget
;
888 // This page doesn't have an entry in the redirect table
889 $this->mRedirectTarget
= $this->insertRedirect();
890 return $this->mRedirectTarget
;
894 * Insert an entry for this page into the redirect table.
896 * Don't call this function directly unless you know what you're doing.
897 * @return Title|null Title object or null if not a redirect
899 public function insertRedirect() {
900 // recurse through to only get the final target
901 $content = $this->getContent();
902 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
906 $this->insertRedirectEntry( $retval );
911 * Insert or update the redirect table entry for this page to indicate
912 * it redirects to $rt .
913 * @param Title $rt Redirect target
915 public function insertRedirectEntry( $rt ) {
916 $dbw = wfGetDB( DB_MASTER
);
917 $dbw->replace( 'redirect', array( 'rd_from' ),
919 'rd_from' => $this->getId(),
920 'rd_namespace' => $rt->getNamespace(),
921 'rd_title' => $rt->getDBkey(),
922 'rd_fragment' => $rt->getFragment(),
923 'rd_interwiki' => $rt->getInterwiki(),
930 * Get the Title object or URL this page redirects to
932 * @return bool|Title|string False, Title of in-wiki target, or string with URL
934 public function followRedirect() {
935 return $this->getRedirectURL( $this->getRedirectTarget() );
939 * Get the Title object or URL to use for a redirect. We use Title
940 * objects for same-wiki, non-special redirects and URLs for everything
942 * @param Title $rt Redirect target
943 * @return bool|Title|string False, Title object of local target, or string with URL
945 public function getRedirectURL( $rt ) {
950 if ( $rt->isExternal() ) {
951 if ( $rt->isLocal() ) {
952 // Offsite wikis need an HTTP redirect.
954 // This can be hard to reverse and may produce loops,
955 // so they may be disabled in the site configuration.
956 $source = $this->mTitle
->getFullURL( 'redirect=no' );
957 return $rt->getFullURL( array( 'rdfrom' => $source ) );
959 // External pages without "local" bit set are not valid
965 if ( $rt->isSpecialPage() ) {
966 // Gotta handle redirects to special pages differently:
967 // Fill the HTTP response "Location" header and ignore
968 // the rest of the page we're on.
970 // Some pages are not valid targets
971 if ( $rt->isValidRedirectTarget() ) {
972 return $rt->getFullURL();
982 * Get a list of users who have edited this article, not including the user who made
983 * the most recent revision, which you can get from $article->getUser() if you want it
984 * @return UserArrayFromResult
986 public function getContributors() {
987 // @todo FIXME: This is expensive; cache this info somewhere.
989 $dbr = wfGetDB( DB_SLAVE
);
991 if ( $dbr->implicitGroupby() ) {
992 $realNameField = 'user_real_name';
994 $realNameField = 'MIN(user_real_name) AS user_real_name';
997 $tables = array( 'revision', 'user' );
1000 'user_id' => 'rev_user',
1001 'user_name' => 'rev_user_text',
1003 'timestamp' => 'MAX(rev_timestamp)',
1006 $conds = array( 'rev_page' => $this->getId() );
1008 // The user who made the top revision gets credited as "this page was last edited by
1009 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1010 $user = $this->getUser();
1012 $conds[] = "rev_user != $user";
1014 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1017 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1020 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1024 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1025 'ORDER BY' => 'timestamp DESC',
1028 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1029 return new UserArrayFromResult( $res );
1033 * Get the last N authors
1034 * @param int $num Number of revisions to get
1035 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1036 * @return array Array of authors, duplicates not removed
1038 public function getLastNAuthors( $num, $revLatest = 0 ) {
1039 // First try the slave
1040 // If that doesn't have the latest revision, try the master
1042 $db = wfGetDB( DB_SLAVE
);
1045 $res = $db->select( array( 'page', 'revision' ),
1046 array( 'rev_id', 'rev_user_text' ),
1048 'page_namespace' => $this->mTitle
->getNamespace(),
1049 'page_title' => $this->mTitle
->getDBkey(),
1050 'rev_page = page_id'
1053 'ORDER BY' => 'rev_timestamp DESC',
1062 $row = $db->fetchObject( $res );
1064 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1065 $db = wfGetDB( DB_MASTER
);
1070 } while ( $continue );
1072 $authors = array( $row->rev_user_text
);
1074 foreach ( $res as $row ) {
1075 $authors[] = $row->rev_user_text
;
1082 * Should the parser cache be used?
1084 * @param ParserOptions $parserOptions ParserOptions to check
1088 public function shouldCheckParserCache( ParserOptions
$parserOptions, $oldId ) {
1089 return $parserOptions->getStubThreshold() == 0
1091 && ( $oldId === null ||
$oldId === 0 ||
$oldId === $this->getLatest() )
1092 && $this->getContentHandler()->isParserCacheSupported();
1096 * Get a ParserOutput for the given ParserOptions and revision ID.
1097 * The parser cache will be used if possible.
1100 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1101 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1102 * get the current revision (default value)
1104 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1106 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1108 $useParserCache = $this->shouldCheckParserCache( $parserOptions, $oldid );
1109 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1110 if ( $parserOptions->getStubThreshold() ) {
1111 wfIncrStats( 'pcache.miss.stub' );
1114 if ( $useParserCache ) {
1115 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1116 if ( $parserOutput !== false ) {
1117 return $parserOutput;
1121 if ( $oldid === null ||
$oldid === 0 ) {
1122 $oldid = $this->getLatest();
1125 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1128 return $pool->getParserOutput();
1132 * Do standard deferred updates after page view (existing or missing page)
1133 * @param User $user The relevant user
1134 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1136 public function doViewUpdates( User
$user, $oldid = 0 ) {
1137 if ( wfReadOnly() ) {
1141 Hooks
::run( 'PageViewUpdates', array( $this, $user ) );
1142 // Update newtalk / watchlist notification status
1144 $user->clearNotification( $this->mTitle
, $oldid );
1145 } catch ( DBError
$e ) {
1146 // Avoid outage if the master is not reachable
1147 MWExceptionHandler
::logException( $e );
1152 * Perform the actions of a page purging
1155 public function doPurge() {
1156 if ( !Hooks
::run( 'ArticlePurge', array( &$this ) ) ) {
1160 $title = $this->mTitle
;
1161 wfGetDB( DB_MASTER
)->onTransactionIdle( function() use ( $title ) {
1163 // Invalidate the cache in auto-commit mode
1164 $title->invalidateCache();
1165 if ( $wgUseSquid ) {
1166 // Send purge now that page_touched update was committed above
1167 $update = SquidUpdate
::newSimplePurge( $title );
1168 $update->doUpdate();
1172 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1173 // @todo move this logic to MessageCache
1174 if ( $this->exists() ) {
1175 // NOTE: use transclusion text for messages.
1176 // This is consistent with MessageCache::getMsgFromNamespace()
1178 $content = $this->getContent();
1179 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1181 if ( $text === null ) {
1188 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1195 * Insert a new empty page record for this article.
1196 * This *must* be followed up by creating a revision
1197 * and running $this->updateRevisionOn( ... );
1198 * or else the record will be left in a funky state.
1199 * Best if all done inside a transaction.
1201 * @param DatabaseBase $dbw
1202 * @return int The newly created page_id key, or false if the title already existed
1204 public function insertOn( $dbw ) {
1206 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1207 $dbw->insert( 'page', array(
1208 'page_id' => $page_id,
1209 'page_namespace' => $this->mTitle
->getNamespace(),
1210 'page_title' => $this->mTitle
->getDBkey(),
1211 'page_restrictions' => '',
1212 'page_is_redirect' => 0, // Will set this shortly...
1214 'page_random' => wfRandom(),
1215 'page_touched' => $dbw->timestamp(),
1216 'page_latest' => 0, // Fill this in shortly...
1217 'page_len' => 0, // Fill this in shortly...
1218 ), __METHOD__
, 'IGNORE' );
1220 $affected = $dbw->affectedRows();
1223 $newid = $dbw->insertId();
1224 $this->mId
= $newid;
1225 $this->mTitle
->resetArticleID( $newid );
1228 return $affected ?
$newid : false;
1232 * Update the page record to point to a newly saved revision.
1234 * @param DatabaseBase $dbw
1235 * @param Revision $revision For ID number, and text used to set
1236 * length and redirect status fields
1237 * @param int $lastRevision If given, will not overwrite the page field
1238 * when different from the currently set value.
1239 * Giving 0 indicates the new page flag should be set on.
1240 * @param bool $lastRevIsRedirect If given, will optimize adding and
1241 * removing rows in redirect table.
1242 * @return bool True on success, false on failure
1244 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1245 $lastRevIsRedirect = null
1247 global $wgContentHandlerUseDB;
1249 // Assertion to try to catch T92046
1250 if ( (int)$revision->getId() === 0 ) {
1251 throw new InvalidArgumentException(
1252 __METHOD__
. ': Revision has ID ' . var_export( $revision->getId(), 1 )
1256 $content = $revision->getContent();
1257 $len = $content ?
$content->getSize() : 0;
1258 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1260 $conditions = array( 'page_id' => $this->getId() );
1262 if ( !is_null( $lastRevision ) ) {
1263 // An extra check against threads stepping on each other
1264 $conditions['page_latest'] = $lastRevision;
1267 $row = array( /* SET */
1268 'page_latest' => $revision->getId(),
1269 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1270 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1271 'page_is_redirect' => $rt !== null ?
1 : 0,
1275 if ( $wgContentHandlerUseDB ) {
1276 $row['page_content_model'] = $revision->getContentModel();
1279 $dbw->update( 'page',
1284 $result = $dbw->affectedRows() > 0;
1286 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1287 $this->setLastEdit( $revision );
1288 $this->mLatest
= $revision->getId();
1289 $this->mIsRedirect
= (bool)$rt;
1290 // Update the LinkCache.
1291 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1292 $this->mLatest
, $revision->getContentModel() );
1299 * Add row to the redirect table if this is a redirect, remove otherwise.
1301 * @param DatabaseBase $dbw
1302 * @param Title $redirectTitle Title object pointing to the redirect target,
1303 * or NULL if this is not a redirect
1304 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1305 * removing rows in redirect table.
1306 * @return bool True on success, false on failure
1309 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1310 // Always update redirects (target link might have changed)
1311 // Update/Insert if we don't know if the last revision was a redirect or not
1312 // Delete if changing from redirect to non-redirect
1313 $isRedirect = !is_null( $redirectTitle );
1315 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1319 if ( $isRedirect ) {
1320 $this->insertRedirectEntry( $redirectTitle );
1322 // This is not a redirect, remove row from redirect table
1323 $where = array( 'rd_from' => $this->getId() );
1324 $dbw->delete( 'redirect', $where, __METHOD__
);
1327 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1328 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1331 return ( $dbw->affectedRows() != 0 );
1335 * If the given revision is newer than the currently set page_latest,
1336 * update the page record. Otherwise, do nothing.
1338 * @deprecated since 1.24, use updateRevisionOn instead
1340 * @param DatabaseBase $dbw
1341 * @param Revision $revision
1344 public function updateIfNewerOn( $dbw, $revision ) {
1346 $row = $dbw->selectRow(
1347 array( 'revision', 'page' ),
1348 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1350 'page_id' => $this->getId(),
1351 'page_latest=rev_id' ),
1355 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1358 $prev = $row->rev_id
;
1359 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1361 // No or missing previous revision; mark the page as new
1363 $lastRevIsRedirect = null;
1366 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1372 * Get the content that needs to be saved in order to undo all revisions
1373 * between $undo and $undoafter. Revisions must belong to the same page,
1374 * must exist and must not be deleted
1375 * @param Revision $undo
1376 * @param Revision $undoafter Must be an earlier revision than $undo
1377 * @return mixed String on success, false on failure
1379 * Before we had the Content object, this was done in getUndoText
1381 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1382 $handler = $undo->getContentHandler();
1383 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1387 * Get the text that needs to be saved in order to undo all revisions
1388 * between $undo and $undoafter. Revisions must belong to the same page,
1389 * must exist and must not be deleted
1390 * @param Revision $undo
1391 * @param Revision $undoafter Must be an earlier revision than $undo
1392 * @return string|bool String on success, false on failure
1393 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1395 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1396 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1398 $this->loadLastEdit();
1400 if ( $this->mLastRevision
) {
1401 if ( is_null( $undoafter ) ) {
1402 $undoafter = $undo->getPrevious();
1405 $handler = $this->getContentHandler();
1406 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1411 return ContentHandler
::getContentText( $undone );
1419 * @param string|number|null|bool $sectionId Section identifier as a number or string
1420 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1421 * or 'new' for a new section.
1422 * @param string $text New text of the section.
1423 * @param string $sectionTitle New section's subject, only if $section is "new".
1424 * @param string $edittime Revision timestamp or null to use the current revision.
1426 * @throws MWException
1427 * @return string New complete article text, or null if error.
1429 * @deprecated since 1.21, use replaceSectionAtRev() instead
1431 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1434 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1436 //NOTE: keep condition in sync with condition in replaceSectionContent!
1437 if ( strval( $sectionId ) === '' ) {
1438 // Whole-page edit; let the whole text through
1442 if ( !$this->supportsSections() ) {
1443 throw new MWException( "sections not supported for content model " .
1444 $this->getContentHandler()->getModelID() );
1447 // could even make section title, but that's not required.
1448 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1450 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1453 return ContentHandler
::getContentText( $newContent );
1457 * Returns true if this page's content model supports sections.
1461 * @todo The skin should check this and not offer section functionality if
1462 * sections are not supported.
1463 * @todo The EditPage should check this and not offer section functionality
1464 * if sections are not supported.
1466 public function supportsSections() {
1467 return $this->getContentHandler()->supportsSections();
1471 * @param string|number|null|bool $sectionId Section identifier as a number or string
1472 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1473 * or 'new' for a new section.
1474 * @param Content $sectionContent New content of the section.
1475 * @param string $sectionTitle New section's subject, only if $section is "new".
1476 * @param string $edittime Revision timestamp or null to use the current revision.
1478 * @throws MWException
1479 * @return Content New complete article content, or null if error.
1482 * @deprecated since 1.24, use replaceSectionAtRev instead
1484 public function replaceSectionContent( $sectionId, Content
$sectionContent, $sectionTitle = '',
1485 $edittime = null ) {
1488 if ( $edittime && $sectionId !== 'new' ) {
1489 $dbr = wfGetDB( DB_SLAVE
);
1490 $rev = Revision
::loadFromTimestamp( $dbr, $this->mTitle
, $edittime );
1491 // Try the master if this thread may have just added it.
1492 // This could be abstracted into a Revision method, but we don't want
1493 // to encourage loading of revisions by timestamp.
1495 && wfGetLB()->getServerCount() > 1
1496 && wfGetLB()->hasOrMadeRecentMasterChanges()
1498 $dbw = wfGetDB( DB_MASTER
);
1499 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1502 $baseRevId = $rev->getId();
1506 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1510 * @param string|number|null|bool $sectionId Section identifier as a number or string
1511 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1512 * or 'new' for a new section.
1513 * @param Content $sectionContent New content of the section.
1514 * @param string $sectionTitle New section's subject, only if $section is "new".
1515 * @param int|null $baseRevId
1517 * @throws MWException
1518 * @return Content New complete article content, or null if error.
1522 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1523 $sectionTitle = '', $baseRevId = null
1526 if ( strval( $sectionId ) === '' ) {
1527 // Whole-page edit; let the whole text through
1528 $newContent = $sectionContent;
1530 if ( !$this->supportsSections() ) {
1531 throw new MWException( "sections not supported for content model " .
1532 $this->getContentHandler()->getModelID() );
1535 // Bug 30711: always use current version when adding a new section
1536 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1537 $oldContent = $this->getContent();
1539 $rev = Revision
::newFromId( $baseRevId );
1541 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1542 $this->getId() . "; section: $sectionId)\n" );
1546 $oldContent = $rev->getContent();
1549 if ( !$oldContent ) {
1550 wfDebug( __METHOD__
. ": no page text\n" );
1554 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1561 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1563 * @return int Updated $flags
1565 public function checkFlags( $flags ) {
1566 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1567 if ( $this->exists() ) {
1568 $flags |
= EDIT_UPDATE
;
1578 * Change an existing article or create a new article. Updates RC and all necessary caches,
1579 * optionally via the deferred update array.
1581 * @param string $text New text
1582 * @param string $summary Edit summary
1583 * @param int $flags Bitfield:
1585 * Article is known or assumed to be non-existent, create a new one
1587 * Article is known or assumed to be pre-existing, update it
1589 * Mark this edit minor, if the user is allowed to do so
1591 * Do not log the change in recentchanges
1593 * Mark the edit a "bot" edit regardless of user rights
1594 * EDIT_DEFER_UPDATES
1595 * Defer some of the updates until the end of index.php
1597 * Fill in blank summaries with generated text where possible
1599 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1600 * article will be detected. If EDIT_UPDATE is specified and the article
1601 * doesn't exist, the function will return an edit-gone-missing error. If
1602 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1603 * error will be returned. These two conditions are also possible with
1604 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1606 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1607 * This is not the parent revision ID, rather the revision ID for older
1608 * content used as the source for a rollback, for example.
1609 * @param User $user The user doing the edit
1611 * @throws MWException
1612 * @return Status Possible errors:
1613 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1614 * set the fatal flag of $status
1615 * edit-gone-missing: In update mode, but the article didn't exist.
1616 * edit-conflict: In update mode, the article changed unexpectedly.
1617 * edit-no-change: Warning that the text was the same as before.
1618 * edit-already-exists: In creation mode, but the article already exists.
1620 * Extensions may define additional errors.
1622 * $return->value will contain an associative array with members as follows:
1623 * new: Boolean indicating if the function attempted to create a new article.
1624 * revision: The revision object for the inserted revision, or null.
1626 * Compatibility note: this function previously returned a boolean value
1627 * indicating success/failure
1629 * @deprecated since 1.21: use doEditContent() instead.
1631 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1632 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1634 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1636 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1640 * Change an existing article or create a new article. Updates RC and all necessary caches,
1641 * optionally via the deferred update array.
1643 * @param Content $content New content
1644 * @param string $summary Edit summary
1645 * @param int $flags Bitfield:
1647 * Article is known or assumed to be non-existent, create a new one
1649 * Article is known or assumed to be pre-existing, update it
1651 * Mark this edit minor, if the user is allowed to do so
1653 * Do not log the change in recentchanges
1655 * Mark the edit a "bot" edit regardless of user rights
1656 * EDIT_DEFER_UPDATES
1657 * Defer some of the updates until the end of index.php
1659 * Fill in blank summaries with generated text where possible
1661 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1662 * article will be detected. If EDIT_UPDATE is specified and the article
1663 * doesn't exist, the function will return an edit-gone-missing error. If
1664 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1665 * error will be returned. These two conditions are also possible with
1666 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1668 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1669 * This is not the parent revision ID, rather the revision ID for older
1670 * content used as the source for a rollback, for example.
1671 * @param User $user The user doing the edit
1672 * @param string $serialFormat Format for storing the content in the
1675 * @throws MWException
1676 * @return Status Possible errors:
1677 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1678 * set the fatal flag of $status.
1679 * edit-gone-missing: In update mode, but the article didn't exist.
1680 * edit-conflict: In update mode, the article changed unexpectedly.
1681 * edit-no-change: Warning that the text was the same as before.
1682 * edit-already-exists: In creation mode, but the article already exists.
1684 * Extensions may define additional errors.
1686 * $return->value will contain an associative array with members as follows:
1687 * new: Boolean indicating if the function attempted to create a new article.
1688 * revision: The revision object for the inserted revision, or null.
1691 * @throws MWException
1693 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1694 User
$user = null, $serialFormat = null
1696 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1698 // Low-level sanity check
1699 if ( $this->mTitle
->getText() === '' ) {
1700 throw new MWException( 'Something is trying to edit an article with an empty title' );
1703 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1704 return Status
::newFatal( 'content-not-allowed-here',
1705 ContentHandler
::getLocalizedName( $content->getModel() ),
1706 $this->getTitle()->getPrefixedText() );
1709 $user = is_null( $user ) ?
$wgUser : $user;
1710 $status = Status
::newGood( array() );
1712 // Load the data from the master database if needed.
1713 // The caller may already loaded it from the master or even loaded it using
1714 // SELECT FOR UPDATE, so do not override that using clear().
1715 $this->loadPageData( 'fromdbmaster' );
1717 $flags = $this->checkFlags( $flags );
1720 $hook_args = array( &$this, &$user, &$content, &$summary,
1721 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1723 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1724 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1726 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1728 if ( $status->isOK() ) {
1729 $status->fatal( 'edit-hook-aborted' );
1735 // Silently ignore EDIT_MINOR if not allowed
1736 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1737 $bot = $flags & EDIT_FORCE_BOT
;
1739 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1741 $oldsize = $old_content ?
$old_content->getSize() : 0;
1742 $oldid = $this->getLatest();
1743 $oldIsRedirect = $this->isRedirect();
1744 $oldcountable = $this->isCountable();
1746 $handler = $content->getContentHandler();
1748 // Provide autosummaries if one is not provided and autosummaries are enabled.
1749 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1750 if ( !$old_content ) {
1751 $old_content = null;
1753 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1756 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1757 $serialized = $editInfo->pst
;
1760 * @var Content $content
1762 $content = $editInfo->pstContent
;
1763 $newsize = $content->getSize();
1765 $dbw = wfGetDB( DB_MASTER
);
1766 $now = wfTimestampNow();
1767 $this->mTimestamp
= $now;
1769 if ( $flags & EDIT_UPDATE
) {
1770 // Update article, but only if changed.
1771 $status->value
['new'] = false;
1774 // Article gone missing
1775 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1776 $status->fatal( 'edit-gone-missing' );
1779 } elseif ( !$old_content ) {
1780 // Sanity check for bug 37225
1781 throw new MWException( "Could not find text for current revision {$oldid}." );
1784 $revision = new Revision( array(
1785 'page' => $this->getId(),
1786 'title' => $this->getTitle(), // for determining the default content model
1787 'comment' => $summary,
1788 'minor_edit' => $isminor,
1789 'text' => $serialized,
1791 'parent_id' => $oldid,
1792 'user' => $user->getId(),
1793 'user_text' => $user->getName(),
1794 'timestamp' => $now,
1795 'content_model' => $content->getModel(),
1796 'content_format' => $serialFormat,
1797 ) ); // XXX: pass content object?!
1799 $changed = !$content->equals( $old_content );
1802 $dbw->begin( __METHOD__
);
1804 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1805 $status->merge( $prepStatus );
1807 if ( !$status->isOK() ) {
1808 $dbw->rollback( __METHOD__
);
1812 $revisionId = $revision->insertOn( $dbw );
1816 // We check for conflicts by comparing $oldid with the current latest revision ID.
1817 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1820 // Belated edit conflict! Run away!!
1821 $status->fatal( 'edit-conflict' );
1823 $dbw->rollback( __METHOD__
);
1828 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1830 // Update recentchanges
1831 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1832 // Mark as patrolled if the user can do so
1833 $patrolled = $wgUseRCPatrol && !count(
1834 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1835 // Add RC row to the DB
1836 RecentChange
::notifyEdit(
1837 $now, $this->mTitle
, $isminor, $user, $summary,
1838 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1839 $revisionId, $patrolled
1843 $user->incEditCount();
1845 $dbw->commit( __METHOD__
);
1847 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1848 // related variables correctly
1849 $revision->setId( $this->getLatest() );
1852 // Update links tables, site stats, etc.
1853 $this->doEditUpdates(
1857 'changed' => $changed,
1858 'oldcountable' => $oldcountable
1863 $status->warning( 'edit-no-change' );
1865 // Update page_touched, this is usually implicit in the page update
1866 // Other cache updates are done in onArticleEdit()
1867 $this->mTitle
->invalidateCache( $now );
1870 // Create new article
1871 $status->value
['new'] = true;
1873 $dbw->begin( __METHOD__
);
1875 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1876 $status->merge( $prepStatus );
1878 if ( !$status->isOK() ) {
1879 $dbw->rollback( __METHOD__
);
1884 $status->merge( $prepStatus );
1886 // Add the page record; stake our claim on this title!
1887 // This will return false if the article already exists
1888 $newid = $this->insertOn( $dbw );
1890 if ( $newid === false ) {
1891 $dbw->rollback( __METHOD__
);
1892 $status->fatal( 'edit-already-exists' );
1897 // Save the revision text...
1898 $revision = new Revision( array(
1900 'title' => $this->getTitle(), // for determining the default content model
1901 'comment' => $summary,
1902 'minor_edit' => $isminor,
1903 'text' => $serialized,
1905 'user' => $user->getId(),
1906 'user_text' => $user->getName(),
1907 'timestamp' => $now,
1908 'content_model' => $content->getModel(),
1909 'content_format' => $serialFormat,
1911 $revisionId = $revision->insertOn( $dbw );
1913 // Bug 37225: use accessor to get the text as Revision may trim it
1914 $content = $revision->getContent(); // sanity; get normalized version
1917 $newsize = $content->getSize();
1920 // Update the page record with revision data
1921 $this->updateRevisionOn( $dbw, $revision, 0 );
1923 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1925 // Update recentchanges
1926 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1927 // Mark as patrolled if the user can do so
1928 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1929 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1930 // Add RC row to the DB
1931 RecentChange
::notifyNew(
1932 $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1933 '', $newsize, $revisionId, $patrolled
1937 $user->incEditCount();
1939 $dbw->commit( __METHOD__
);
1941 // Update links, etc.
1942 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1944 $hook_args = array( &$this, &$user, $content, $summary,
1945 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1947 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1948 Hooks
::run( 'PageContentInsertComplete', $hook_args );
1951 // Do updates right now unless deferral was requested
1952 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1953 DeferredUpdates
::doUpdates();
1956 // Return the new revision (or null) to the caller
1957 $status->value
['revision'] = $revision;
1959 $hook_args = array( &$this, &$user, $content, $summary,
1960 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1962 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1963 Hooks
::run( 'PageContentSaveComplete', $hook_args );
1965 // Promote user to any groups they meet the criteria for
1966 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1967 $user->addAutopromoteOnceGroups( 'onEdit' );
1968 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1975 * Get parser options suitable for rendering the primary article wikitext
1977 * @see ContentHandler::makeParserOptions
1979 * @param IContextSource|User|string $context One of the following:
1980 * - IContextSource: Use the User and the Language of the provided
1982 * - User: Use the provided User object and $wgLang for the language,
1983 * so use an IContextSource object if possible.
1984 * - 'canonical': Canonical options (anonymous user with default
1985 * preferences and content language).
1986 * @return ParserOptions
1988 public function makeParserOptions( $context ) {
1989 $options = $this->getContentHandler()->makeParserOptions( $context );
1991 if ( $this->getTitle()->isConversionTable() ) {
1992 // @todo ConversionTable should become a separate content model, so
1993 // we don't need special cases like this one.
1994 $options->disableContentConversion();
2001 * Prepare text which is about to be saved.
2002 * Returns a stdClass with source, pst and output members
2004 * @deprecated since 1.21: use prepareContentForEdit instead.
2007 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2008 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2009 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2010 return $this->prepareContentForEdit( $content, $revid, $user );
2014 * Prepare content which is about to be saved.
2015 * Returns a stdClass with source, pst and output members
2017 * @param Content $content
2018 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2019 * revision ID is also accepted, but this is deprecated.
2020 * @param User|null $user
2021 * @param string|null $serialFormat
2022 * @param bool $useCache Check shared prepared edit cache
2028 public function prepareContentForEdit(
2029 Content
$content, $revision = null, User
$user = null, $serialFormat = null, $useCache = true
2031 global $wgContLang, $wgUser, $wgAjaxEditStash;
2033 if ( is_object( $revision ) ) {
2034 $revid = $revision->getId();
2037 // This code path is deprecated, and nothing is known to
2038 // use it, so performance here shouldn't be a worry.
2039 if ( $revid !== null ) {
2040 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2046 $user = is_null( $user ) ?
$wgUser : $user;
2047 //XXX: check $user->getId() here???
2049 // Use a sane default for $serialFormat, see bug 57026
2050 if ( $serialFormat === null ) {
2051 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2054 if ( $this->mPreparedEdit
2055 && $this->mPreparedEdit
->newContent
2056 && $this->mPreparedEdit
->newContent
->equals( $content )
2057 && $this->mPreparedEdit
->revid
== $revid
2058 && $this->mPreparedEdit
->format
== $serialFormat
2059 // XXX: also check $user here?
2062 return $this->mPreparedEdit
;
2065 // The edit may have already been prepared via api.php?action=stashedit
2066 $cachedEdit = $useCache && $wgAjaxEditStash && !$user->isAllowed( 'bot' )
2067 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2070 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2071 Hooks
::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2073 $edit = (object)array();
2074 if ( $cachedEdit ) {
2075 $edit->timestamp
= $cachedEdit->timestamp
;
2077 $edit->timestamp
= wfTimestampNow();
2079 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2080 $edit->revid
= $revid;
2082 if ( $cachedEdit ) {
2083 $edit->pstContent
= $cachedEdit->pstContent
;
2085 $edit->pstContent
= $content
2086 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2090 $edit->format
= $serialFormat;
2091 $edit->popts
= $this->makeParserOptions( 'canonical' );
2092 if ( $cachedEdit ) {
2093 $edit->output
= $cachedEdit->output
;
2096 // We get here if vary-revision is set. This means that this page references
2097 // itself (such as via self-transclusion). In this case, we need to make sure
2098 // that any such self-references refer to the newly-saved revision, and not
2099 // to the previous one, which could otherwise happen due to slave lag.
2100 $oldCallback = $edit->popts
->setCurrentRevisionCallback(
2101 function ( $title, $parser = false ) use ( $revision, &$oldCallback ) {
2102 if ( $title->equals( $revision->getTitle() ) ) {
2105 return call_user_func(
2114 $edit->output
= $edit->pstContent
2115 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2119 $edit->newContent
= $content;
2120 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2122 // NOTE: B/C for hooks! don't use these fields!
2123 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2124 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2125 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2127 $this->mPreparedEdit
= $edit;
2132 * Do standard deferred updates after page edit.
2133 * Update links tables, site stats, search index and message cache.
2134 * Purges pages that include this page if the text was changed here.
2135 * Every 100th edit, prune the recent changes table.
2137 * @param Revision $revision
2138 * @param User $user User object that did the revision
2139 * @param array $options Array of options, following indexes are used:
2140 * - changed: boolean, whether the revision changed the content (default true)
2141 * - created: boolean, whether the revision created the page (default false)
2142 * - moved: boolean, whether the page was moved (default false)
2143 * - oldcountable: boolean, null, or string 'no-change' (default null):
2144 * - boolean: whether the page was counted as an article before that
2145 * revision, only used in changed is true and created is false
2146 * - null: if created is false, don't update the article count; if created
2147 * is true, do update the article count
2148 * - 'no-change': don't update the article count, ever
2150 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2155 'oldcountable' => null
2157 $content = $revision->getContent();
2160 // Be careful not to do pre-save transform twice: $text is usually
2161 // already pre-save transformed once.
2162 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2163 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2164 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2166 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2167 $editInfo = $this->mPreparedEdit
;
2170 // Save it to the parser cache.
2171 // Make sure the cache time matches page_touched to avoid double parsing.
2172 ParserCache
::singleton()->save(
2173 $editInfo->output
, $this, $editInfo->popts
,
2174 $revision->getTimestamp(), $editInfo->revid
2177 // Update the links tables and other secondary data
2179 $recursive = $options['changed']; // bug 50785
2180 $updates = $content->getSecondaryDataUpdates(
2181 $this->getTitle(), null, $recursive, $editInfo->output
);
2182 foreach ( $updates as $update ) {
2183 DeferredUpdates
::addUpdate( $update );
2187 Hooks
::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2189 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2190 // Flush old entries from the `recentchanges` table
2191 if ( mt_rand( 0, 9 ) == 0 ) {
2192 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newPurgeJob() );
2196 if ( !$this->exists() ) {
2200 $id = $this->getId();
2201 $title = $this->mTitle
->getPrefixedDBkey();
2202 $shortTitle = $this->mTitle
->getDBkey();
2204 if ( $options['oldcountable'] === 'no-change' ||
2205 ( !$options['changed'] && !$options['moved'] )
2208 } elseif ( $options['created'] ) {
2209 $good = (int)$this->isCountable( $editInfo );
2210 } elseif ( $options['oldcountable'] !== null ) {
2211 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2215 $edits = $options['changed'] ?
1 : 0;
2216 $total = $options['created'] ?
1 : 0;
2218 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2219 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2221 // If this is another user's talk page, update newtalk.
2222 // Don't do this if $options['changed'] = false (null-edits) nor if
2223 // it's a minor edit and the user doesn't want notifications for those.
2224 if ( $options['changed']
2225 && $this->mTitle
->getNamespace() == NS_USER_TALK
2226 && $shortTitle != $user->getTitleKey()
2227 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2229 $recipient = User
::newFromName( $shortTitle, false );
2230 if ( !$recipient ) {
2231 wfDebug( __METHOD__
. ": invalid username\n" );
2233 // Allow extensions to prevent user notification when a new message is added to their talk page
2234 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2235 if ( User
::isIP( $shortTitle ) ) {
2236 // An anonymous user
2237 $recipient->setNewtalk( true, $revision );
2238 } elseif ( $recipient->isLoggedIn() ) {
2239 $recipient->setNewtalk( true, $revision );
2241 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2247 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2248 // XXX: could skip pseudo-messages like js/css here, based on content model.
2249 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2250 if ( $msgtext === false ||
$msgtext === null ) {
2254 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2257 if ( $options['created'] ) {
2258 self
::onArticleCreate( $this->mTitle
);
2259 } elseif ( $options['changed'] ) { // bug 50785
2260 self
::onArticleEdit( $this->mTitle
, $revision );
2265 * Edit an article without doing all that other stuff
2266 * The article must already exist; link tables etc
2267 * are not updated, caches are not flushed.
2269 * @param string $text Text submitted
2270 * @param User $user The relevant user
2271 * @param string $comment Comment submitted
2272 * @param bool $minor Whereas it's a minor modification
2274 * @deprecated since 1.21, use doEditContent() instead.
2276 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2277 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2279 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2280 $this->doQuickEditContent( $content, $user, $comment, $minor );
2284 * Edit an article without doing all that other stuff
2285 * The article must already exist; link tables etc
2286 * are not updated, caches are not flushed.
2288 * @param Content $content Content submitted
2289 * @param User $user The relevant user
2290 * @param string $comment Comment submitted
2291 * @param bool $minor Whereas it's a minor modification
2292 * @param string $serialFormat Format for storing the content in the database
2294 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2295 $serialFormat = null
2298 $serialized = $content->serialize( $serialFormat );
2300 $dbw = wfGetDB( DB_MASTER
);
2301 $revision = new Revision( array(
2302 'title' => $this->getTitle(), // for determining the default content model
2303 'page' => $this->getId(),
2304 'user_text' => $user->getName(),
2305 'user' => $user->getId(),
2306 'text' => $serialized,
2307 'length' => $content->getSize(),
2308 'comment' => $comment,
2309 'minor_edit' => $minor ?
1 : 0,
2310 ) ); // XXX: set the content object?
2311 $revision->insertOn( $dbw );
2312 $this->updateRevisionOn( $dbw, $revision );
2314 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2319 * Update the article's restriction field, and leave a log entry.
2320 * This works for protection both existing and non-existing pages.
2322 * @param array $limit Set of restriction keys
2323 * @param array $expiry Per restriction type expiration
2324 * @param int &$cascade Set to false if cascading protection isn't allowed.
2325 * @param string $reason
2326 * @param User $user The user updating the restrictions
2329 public function doUpdateRestrictions( array $limit, array $expiry,
2330 &$cascade, $reason, User
$user
2332 global $wgCascadingRestrictionLevels, $wgContLang;
2334 if ( wfReadOnly() ) {
2335 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2338 $this->loadPageData( 'fromdbmaster' );
2339 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2340 $id = $this->getId();
2346 // Take this opportunity to purge out expired restrictions
2347 Title
::purgeExpiredRestrictions();
2349 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2350 // we expect a single selection, but the schema allows otherwise.
2351 $isProtected = false;
2355 $dbw = wfGetDB( DB_MASTER
);
2357 foreach ( $restrictionTypes as $action ) {
2358 if ( !isset( $expiry[$action] ) ||
$expiry[$action] === $dbw->getInfinity() ) {
2359 $expiry[$action] = 'infinity';
2361 if ( !isset( $limit[$action] ) ) {
2362 $limit[$action] = '';
2363 } elseif ( $limit[$action] != '' ) {
2367 // Get current restrictions on $action
2368 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2369 if ( $current != '' ) {
2370 $isProtected = true;
2373 if ( $limit[$action] != $current ) {
2375 } elseif ( $limit[$action] != '' ) {
2376 // Only check expiry change if the action is actually being
2377 // protected, since expiry does nothing on an not-protected
2379 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2385 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2389 // If nothing has changed, do nothing
2391 return Status
::newGood();
2394 if ( !$protect ) { // No protection at all means unprotection
2395 $revCommentMsg = 'unprotectedarticle';
2396 $logAction = 'unprotect';
2397 } elseif ( $isProtected ) {
2398 $revCommentMsg = 'modifiedarticleprotection';
2399 $logAction = 'modify';
2401 $revCommentMsg = 'protectedarticle';
2402 $logAction = 'protect';
2405 // Truncate for whole multibyte characters
2406 $reason = $wgContLang->truncate( $reason, 255 );
2408 $logRelationsValues = array();
2409 $logRelationsField = null;
2411 if ( $id ) { // Protection of existing page
2412 if ( !Hooks
::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2413 return Status
::newGood();
2416 // Only certain restrictions can cascade...
2417 $editrestriction = isset( $limit['edit'] )
2418 ?
array( $limit['edit'] )
2419 : $this->mTitle
->getRestrictions( 'edit' );
2420 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2421 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2423 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2424 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2427 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2428 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2429 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2431 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2432 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2435 // The schema allows multiple restrictions
2436 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2440 // insert null revision to identify the page protection change as edit summary
2441 $latest = $this->getLatest();
2442 $nullRevision = $this->insertProtectNullRevision(
2451 if ( $nullRevision === null ) {
2452 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2455 $logRelationsField = 'pr_id';
2457 // Update restrictions table
2458 foreach ( $limit as $action => $restrictions ) {
2460 'page_restrictions',
2463 'pr_type' => $action
2467 if ( $restrictions != '' ) {
2469 'page_restrictions',
2471 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2473 'pr_type' => $action,
2474 'pr_level' => $restrictions,
2475 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2476 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2480 $logRelationsValues[] = $dbw->insertId();
2484 // Clear out legacy restriction fields
2487 array( 'page_restrictions' => '' ),
2488 array( 'page_id' => $id ),
2492 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2493 Hooks
::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2494 } else { // Protection of non-existing page (also known as "title protection")
2495 // Cascade protection is meaningless in this case
2498 if ( $limit['create'] != '' ) {
2499 $dbw->replace( 'protected_titles',
2500 array( array( 'pt_namespace', 'pt_title' ) ),
2502 'pt_namespace' => $this->mTitle
->getNamespace(),
2503 'pt_title' => $this->mTitle
->getDBkey(),
2504 'pt_create_perm' => $limit['create'],
2505 'pt_timestamp' => $dbw->timestamp(),
2506 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2507 'pt_user' => $user->getId(),
2508 'pt_reason' => $reason,
2512 $dbw->delete( 'protected_titles',
2514 'pt_namespace' => $this->mTitle
->getNamespace(),
2515 'pt_title' => $this->mTitle
->getDBkey()
2521 $this->mTitle
->flushRestrictions();
2522 InfoAction
::invalidateCache( $this->mTitle
);
2524 if ( $logAction == 'unprotect' ) {
2527 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2528 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2531 // Update the protection log
2532 $log = new LogPage( 'protect' );
2533 $logId = $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2534 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2535 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2538 return Status
::newGood();
2542 * Insert a new null revision for this page.
2544 * @param string $revCommentMsg Comment message key for the revision
2545 * @param array $limit Set of restriction keys
2546 * @param array $expiry Per restriction type expiration
2547 * @param int $cascade Set to false if cascading protection isn't allowed.
2548 * @param string $reason
2549 * @param User|null $user
2550 * @return Revision|null Null on error
2552 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2553 array $expiry, $cascade, $reason, $user = null
2556 $dbw = wfGetDB( DB_MASTER
);
2558 // Prepare a null revision to be added to the history
2559 $editComment = $wgContLang->ucfirst(
2562 $this->mTitle
->getPrefixedText()
2563 )->inContentLanguage()->text()
2566 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2568 $protectDescription = $this->protectDescription( $limit, $expiry );
2569 if ( $protectDescription ) {
2570 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2571 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2572 ->inContentLanguage()->text();
2575 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2576 $editComment .= wfMessage( 'brackets' )->params(
2577 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2578 )->inContentLanguage()->text();
2581 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2583 $nullRev->insertOn( $dbw );
2585 // Update page record and touch page
2586 $oldLatest = $nullRev->getParentId();
2587 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2594 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2597 protected function formatExpiry( $expiry ) {
2600 if ( $expiry != 'infinity' ) {
2603 $wgContLang->timeanddate( $expiry, false, false ),
2604 $wgContLang->date( $expiry, false, false ),
2605 $wgContLang->time( $expiry, false, false )
2606 )->inContentLanguage()->text();
2608 return wfMessage( 'protect-expiry-indefinite' )
2609 ->inContentLanguage()->text();
2614 * Builds the description to serve as comment for the edit.
2616 * @param array $limit Set of restriction keys
2617 * @param array $expiry Per restriction type expiration
2620 public function protectDescription( array $limit, array $expiry ) {
2621 $protectDescription = '';
2623 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2624 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2625 # All possible message keys are listed here for easier grepping:
2626 # * restriction-create
2627 # * restriction-edit
2628 # * restriction-move
2629 # * restriction-upload
2630 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2631 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2632 # with '' filtered out. All possible message keys are listed below:
2633 # * protect-level-autoconfirmed
2634 # * protect-level-sysop
2635 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2637 $expiryText = $this->formatExpiry( $expiry[$action] );
2639 if ( $protectDescription !== '' ) {
2640 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2642 $protectDescription .= wfMessage( 'protect-summary-desc' )
2643 ->params( $actionText, $restrictionsText, $expiryText )
2644 ->inContentLanguage()->text();
2647 return $protectDescription;
2651 * Builds the description to serve as comment for the log entry.
2653 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2654 * protect description text. Keep them in old format to avoid breaking compatibility.
2655 * TODO: Fix protection log to store structured description and format it on-the-fly.
2657 * @param array $limit Set of restriction keys
2658 * @param array $expiry Per restriction type expiration
2661 public function protectDescriptionLog( array $limit, array $expiry ) {
2664 $protectDescriptionLog = '';
2666 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2667 $expiryText = $this->formatExpiry( $expiry[$action] );
2668 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2671 return trim( $protectDescriptionLog );
2675 * Take an array of page restrictions and flatten it to a string
2676 * suitable for insertion into the page_restrictions field.
2678 * @param string[] $limit
2680 * @throws MWException
2683 protected static function flattenRestrictions( $limit ) {
2684 if ( !is_array( $limit ) ) {
2685 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2691 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2692 $bits[] = "$action=$restrictions";
2695 return implode( ':', $bits );
2699 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2700 * backwards compatibility, if you care about error reporting you should use
2701 * doDeleteArticleReal() instead.
2703 * Deletes the article with database consistency, writes logs, purges caches
2705 * @param string $reason Delete reason for deletion log
2706 * @param bool $suppress Suppress all revisions and log the deletion in
2707 * the suppression log instead of the deletion log
2708 * @param int $id Article ID
2709 * @param bool $commit Defaults to true, triggers transaction end
2710 * @param array &$error Array of errors to append to
2711 * @param User $user The deleting user
2712 * @return bool True if successful
2714 public function doDeleteArticle(
2715 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2717 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2718 return $status->isGood();
2722 * Back-end article deletion
2723 * Deletes the article with database consistency, writes logs, purges caches
2727 * @param string $reason Delete reason for deletion log
2728 * @param bool $suppress Suppress all revisions and log the deletion in
2729 * the suppression log instead of the deletion log
2730 * @param int $id Article ID
2731 * @param bool $commit Defaults to true, triggers transaction end
2732 * @param array &$error Array of errors to append to
2733 * @param User $user The deleting user
2734 * @return Status Status object; if successful, $status->value is the log_id of the
2735 * deletion log entry. If the page couldn't be deleted because it wasn't
2736 * found, $status is a non-fatal 'cannotdelete' error
2738 public function doDeleteArticleReal(
2739 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2741 global $wgUser, $wgContentHandlerUseDB;
2743 wfDebug( __METHOD__
. "\n" );
2745 $status = Status
::newGood();
2747 if ( $this->mTitle
->getDBkey() === '' ) {
2748 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2752 $user = is_null( $user ) ?
$wgUser : $user;
2753 if ( !Hooks
::run( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2754 if ( $status->isOK() ) {
2755 // Hook aborted but didn't set a fatal status
2756 $status->fatal( 'delete-hook-aborted' );
2761 $dbw = wfGetDB( DB_MASTER
);
2762 $dbw->begin( __METHOD__
);
2765 // T98706: lock the page from various other updates but avoid using
2766 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2767 // the revisions queries (which also JOIN on user). Only lock the page
2768 // row and CAS check on page_latest to see if the trx snapshot matches.
2769 $latest = $this->lock();
2771 $this->loadPageData( WikiPage
::READ_LATEST
);
2772 $id = $this->getID();
2773 if ( $id == 0 ||
$this->getLatest() != $latest ) {
2774 // Page not there or trx snapshot is stale
2775 $dbw->rollback( __METHOD__
);
2776 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2781 // we need to remember the old content so we can use it to generate all deletion updates.
2782 $content = $this->getContent( Revision
::RAW
);
2784 // Bitfields to further suppress the content
2787 // This should be 15...
2788 $bitfield |
= Revision
::DELETED_TEXT
;
2789 $bitfield |
= Revision
::DELETED_COMMENT
;
2790 $bitfield |
= Revision
::DELETED_USER
;
2791 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2793 $bitfield = 'rev_deleted';
2796 // For now, shunt the revision data into the archive table.
2797 // Text is *not* removed from the text table; bulk storage
2798 // is left intact to avoid breaking block-compression or
2799 // immutable storage schemes.
2801 // For backwards compatibility, note that some older archive
2802 // table entries will have ar_text and ar_flags fields still.
2804 // In the future, we may keep revisions and mark them with
2805 // the rev_deleted field, which is reserved for this purpose.
2808 'ar_namespace' => 'page_namespace',
2809 'ar_title' => 'page_title',
2810 'ar_comment' => 'rev_comment',
2811 'ar_user' => 'rev_user',
2812 'ar_user_text' => 'rev_user_text',
2813 'ar_timestamp' => 'rev_timestamp',
2814 'ar_minor_edit' => 'rev_minor_edit',
2815 'ar_rev_id' => 'rev_id',
2816 'ar_parent_id' => 'rev_parent_id',
2817 'ar_text_id' => 'rev_text_id',
2818 'ar_text' => '\'\'', // Be explicit to appease
2819 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2820 'ar_len' => 'rev_len',
2821 'ar_page_id' => 'page_id',
2822 'ar_deleted' => $bitfield,
2823 'ar_sha1' => 'rev_sha1',
2826 if ( $wgContentHandlerUseDB ) {
2827 $row['ar_content_model'] = 'rev_content_model';
2828 $row['ar_content_format'] = 'rev_content_format';
2831 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2835 'page_id = rev_page'
2839 // Now that it's safely backed up, delete it
2840 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2841 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2844 $dbw->rollback( __METHOD__
);
2845 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2849 if ( !$dbw->cascadingDeletes() ) {
2850 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2853 // Clone the title, so we have the information we need when we log
2854 $logTitle = clone $this->mTitle
;
2856 // Log the deletion, if the page was suppressed, log it at Oversight instead
2857 $logtype = $suppress ?
'suppress' : 'delete';
2859 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2860 $logEntry->setPerformer( $user );
2861 $logEntry->setTarget( $logTitle );
2862 $logEntry->setComment( $reason );
2863 $logid = $logEntry->insert();
2865 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2866 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2867 $logEntry->publish( $logid );
2871 $dbw->commit( __METHOD__
);
2874 $this->doDeleteUpdates( $id, $content );
2876 Hooks
::run( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2877 $status->value
= $logid;
2882 * Lock the page row for this title and return page_latest (or 0)
2886 protected function lock() {
2887 return (int)wfGetDB( DB_MASTER
)->selectField(
2891 'page_namespace' => $this->getTitle()->getNamespace(),
2892 'page_title' => $this->getTitle()->getDBkey()
2895 array( 'FOR UPDATE' )
2900 * Do some database updates after deletion
2902 * @param int $id The page_id value of the page being deleted
2903 * @param Content $content Optional page content to be used when determining
2904 * the required updates. This may be needed because $this->getContent()
2905 * may already return null when the page proper was deleted.
2907 public function doDeleteUpdates( $id, Content
$content = null ) {
2908 // update site status
2909 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2911 // remove secondary indexes, etc
2912 $updates = $this->getDeletionUpdates( $content );
2913 DataUpdate
::runUpdates( $updates );
2915 // Reparse any pages transcluding this page
2916 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2918 // Reparse any pages including this image
2919 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2920 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2924 WikiPage
::onArticleDelete( $this->mTitle
);
2926 // Reset this object and the Title object
2927 $this->loadFromRow( false, self
::READ_LATEST
);
2930 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2934 * Roll back the most recent consecutive set of edits to a page
2935 * from the same user; fails if there are no eligible edits to
2936 * roll back to, e.g. user is the sole contributor. This function
2937 * performs permissions checks on $user, then calls commitRollback()
2938 * to do the dirty work
2940 * @todo Separate the business/permission stuff out from backend code
2942 * @param string $fromP Name of the user whose edits to rollback.
2943 * @param string $summary Custom summary. Set to default summary if empty.
2944 * @param string $token Rollback token.
2945 * @param bool $bot If true, mark all reverted edits as bot.
2947 * @param array $resultDetails Array contains result-specific array of additional values
2948 * 'alreadyrolled' : 'current' (rev)
2949 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2951 * @param User $user The user performing the rollback
2952 * @return array Array of errors, each error formatted as
2953 * array(messagekey, param1, param2, ...).
2954 * On success, the array is empty. This array can also be passed to
2955 * OutputPage::showPermissionsErrorPage().
2957 public function doRollback(
2958 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2960 $resultDetails = null;
2962 // Check permissions
2963 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2964 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2965 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2967 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2968 $errors[] = array( 'sessionfailure' );
2971 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2972 $errors[] = array( 'actionthrottledtext' );
2975 // If there were errors, bail out now
2976 if ( !empty( $errors ) ) {
2980 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2984 * Backend implementation of doRollback(), please refer there for parameter
2985 * and return value documentation
2987 * NOTE: This function does NOT check ANY permissions, it just commits the
2988 * rollback to the DB. Therefore, you should only call this function direct-
2989 * ly if you want to use custom permissions checks. If you don't, use
2990 * doRollback() instead.
2991 * @param string $fromP Name of the user whose edits to rollback.
2992 * @param string $summary Custom summary. Set to default summary if empty.
2993 * @param bool $bot If true, mark all reverted edits as bot.
2995 * @param array $resultDetails Contains result-specific array of additional values
2996 * @param User $guser The user performing the rollback
2999 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
3000 global $wgUseRCPatrol, $wgContLang;
3002 $dbw = wfGetDB( DB_MASTER
);
3004 if ( wfReadOnly() ) {
3005 return array( array( 'readonlytext' ) );
3008 // Get the last editor
3009 $current = $this->getRevision();
3010 if ( is_null( $current ) ) {
3011 // Something wrong... no page?
3012 return array( array( 'notanarticle' ) );
3015 $from = str_replace( '_', ' ', $fromP );
3016 // User name given should match up with the top revision.
3017 // If the user was deleted then $from should be empty.
3018 if ( $from != $current->getUserText() ) {
3019 $resultDetails = array( 'current' => $current );
3020 return array( array( 'alreadyrolled',
3021 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3022 htmlspecialchars( $fromP ),
3023 htmlspecialchars( $current->getUserText() )
3027 // Get the last edit not by this person...
3028 // Note: these may not be public values
3029 $user = intval( $current->getUser( Revision
::RAW
) );
3030 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3031 $s = $dbw->selectRow( 'revision',
3032 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3033 array( 'rev_page' => $current->getPage(),
3034 "rev_user != {$user} OR rev_user_text != {$user_text}"
3036 array( 'USE INDEX' => 'page_timestamp',
3037 'ORDER BY' => 'rev_timestamp DESC' )
3039 if ( $s === false ) {
3040 // No one else ever edited this page
3041 return array( array( 'cantrollback' ) );
3042 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3043 ||
$s->rev_deleted
& Revision
::DELETED_USER
3045 // Only admins can see this text
3046 return array( array( 'notvisiblerev' ) );
3049 // Generate the edit summary if necessary
3050 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3051 if ( empty( $summary ) ) {
3052 if ( $from == '' ) { // no public user name
3053 $summary = wfMessage( 'revertpage-nouser' );
3055 $summary = wfMessage( 'revertpage' );
3059 // Allow the custom summary to use the same args as the default message
3061 $target->getUserText(), $from, $s->rev_id
,
3062 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3063 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3065 if ( $summary instanceof Message
) {
3066 $summary = $summary->params( $args )->inContentLanguage()->text();
3068 $summary = wfMsgReplaceArgs( $summary, $args );
3071 // Trim spaces on user supplied text
3072 $summary = trim( $summary );
3074 // Truncate for whole multibyte characters.
3075 $summary = $wgContLang->truncate( $summary, 255 );
3078 $flags = EDIT_UPDATE
;
3080 if ( $guser->isAllowed( 'minoredit' ) ) {
3081 $flags |
= EDIT_MINOR
;
3084 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3085 $flags |
= EDIT_FORCE_BOT
;
3088 // Actually store the edit
3089 $status = $this->doEditContent(
3090 $target->getContent(),
3097 // Set patrolling and bot flag on the edits, which gets rollbacked.
3098 // This is done even on edit failure to have patrolling in that case (bug 62157).
3100 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3101 // Mark all reverted edits as bot
3105 if ( $wgUseRCPatrol ) {
3106 // Mark all reverted edits as patrolled
3107 $set['rc_patrolled'] = 1;
3110 if ( count( $set ) ) {
3111 $dbw->update( 'recentchanges', $set,
3113 'rc_cur_id' => $current->getPage(),
3114 'rc_user_text' => $current->getUserText(),
3115 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3121 if ( !$status->isOK() ) {
3122 return $status->getErrorsArray();
3125 // raise error, when the edit is an edit without a new version
3126 if ( empty( $status->value
['revision'] ) ) {
3127 $resultDetails = array( 'current' => $current );
3128 return array( array( 'alreadyrolled',
3129 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3130 htmlspecialchars( $fromP ),
3131 htmlspecialchars( $current->getUserText() )
3135 $revId = $status->value
['revision']->getId();
3137 Hooks
::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3139 $resultDetails = array(
3140 'summary' => $summary,
3141 'current' => $current,
3142 'target' => $target,
3150 * The onArticle*() functions are supposed to be a kind of hooks
3151 * which should be called whenever any of the specified actions
3154 * This is a good place to put code to clear caches, for instance.
3156 * This is called on page move and undelete, as well as edit
3158 * @param Title $title
3160 public static function onArticleCreate( Title
$title ) {
3161 // Update existence markers on article/talk tabs...
3162 $other = $title->getOtherPage();
3164 $other->purgeSquid();
3166 $title->touchLinks();
3167 $title->purgeSquid();
3168 $title->deleteTitleProtection();
3172 * Clears caches when article is deleted
3174 * @param Title $title
3176 public static function onArticleDelete( Title
$title ) {
3177 // Update existence markers on article/talk tabs...
3178 $other = $title->getOtherPage();
3180 $other->purgeSquid();
3182 $title->touchLinks();
3183 $title->purgeSquid();
3186 HTMLFileCache
::clearFileCache( $title );
3187 InfoAction
::invalidateCache( $title );
3190 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3191 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3195 if ( $title->getNamespace() == NS_FILE
) {
3196 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3197 $update->doUpdate();
3201 if ( $title->getNamespace() == NS_USER_TALK
) {
3202 $user = User
::newFromName( $title->getText(), false );
3204 $user->setNewtalk( false );
3209 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3213 * Purge caches on page update etc
3215 * @param Title $title
3216 * @param Revision|null $revision Revision that was just saved, may be null
3218 public static function onArticleEdit( Title
$title, Revision
$revision = null ) {
3219 // Invalidate caches of articles which include this page
3220 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3222 // Invalidate the caches of all pages which redirect here
3223 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3225 // Purge squid for this page only
3226 $title->purgeSquid();
3228 $revid = $revision ?
$revision->getId() : null;
3229 // Clear file cache for this page only
3230 HTMLFileCache
::clearFileCache( $title );
3231 DeferredUpdates
::addCallableUpdate( function() use ( $title, $revid ) {
3232 InfoAction
::invalidateCache( $title, $revid );
3239 * Returns a list of categories this page is a member of.
3240 * Results will include hidden categories
3242 * @return TitleArray
3244 public function getCategories() {
3245 $id = $this->getId();
3247 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3250 $dbr = wfGetDB( DB_SLAVE
);
3251 $res = $dbr->select( 'categorylinks',
3252 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3253 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3254 // as not being aliases, and NS_CATEGORY is numeric
3255 array( 'cl_from' => $id ),
3258 return TitleArray
::newFromResult( $res );
3262 * Returns a list of hidden categories this page is a member of.
3263 * Uses the page_props and categorylinks tables.
3265 * @return array Array of Title objects
3267 public function getHiddenCategories() {
3269 $id = $this->getId();
3275 $dbr = wfGetDB( DB_SLAVE
);
3276 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3278 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3279 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3282 if ( $res !== false ) {
3283 foreach ( $res as $row ) {
3284 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3292 * Return an applicable autosummary if one exists for the given edit.
3293 * @param string|null $oldtext The previous text of the page.
3294 * @param string|null $newtext The submitted text of the page.
3295 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3296 * @return string An appropriate autosummary, or an empty string.
3298 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3300 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3301 // NOTE: stub for backwards-compatibility. assumes the given text is
3302 // wikitext. will break horribly if it isn't.
3304 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3306 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3307 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3308 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3310 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3314 * Auto-generates a deletion reason
3316 * @param bool &$hasHistory Whether the page has a history
3317 * @return string|bool String containing deletion reason or empty string, or boolean false
3318 * if no revision occurred
3320 public function getAutoDeleteReason( &$hasHistory ) {
3321 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3325 * Update all the appropriate counts in the category table, given that
3326 * we've added the categories $added and deleted the categories $deleted.
3328 * @param array $added The names of categories that were added
3329 * @param array $deleted The names of categories that were deleted
3331 public function updateCategoryCounts( array $added, array $deleted ) {
3333 $method = __METHOD__
;
3334 $dbw = wfGetDB( DB_MASTER
);
3336 // Do this at the end of the commit to reduce lock wait timeouts
3337 $dbw->onTransactionPreCommitOrIdle(
3338 function () use ( $dbw, $that, $method, $added, $deleted ) {
3339 $ns = $that->getTitle()->getNamespace();
3341 $addFields = array( 'cat_pages = cat_pages + 1' );
3342 $removeFields = array( 'cat_pages = cat_pages - 1' );
3343 if ( $ns == NS_CATEGORY
) {
3344 $addFields[] = 'cat_subcats = cat_subcats + 1';
3345 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3346 } elseif ( $ns == NS_FILE
) {
3347 $addFields[] = 'cat_files = cat_files + 1';
3348 $removeFields[] = 'cat_files = cat_files - 1';
3351 if ( count( $added ) ) {
3352 $insertRows = array();
3353 foreach ( $added as $cat ) {
3354 $insertRows[] = array(
3355 'cat_title' => $cat,
3357 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3358 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3364 array( 'cat_title' ),
3370 if ( count( $deleted ) ) {
3374 array( 'cat_title' => $deleted ),
3379 foreach ( $added as $catName ) {
3380 $cat = Category
::newFromName( $catName );
3381 Hooks
::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3384 foreach ( $deleted as $catName ) {
3385 $cat = Category
::newFromName( $catName );
3386 Hooks
::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3393 * Opportunistically enqueue link update jobs given fresh parser output if useful
3395 * @param ParserOutput $parserOutput Current version page output
3398 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3399 if ( wfReadOnly() ) {
3403 if ( !Hooks
::run( 'OpportunisticLinksUpdate', array( $this, $this->mTitle
, $parserOutput ) ) ) {
3407 if ( $this->mTitle
->areRestrictionsCascading() ) {
3408 // If the page is cascade protecting, the links should really be up-to-date
3409 $params = array( 'prioritize' => true );
3410 } elseif ( $parserOutput->hasDynamicContent() ) {
3411 // Assume the output contains time/random based magic words
3414 // If the inclusions are deterministic, the edit-triggered link jobs are enough
3418 // Check if the last link refresh was before page_touched
3419 if ( $this->getLinksTimestamp() < $this->getTouched() ) {
3420 $params['isOpportunistic'] = true;
3421 $params['rootJobTimestamp'] = $parserOutput->getCacheTime();
3423 JobQueueGroup
::singleton()->lazyPush( EnqueueJob
::newFromLocalJobs(
3424 new JobSpecification( 'refreshLinks', $params,
3425 array( 'removeDuplicates' => true ), $this->mTitle
)
3431 * Return a list of templates used by this article.
3432 * Uses the templatelinks table
3434 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3435 * @return array Array of Title objects
3437 public function getUsedTemplates() {
3438 return $this->mTitle
->getTemplateLinksFrom();
3442 * This function is called right before saving the wikitext,
3443 * so we can do things like signatures and links-in-context.
3445 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3446 * @param string $text Article contents
3447 * @param User $user User doing the edit
3448 * @param ParserOptions $popts Parser options, default options for
3449 * the user loaded if null given
3450 * @return string Article contents with altered wikitext markup (signatures
3451 * converted, {{subst:}}, templates, etc.)
3453 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3454 global $wgParser, $wgUser;
3456 wfDeprecated( __METHOD__
, '1.19' );
3458 $user = is_null( $user ) ?
$wgUser : $user;
3460 if ( $popts === null ) {
3461 $popts = ParserOptions
::newFromUser( $user );
3464 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3468 * Update the article's restriction field, and leave a log entry.
3470 * @deprecated since 1.19
3471 * @param array $limit Set of restriction keys
3472 * @param string $reason
3473 * @param int &$cascade Set to false if cascading protection isn't allowed.
3474 * @param array $expiry Per restriction type expiration
3475 * @param User $user The user updating the restrictions
3476 * @return bool True on success
3478 public function updateRestrictions(
3479 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3483 $user = is_null( $user ) ?
$wgUser : $user;
3485 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3489 * Returns a list of updates to be performed when this page is deleted. The
3490 * updates should remove any information about this page from secondary data
3491 * stores such as links tables.
3493 * @param Content|null $content Optional Content object for determining the
3494 * necessary updates.
3495 * @return array An array of DataUpdates objects
3497 public function getDeletionUpdates( Content
$content = null ) {
3499 // load content object, which may be used to determine the necessary updates
3500 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3501 $content = $this->getContent( Revision
::RAW
);
3507 $updates = $content->getDeletionUpdates( $this );
3510 Hooks
::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );